]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bit_mask.rs
Merge remote-tracking branch 'origin/master' into yati_master
[rust.git] / clippy_lints / src / bit_mask.rs
1 use rustc::hir::*;
2 use rustc::hir::def::Def;
3 use rustc::lint::*;
4 use rustc::ty;
5 use rustc_const_eval::lookup_const_by_id;
6 use syntax::ast::LitKind;
7 use syntax::codemap::{Span, DUMMY_SP};
8 use utils::span_lint;
9
10 /// **What it does:** Checks for incompatible bit masks in comparisons.
11 ///
12 /// The formula for detecting if an expression of the type `_ <bit_op> m
13 /// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
14 /// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
15 /// table:
16 ///
17 /// |Comparison  |Bit Op|Example     |is always|Formula               |
18 /// |------------|------|------------|---------|----------------------|
19 /// |`==` or `!=`| `&`  |`x & 2 == 3`|`false`  |`c & m != c`          |
20 /// |`<`  or `>=`| `&`  |`x & 2 < 3` |`true`   |`m < c`               |
21 /// |`>`  or `<=`| `&`  |`x & 1 > 1` |`false`  |`m <= c`              |
22 /// |`==` or `!=`| `|`  |`x | 1 == 0`|`false`  |`c | m != c`          |
23 /// |`<`  or `>=`| `|`  |`x | 1 < 1` |`false`  |`m >= c`              |
24 /// |`<=` or `>` | `|`  |`x | 1 > 0` |`true`   |`m > c`               |
25 ///
26 /// **Why is this bad?** If the bits that the comparison cares about are always
27 /// set to zero or one by the bit mask, the comparison is constant `true` or
28 /// `false` (depending on mask, compared value, and operators).
29 ///
30 /// So the code is actively misleading, and the only reason someone would write
31 /// this intentionally is to win an underhanded Rust contest or create a
32 /// test-case for this lint.
33 ///
34 /// **Known problems:** None.
35 ///
36 /// **Example:**
37 /// ```rust
38 /// if (x & 1 == 2) { … }
39 /// ```
40 declare_lint! {
41     pub BAD_BIT_MASK,
42     Warn,
43     "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
44 }
45
46 /// **What it does:** Checks for bit masks in comparisons which can be removed
47 /// without changing the outcome. The basic structure can be seen in the
48 /// following table:
49 ///
50 /// |Comparison| Bit Op  |Example    |equals |
51 /// |----------|---------|-----------|-------|
52 /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
53 /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
54 ///
55 /// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
56 /// but still a bit misleading, because the bit mask is ineffective.
57 ///
58 /// **Known problems:** False negatives: This lint will only match instances
59 /// where we have figured out the math (which is for a power-of-two compared
60 /// value). This means things like `x | 1 >= 7` (which would be better written
61 /// as `x >= 6`) will not be reported (but bit masks like this are fairly
62 /// uncommon).
63 ///
64 /// **Example:**
65 /// ```rust
66 /// if (x | 1 > 3) { … }
67 /// ```
68 declare_lint! {
69     pub INEFFECTIVE_BIT_MASK,
70     Warn,
71     "expressions where a bit mask will be rendered useless by a comparison, e.g. `(x | 1) > 2`"
72 }
73
74 #[derive(Copy,Clone)]
75 pub struct BitMask;
76
77 impl LintPass for BitMask {
78     fn get_lints(&self) -> LintArray {
79         lint_array!(BAD_BIT_MASK, INEFFECTIVE_BIT_MASK)
80     }
81 }
82
83 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
84     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
85         if let ExprBinary(ref cmp, ref left, ref right) = e.node {
86             if cmp.node.is_comparison() {
87                 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
88                     check_compare(cx, left, cmp.node, cmp_opt, &e.span)
89                 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
90                     check_compare(cx, right, invert_cmp(cmp.node), cmp_val, &e.span)
91                 }
92             }
93         }
94     }
95 }
96
97 fn invert_cmp(cmp: BinOp_) -> BinOp_ {
98     match cmp {
99         BiEq => BiEq,
100         BiNe => BiNe,
101         BiLt => BiGt,
102         BiGt => BiLt,
103         BiLe => BiGe,
104         BiGe => BiLe,
105         _ => BiOr, // Dummy
106     }
107 }
108
109
110 fn check_compare(cx: &LateContext, bit_op: &Expr, cmp_op: BinOp_, cmp_value: u128, span: &Span) {
111     if let ExprBinary(ref op, ref left, ref right) = bit_op.node {
112         if op.node != BiBitAnd && op.node != BiBitOr {
113             return;
114         }
115         fetch_int_literal(cx, right)
116             .or_else(|| fetch_int_literal(cx, left))
117             .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
118     }
119 }
120
121 fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value: u128, cmp_value: u128, span: &Span) {
122     match cmp_op {
123         BiEq | BiNe => {
124             match bit_op {
125                 BiBitAnd => {
126                     if mask_value & cmp_value != cmp_value {
127                         if cmp_value != 0 {
128                             span_lint(cx,
129                                       BAD_BIT_MASK,
130                                       *span,
131                                       &format!("incompatible bit mask: `_ & {}` can never be equal to `{}`",
132                                                mask_value,
133                                                cmp_value));
134                         }
135                     } else if mask_value == 0 {
136                         span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
137                     }
138                 },
139                 BiBitOr => {
140                     if mask_value | cmp_value != cmp_value {
141                         span_lint(cx,
142                                   BAD_BIT_MASK,
143                                   *span,
144                                   &format!("incompatible bit mask: `_ | {}` can never be equal to `{}`",
145                                            mask_value,
146                                            cmp_value));
147                     }
148                 },
149                 _ => (),
150             }
151         },
152         BiLt | BiGe => {
153             match bit_op {
154                 BiBitAnd => {
155                     if mask_value < cmp_value {
156                         span_lint(cx,
157                                   BAD_BIT_MASK,
158                                   *span,
159                                   &format!("incompatible bit mask: `_ & {}` will always be lower than `{}`",
160                                            mask_value,
161                                            cmp_value));
162                     } else if mask_value == 0 {
163                         span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
164                     }
165                 },
166                 BiBitOr => {
167                     if mask_value >= cmp_value {
168                         span_lint(cx,
169                                   BAD_BIT_MASK,
170                                   *span,
171                                   &format!("incompatible bit mask: `_ | {}` will never be lower than `{}`",
172                                            mask_value,
173                                            cmp_value));
174                     } else {
175                         check_ineffective_lt(cx, *span, mask_value, cmp_value, "|");
176                     }
177                 },
178                 BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"),
179                 _ => (),
180             }
181         },
182         BiLe | BiGt => {
183             match bit_op {
184                 BiBitAnd => {
185                     if mask_value <= cmp_value {
186                         span_lint(cx,
187                                   BAD_BIT_MASK,
188                                   *span,
189                                   &format!("incompatible bit mask: `_ & {}` will never be higher than `{}`",
190                                            mask_value,
191                                            cmp_value));
192                     } else if mask_value == 0 {
193                         span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
194                     }
195                 },
196                 BiBitOr => {
197                     if mask_value > cmp_value {
198                         span_lint(cx,
199                                   BAD_BIT_MASK,
200                                   *span,
201                                   &format!("incompatible bit mask: `_ | {}` will always be higher than `{}`",
202                                            mask_value,
203                                            cmp_value));
204                     } else {
205                         check_ineffective_gt(cx, *span, mask_value, cmp_value, "|");
206                     }
207                 },
208                 BiBitXor => check_ineffective_gt(cx, *span, mask_value, cmp_value, "^"),
209                 _ => (),
210             }
211         },
212         _ => (),
213     }
214 }
215
216 fn check_ineffective_lt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
217     if c.is_power_of_two() && m < c {
218         span_lint(cx,
219                   INEFFECTIVE_BIT_MASK,
220                   span,
221                   &format!("ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
222                            op,
223                            m,
224                            c));
225     }
226 }
227
228 fn check_ineffective_gt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
229     if (c + 1).is_power_of_two() && m <= c {
230         span_lint(cx,
231                   INEFFECTIVE_BIT_MASK,
232                   span,
233                   &format!("ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
234                            op,
235                            m,
236                            c));
237     }
238 }
239
240 fn fetch_int_literal(cx: &LateContext, lit: &Expr) -> Option<u128> {
241     use rustc::ty::subst::Substs;
242     match lit.node {
243         ExprLit(ref lit_ptr) => {
244             if let LitKind::Int(value, _) = lit_ptr.node {
245                 Some(value) // TODO: Handle sign
246             } else {
247                 None
248             }
249         },
250         ExprPath(ref qpath) => {
251             let def = cx.tables.qpath_def(qpath, lit.id);
252             if let Def::Const(def_id) = def {
253                 lookup_const_by_id(cx.tcx, def_id, Substs::empty()).and_then(|(l, _ty)| {
254                     let body = if let Some(id) = cx.tcx.hir.as_local_node_id(l) {
255                         ty::queries::mir_const_qualif::get(cx.tcx, DUMMY_SP, def_id);
256                         cx.tcx.hir.body(cx.tcx.hir.body_owned_by(id))
257                     } else {
258                         cx.tcx.sess.cstore.item_body(cx.tcx, def_id)
259                     };
260                     fetch_int_literal(cx, &body.value)
261                 })
262             } else {
263                 None
264             }
265         },
266         _ => None,
267     }
268 }