]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/hir_utils.rs
a44f2df2fd631e9793dd022cc50517a48caa7e07
[rust.git] / clippy_utils / src / hir_utils.rs
1 use crate::consts::{constant_context, constant_simple};
2 use crate::differing_macro_contexts;
3 use crate::source::snippet_opt;
4 use rustc_ast::ast::InlineAsmTemplatePiece;
5 use rustc_data_structures::fx::FxHasher;
6 use rustc_hir::def::Res;
7 use rustc_hir::HirIdMap;
8 use rustc_hir::{
9     BinOpKind, Block, BodyId, Expr, ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, Guard, HirId,
10     InlineAsmOperand, Lifetime, LifetimeName, ParamName, Pat, PatField, PatKind, Path, PathSegment, QPath, Stmt,
11     StmtKind, Ty, TyKind, TypeBinding,
12 };
13 use rustc_lexer::{tokenize, TokenKind};
14 use rustc_lint::LateContext;
15 use rustc_middle::ty::TypeckResults;
16 use rustc_span::Symbol;
17 use std::hash::{Hash, Hasher};
18
19 /// Type used to check whether two ast are the same. This is different from the
20 /// operator
21 /// `==` on ast types as this operator would compare true equality with ID and
22 /// span.
23 ///
24 /// Note that some expressions kinds are not considered but could be added.
25 pub struct SpanlessEq<'a, 'tcx> {
26     /// Context used to evaluate constant expressions.
27     cx: &'a LateContext<'tcx>,
28     maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
29     allow_side_effects: bool,
30     expr_fallback: Option<Box<dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a>>,
31 }
32
33 impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
34     pub fn new(cx: &'a LateContext<'tcx>) -> Self {
35         Self {
36             cx,
37             maybe_typeck_results: cx.maybe_typeck_results(),
38             allow_side_effects: true,
39             expr_fallback: None,
40         }
41     }
42
43     /// Consider expressions containing potential side effects as not equal.
44     pub fn deny_side_effects(self) -> Self {
45         Self {
46             allow_side_effects: false,
47             ..self
48         }
49     }
50
51     pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
52         Self {
53             expr_fallback: Some(Box::new(expr_fallback)),
54             ..self
55         }
56     }
57
58     /// Use this method to wrap comparisons that may involve inter-expression context.
59     /// See `self.locals`.
60     pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
61         HirEqInterExpr {
62             inner: self,
63             locals: HirIdMap::default(),
64         }
65     }
66
67     #[allow(dead_code)]
68     pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
69         self.inter_expr().eq_block(left, right)
70     }
71
72     pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
73         self.inter_expr().eq_expr(left, right)
74     }
75
76     pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
77         self.inter_expr().eq_path_segment(left, right)
78     }
79
80     pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
81         self.inter_expr().eq_path_segments(left, right)
82     }
83 }
84
85 pub struct HirEqInterExpr<'a, 'b, 'tcx> {
86     inner: &'a mut SpanlessEq<'b, 'tcx>,
87
88     // When binding are declared, the binding ID in the left expression is mapped to the one on the
89     // right. For example, when comparing `{ let x = 1; x + 2 }` and `{ let y = 1; y + 2 }`,
90     // these blocks are considered equal since `x` is mapped to `y`.
91     locals: HirIdMap<HirId>,
92 }
93
94 impl HirEqInterExpr<'_, '_, '_> {
95     pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
96         match (&left.kind, &right.kind) {
97             (&StmtKind::Local(l), &StmtKind::Local(r)) => {
98                 // This additional check ensures that the type of the locals are equivalent even if the init
99                 // expression or type have some inferred parts.
100                 if let Some(typeck) = self.inner.maybe_typeck_results {
101                     let l_ty = typeck.pat_ty(l.pat);
102                     let r_ty = typeck.pat_ty(r.pat);
103                     if !rustc_middle::ty::TyS::same_type(l_ty, r_ty) {
104                         return false;
105                     }
106                 }
107
108                 // eq_pat adds the HirIds to the locals map. We therefor call it last to make sure that
109                 // these only get added if the init and type is equal.
110                 both(&l.init, &r.init, |l, r| self.eq_expr(l, r))
111                     && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r))
112                     && self.eq_pat(l.pat, r.pat)
113             },
114             (&StmtKind::Expr(l), &StmtKind::Expr(r)) | (&StmtKind::Semi(l), &StmtKind::Semi(r)) => self.eq_expr(l, r),
115             _ => false,
116         }
117     }
118
119     /// Checks whether two blocks are the same.
120     fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
121         match (left.stmts, left.expr, right.stmts, right.expr) {
122             ([], None, [], None) => {
123                 // For empty blocks, check to see if the tokens are equal. This will catch the case where a macro
124                 // expanded to nothing, or the cfg attribute was used.
125                 let (left, right) = match (
126                     snippet_opt(self.inner.cx, left.span),
127                     snippet_opt(self.inner.cx, right.span),
128                 ) {
129                     (Some(left), Some(right)) => (left, right),
130                     _ => return true,
131                 };
132                 let mut left_pos = 0;
133                 let left = tokenize(&left)
134                     .map(|t| {
135                         let end = left_pos + t.len;
136                         let s = &left[left_pos..end];
137                         left_pos = end;
138                         (t, s)
139                     })
140                     .filter(|(t, _)| {
141                         !matches!(
142                             t.kind,
143                             TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
144                         )
145                     })
146                     .map(|(_, s)| s);
147                 let mut right_pos = 0;
148                 let right = tokenize(&right)
149                     .map(|t| {
150                         let end = right_pos + t.len;
151                         let s = &right[right_pos..end];
152                         right_pos = end;
153                         (t, s)
154                     })
155                     .filter(|(t, _)| {
156                         !matches!(
157                             t.kind,
158                             TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
159                         )
160                     })
161                     .map(|(_, s)| s);
162                 left.eq(right)
163             },
164             _ => {
165                 over(left.stmts, right.stmts, |l, r| self.eq_stmt(l, r))
166                     && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
167             },
168         }
169     }
170
171     pub fn eq_body(&mut self, left: BodyId, right: BodyId) -> bool {
172         let cx = self.inner.cx;
173         let eval_const = |body| constant_context(cx, cx.tcx.typeck_body(body)).expr(&cx.tcx.hir().body(body).value);
174         eval_const(left) == eval_const(right)
175     }
176
177     #[allow(clippy::similar_names)]
178     pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
179         if !self.inner.allow_side_effects && differing_macro_contexts(left.span, right.span) {
180             return false;
181         }
182
183         if let Some(typeck_results) = self.inner.maybe_typeck_results {
184             if let (Some(l), Some(r)) = (
185                 constant_simple(self.inner.cx, typeck_results, left),
186                 constant_simple(self.inner.cx, typeck_results, right),
187             ) {
188                 if l == r {
189                     return true;
190                 }
191             }
192         }
193
194         let is_eq = match (
195             &reduce_exprkind(self.inner.cx, &left.kind),
196             &reduce_exprkind(self.inner.cx, &right.kind),
197         ) {
198             (&ExprKind::AddrOf(lb, l_mut, le), &ExprKind::AddrOf(rb, r_mut, re)) => {
199                 lb == rb && l_mut == r_mut && self.eq_expr(le, re)
200             },
201             (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => {
202                 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
203             },
204             (&ExprKind::Assign(ll, lr, _), &ExprKind::Assign(rl, rr, _)) => {
205                 self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
206             },
207             (&ExprKind::AssignOp(ref lo, ll, lr), &ExprKind::AssignOp(ref ro, rl, rr)) => {
208                 self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
209             },
210             (&ExprKind::Block(l, _), &ExprKind::Block(r, _)) => self.eq_block(l, r),
211             (&ExprKind::Binary(l_op, ll, lr), &ExprKind::Binary(r_op, rl, rr)) => {
212                 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
213                     || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
214                         l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
215                     })
216             },
217             (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => {
218                 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
219                     && both(le, re, |l, r| self.eq_expr(l, r))
220             },
221             (&ExprKind::Box(l), &ExprKind::Box(r)) => self.eq_expr(l, r),
222             (&ExprKind::Call(l_fun, l_args), &ExprKind::Call(r_fun, r_args)) => {
223                 self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
224             },
225             (&ExprKind::Cast(lx, lt), &ExprKind::Cast(rx, rt)) | (&ExprKind::Type(lx, lt), &ExprKind::Type(rx, rt)) => {
226                 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
227             },
228             (&ExprKind::Field(l_f_exp, ref l_f_ident), &ExprKind::Field(r_f_exp, ref r_f_ident)) => {
229                 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
230             },
231             (&ExprKind::Index(la, li), &ExprKind::Index(ra, ri)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
232             (&ExprKind::If(lc, lt, ref le), &ExprKind::If(rc, rt, ref re)) => {
233                 self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r))
234             },
235             (&ExprKind::Let(ref lp, ref le, _), &ExprKind::Let(ref rp, ref re, _)) => {
236                 self.eq_pat(lp, rp) && self.eq_expr(le, re)
237             },
238             (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
239             (&ExprKind::Loop(lb, ref ll, ref lls, _), &ExprKind::Loop(rb, ref rl, ref rls, _)) => {
240                 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.name == r.ident.name)
241             },
242             (&ExprKind::Match(le, la, ref ls), &ExprKind::Match(re, ra, ref rs)) => {
243                 ls == rs
244                     && self.eq_expr(le, re)
245                     && over(la, ra, |l, r| {
246                         self.eq_pat(l.pat, r.pat)
247                             && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
248                             && self.eq_expr(l.body, r.body)
249                     })
250             },
251             (&ExprKind::MethodCall(l_path, _, l_args, _), &ExprKind::MethodCall(r_path, _, r_args, _)) => {
252                 self.inner.allow_side_effects && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
253             },
254             (&ExprKind::Repeat(le, ref ll_id), &ExprKind::Repeat(re, ref rl_id)) => {
255                 self.eq_expr(le, re) && self.eq_body(ll_id.body, rl_id.body)
256             },
257             (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
258             (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
259             (&ExprKind::Struct(l_path, lf, ref lo), &ExprKind::Struct(r_path, rf, ref ro)) => {
260                 self.eq_qpath(l_path, r_path)
261                     && both(lo, ro, |l, r| self.eq_expr(l, r))
262                     && over(lf, rf, |l, r| self.eq_expr_field(l, r))
263             },
264             (&ExprKind::Tup(l_tup), &ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
265             (&ExprKind::Unary(l_op, le), &ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
266             (&ExprKind::Array(l), &ExprKind::Array(r)) => self.eq_exprs(l, r),
267             (&ExprKind::DropTemps(le), &ExprKind::DropTemps(re)) => self.eq_expr(le, re),
268             _ => false,
269         };
270         is_eq || self.inner.expr_fallback.as_mut().map_or(false, |f| f(left, right))
271     }
272
273     fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
274         over(left, right, |l, r| self.eq_expr(l, r))
275     }
276
277     fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
278         left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
279     }
280
281     fn eq_guard(&mut self, left: &Guard<'_>, right: &Guard<'_>) -> bool {
282         match (left, right) {
283             (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
284             (Guard::IfLet(lp, le), Guard::IfLet(rp, re)) => self.eq_pat(lp, rp) && self.eq_expr(le, re),
285             _ => false,
286         }
287     }
288
289     fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
290         match (left, right) {
291             (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_body(l.value.body, r.value.body),
292             (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
293             (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
294             (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
295             _ => false,
296         }
297     }
298
299     fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
300         left.name == right.name
301     }
302
303     fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
304         let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
305         li.name == ri.name && self.eq_pat(lp, rp)
306     }
307
308     /// Checks whether two patterns are the same.
309     fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
310         match (&left.kind, &right.kind) {
311             (&PatKind::Box(l), &PatKind::Box(r)) => self.eq_pat(l, r),
312             (&PatKind::Struct(ref lp, la, ..), &PatKind::Struct(ref rp, ra, ..)) => {
313                 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
314             },
315             (&PatKind::TupleStruct(ref lp, la, ls), &PatKind::TupleStruct(ref rp, ra, rs)) => {
316                 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
317             },
318             (&PatKind::Binding(lb, li, _, ref lp), &PatKind::Binding(rb, ri, _, ref rp)) => {
319                 let eq = lb == rb && both(lp, rp, |l, r| self.eq_pat(l, r));
320                 if eq {
321                     self.locals.insert(li, ri);
322                 }
323                 eq
324             },
325             (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
326             (&PatKind::Lit(l), &PatKind::Lit(r)) => self.eq_expr(l, r),
327             (&PatKind::Tuple(l, ls), &PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
328             (&PatKind::Range(ref ls, ref le, li), &PatKind::Range(ref rs, ref re, ri)) => {
329                 both(ls, rs, |a, b| self.eq_expr(a, b)) && both(le, re, |a, b| self.eq_expr(a, b)) && (li == ri)
330             },
331             (&PatKind::Ref(le, ref lm), &PatKind::Ref(re, ref rm)) => lm == rm && self.eq_pat(le, re),
332             (&PatKind::Slice(ls, ref li, le), &PatKind::Slice(rs, ref ri, re)) => {
333                 over(ls, rs, |l, r| self.eq_pat(l, r))
334                     && over(le, re, |l, r| self.eq_pat(l, r))
335                     && both(li, ri, |l, r| self.eq_pat(l, r))
336             },
337             (&PatKind::Wild, &PatKind::Wild) => true,
338             _ => false,
339         }
340     }
341
342     #[allow(clippy::similar_names)]
343     fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
344         match (left, right) {
345             (&QPath::Resolved(ref lty, lpath), &QPath::Resolved(ref rty, rpath)) => {
346                 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
347             },
348             (&QPath::TypeRelative(lty, lseg), &QPath::TypeRelative(rty, rseg)) => {
349                 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
350             },
351             (&QPath::LangItem(llang_item, _), &QPath::LangItem(rlang_item, _)) => llang_item == rlang_item,
352             _ => false,
353         }
354     }
355
356     fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
357         match (left.res, right.res) {
358             (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
359             (Res::Local(_), _) | (_, Res::Local(_)) => false,
360             _ => over(left.segments, right.segments, |l, r| self.eq_path_segment(l, r)),
361         }
362     }
363
364     fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
365         if !(left.parenthesized || right.parenthesized) {
366             over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
367                 && over(left.bindings, right.bindings, |l, r| self.eq_type_binding(l, r))
368         } else if left.parenthesized && right.parenthesized {
369             over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
370                 && both(&Some(&left.bindings[0].ty()), &Some(&right.bindings[0].ty()), |l, r| {
371                     self.eq_ty(l, r)
372                 })
373         } else {
374             false
375         }
376     }
377
378     pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
379         left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
380     }
381
382     pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
383         // The == of idents doesn't work with different contexts,
384         // we have to be explicit about hygiene
385         left.ident.name == right.ident.name && both(&left.args, &right.args, |l, r| self.eq_path_parameters(l, r))
386     }
387
388     #[allow(clippy::similar_names)]
389     fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
390         match (&left.kind, &right.kind) {
391             (&TyKind::Slice(l_vec), &TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
392             (&TyKind::Array(lt, ref ll_id), &TyKind::Array(rt, ref rl_id)) => {
393                 self.eq_ty(lt, rt) && self.eq_body(ll_id.body, rl_id.body)
394             },
395             (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
396                 l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty)
397             },
398             (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
399                 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
400             },
401             (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
402             (&TyKind::Tup(l), &TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
403             (&TyKind::Infer, &TyKind::Infer) => true,
404             _ => false,
405         }
406     }
407
408     fn eq_type_binding(&mut self, left: &TypeBinding<'_>, right: &TypeBinding<'_>) -> bool {
409         left.ident.name == right.ident.name && self.eq_ty(left.ty(), right.ty())
410     }
411 }
412
413 /// Some simple reductions like `{ return }` => `return`
414 fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
415     if let ExprKind::Block(block, _) = kind {
416         match (block.stmts, block.expr) {
417             // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
418             // block with an empty span.
419             ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
420             // `{}` => `()`
421             ([], None) => match snippet_opt(cx, block.span) {
422                 // Don't reduce if there are any tokens contained in the braces
423                 Some(snip)
424                     if tokenize(&snip)
425                         .map(|t| t.kind)
426                         .filter(|t| {
427                             !matches!(
428                                 t,
429                                 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
430                             )
431                         })
432                         .ne([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied()) =>
433                 {
434                     kind
435                 },
436                 _ => &ExprKind::Tup(&[]),
437             },
438             ([], Some(expr)) => match expr.kind {
439                 // `{ return .. }` => `return ..`
440                 ExprKind::Ret(..) => &expr.kind,
441                 _ => kind,
442             },
443             ([stmt], None) => match stmt.kind {
444                 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
445                     // `{ return ..; }` => `return ..`
446                     ExprKind::Ret(..) => &expr.kind,
447                     _ => kind,
448                 },
449                 _ => kind,
450             },
451             _ => kind,
452         }
453     } else {
454         kind
455     }
456 }
457
458 fn swap_binop<'a>(
459     binop: BinOpKind,
460     lhs: &'a Expr<'a>,
461     rhs: &'a Expr<'a>,
462 ) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
463     match binop {
464         BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
465             Some((binop, rhs, lhs))
466         },
467         BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
468         BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
469         BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
470         BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
471         BinOpKind::Mul // Not always commutative, e.g. with matrices. See issue #5698
472         | BinOpKind::Shl
473         | BinOpKind::Shr
474         | BinOpKind::Rem
475         | BinOpKind::Sub
476         | BinOpKind::Div
477         | BinOpKind::And
478         | BinOpKind::Or => None,
479     }
480 }
481
482 /// Checks if the two `Option`s are both `None` or some equal values as per
483 /// `eq_fn`.
484 pub fn both<X>(l: &Option<X>, r: &Option<X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
485     l.as_ref()
486         .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
487 }
488
489 /// Checks if two slices are equal as per `eq_fn`.
490 pub fn over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
491     left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
492 }
493
494 /// Counts how many elements of the slices are equal as per `eq_fn`.
495 pub fn count_eq<X: Sized>(
496     left: &mut dyn Iterator<Item = X>,
497     right: &mut dyn Iterator<Item = X>,
498     mut eq_fn: impl FnMut(&X, &X) -> bool,
499 ) -> usize {
500     left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
501 }
502
503 /// Checks if two expressions evaluate to the same value, and don't contain any side effects.
504 pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
505     SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
506 }
507
508 /// Type used to hash an ast element. This is different from the `Hash` trait
509 /// on ast types as this
510 /// trait would consider IDs and spans.
511 ///
512 /// All expressions kind are hashed, but some might have a weaker hash.
513 pub struct SpanlessHash<'a, 'tcx> {
514     /// Context used to evaluate constant expressions.
515     cx: &'a LateContext<'tcx>,
516     maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
517     s: FxHasher,
518 }
519
520 impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
521     pub fn new(cx: &'a LateContext<'tcx>) -> Self {
522         Self {
523             cx,
524             maybe_typeck_results: cx.maybe_typeck_results(),
525             s: FxHasher::default(),
526         }
527     }
528
529     pub fn finish(self) -> u64 {
530         self.s.finish()
531     }
532
533     pub fn hash_block(&mut self, b: &Block<'_>) {
534         for s in b.stmts {
535             self.hash_stmt(s);
536         }
537
538         if let Some(e) = b.expr {
539             self.hash_expr(e);
540         }
541
542         std::mem::discriminant(&b.rules).hash(&mut self.s);
543     }
544
545     #[allow(clippy::many_single_char_names, clippy::too_many_lines)]
546     pub fn hash_expr(&mut self, e: &Expr<'_>) {
547         let simple_const = self
548             .maybe_typeck_results
549             .and_then(|typeck_results| constant_simple(self.cx, typeck_results, e));
550
551         // const hashing may result in the same hash as some unrelated node, so add a sort of
552         // discriminant depending on which path we're choosing next
553         simple_const.hash(&mut self.s);
554         if simple_const.is_some() {
555             return;
556         }
557
558         std::mem::discriminant(&e.kind).hash(&mut self.s);
559
560         match e.kind {
561             ExprKind::AddrOf(kind, m, e) => {
562                 std::mem::discriminant(&kind).hash(&mut self.s);
563                 m.hash(&mut self.s);
564                 self.hash_expr(e);
565             },
566             ExprKind::Continue(i) => {
567                 if let Some(i) = i.label {
568                     self.hash_name(i.ident.name);
569                 }
570             },
571             ExprKind::Assign(l, r, _) => {
572                 self.hash_expr(l);
573                 self.hash_expr(r);
574             },
575             ExprKind::AssignOp(ref o, l, r) => {
576                 std::mem::discriminant(&o.node).hash(&mut self.s);
577                 self.hash_expr(l);
578                 self.hash_expr(r);
579             },
580             ExprKind::Block(b, _) => {
581                 self.hash_block(b);
582             },
583             ExprKind::Binary(op, l, r) => {
584                 std::mem::discriminant(&op.node).hash(&mut self.s);
585                 self.hash_expr(l);
586                 self.hash_expr(r);
587             },
588             ExprKind::Break(i, ref j) => {
589                 if let Some(i) = i.label {
590                     self.hash_name(i.ident.name);
591                 }
592                 if let Some(j) = *j {
593                     self.hash_expr(&*j);
594                 }
595             },
596             ExprKind::Box(e) | ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
597                 self.hash_expr(e);
598             },
599             ExprKind::Call(fun, args) => {
600                 self.hash_expr(fun);
601                 self.hash_exprs(args);
602             },
603             ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
604                 self.hash_expr(e);
605                 self.hash_ty(ty);
606             },
607             ExprKind::Closure(cap, _, eid, _, _) => {
608                 std::mem::discriminant(&cap).hash(&mut self.s);
609                 // closures inherit TypeckResults
610                 self.hash_expr(&self.cx.tcx.hir().body(eid).value);
611             },
612             ExprKind::Field(e, ref f) => {
613                 self.hash_expr(e);
614                 self.hash_name(f.name);
615             },
616             ExprKind::Index(a, i) => {
617                 self.hash_expr(a);
618                 self.hash_expr(i);
619             },
620             ExprKind::InlineAsm(asm) => {
621                 for piece in asm.template {
622                     match piece {
623                         InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
624                         InlineAsmTemplatePiece::Placeholder {
625                             operand_idx,
626                             modifier,
627                             span: _,
628                         } => {
629                             operand_idx.hash(&mut self.s);
630                             modifier.hash(&mut self.s);
631                         },
632                     }
633                 }
634                 asm.options.hash(&mut self.s);
635                 for (op, _op_sp) in asm.operands {
636                     match op {
637                         InlineAsmOperand::In { reg, expr } => {
638                             reg.hash(&mut self.s);
639                             self.hash_expr(expr);
640                         },
641                         InlineAsmOperand::Out { reg, late, expr } => {
642                             reg.hash(&mut self.s);
643                             late.hash(&mut self.s);
644                             if let Some(expr) = expr {
645                                 self.hash_expr(expr);
646                             }
647                         },
648                         InlineAsmOperand::InOut { reg, late, expr } => {
649                             reg.hash(&mut self.s);
650                             late.hash(&mut self.s);
651                             self.hash_expr(expr);
652                         },
653                         InlineAsmOperand::SplitInOut {
654                             reg,
655                             late,
656                             in_expr,
657                             out_expr,
658                         } => {
659                             reg.hash(&mut self.s);
660                             late.hash(&mut self.s);
661                             self.hash_expr(in_expr);
662                             if let Some(out_expr) = out_expr {
663                                 self.hash_expr(out_expr);
664                             }
665                         },
666                         InlineAsmOperand::Const { anon_const } => self.hash_body(anon_const.body),
667                         InlineAsmOperand::Sym { expr } => self.hash_expr(expr),
668                     }
669                 }
670             },
671             ExprKind::Let(ref pat, ref expr, _) => {
672                 self.hash_expr(expr);
673                 self.hash_pat(pat);
674             },
675             ExprKind::LlvmInlineAsm(..) | ExprKind::Err => {},
676             ExprKind::Lit(ref l) => {
677                 l.node.hash(&mut self.s);
678             },
679             ExprKind::Loop(b, ref i, ..) => {
680                 self.hash_block(b);
681                 if let Some(i) = *i {
682                     self.hash_name(i.ident.name);
683                 }
684             },
685             ExprKind::If(cond, then, ref else_opt) => {
686                 self.hash_expr(cond);
687                 self.hash_expr(then);
688                 if let Some(e) = *else_opt {
689                     self.hash_expr(e);
690                 }
691             },
692             ExprKind::Match(e, arms, ref s) => {
693                 self.hash_expr(e);
694
695                 for arm in arms {
696                     self.hash_pat(arm.pat);
697                     if let Some(ref e) = arm.guard {
698                         self.hash_guard(e);
699                     }
700                     self.hash_expr(arm.body);
701                 }
702
703                 s.hash(&mut self.s);
704             },
705             ExprKind::MethodCall(path, ref _tys, args, ref _fn_span) => {
706                 self.hash_name(path.ident.name);
707                 self.hash_exprs(args);
708             },
709             ExprKind::ConstBlock(ref l_id) => {
710                 self.hash_body(l_id.body);
711             },
712             ExprKind::Repeat(e, ref l_id) => {
713                 self.hash_expr(e);
714                 self.hash_body(l_id.body);
715             },
716             ExprKind::Ret(ref e) => {
717                 if let Some(e) = *e {
718                     self.hash_expr(e);
719                 }
720             },
721             ExprKind::Path(ref qpath) => {
722                 self.hash_qpath(qpath);
723             },
724             ExprKind::Struct(path, fields, ref expr) => {
725                 self.hash_qpath(path);
726
727                 for f in fields {
728                     self.hash_name(f.ident.name);
729                     self.hash_expr(f.expr);
730                 }
731
732                 if let Some(e) = *expr {
733                     self.hash_expr(e);
734                 }
735             },
736             ExprKind::Tup(tup) => {
737                 self.hash_exprs(tup);
738             },
739             ExprKind::Array(v) => {
740                 self.hash_exprs(v);
741             },
742             ExprKind::Unary(lop, le) => {
743                 std::mem::discriminant(&lop).hash(&mut self.s);
744                 self.hash_expr(le);
745             },
746         }
747     }
748
749     pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
750         for e in e {
751             self.hash_expr(e);
752         }
753     }
754
755     pub fn hash_name(&mut self, n: Symbol) {
756         n.hash(&mut self.s);
757     }
758
759     pub fn hash_qpath(&mut self, p: &QPath<'_>) {
760         match *p {
761             QPath::Resolved(_, path) => {
762                 self.hash_path(path);
763             },
764             QPath::TypeRelative(_, path) => {
765                 self.hash_name(path.ident.name);
766             },
767             QPath::LangItem(lang_item, ..) => {
768                 std::mem::discriminant(&lang_item).hash(&mut self.s);
769             },
770         }
771         // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
772     }
773
774     pub fn hash_pat(&mut self, pat: &Pat<'_>) {
775         std::mem::discriminant(&pat.kind).hash(&mut self.s);
776         match pat.kind {
777             PatKind::Binding(ann, _, _, pat) => {
778                 std::mem::discriminant(&ann).hash(&mut self.s);
779                 if let Some(pat) = pat {
780                     self.hash_pat(pat);
781                 }
782             },
783             PatKind::Box(pat) => self.hash_pat(pat),
784             PatKind::Lit(expr) => self.hash_expr(expr),
785             PatKind::Or(pats) => {
786                 for pat in pats {
787                     self.hash_pat(pat);
788                 }
789             },
790             PatKind::Path(ref qpath) => self.hash_qpath(qpath),
791             PatKind::Range(s, e, i) => {
792                 if let Some(s) = s {
793                     self.hash_expr(s);
794                 }
795                 if let Some(e) = e {
796                     self.hash_expr(e);
797                 }
798                 std::mem::discriminant(&i).hash(&mut self.s);
799             },
800             PatKind::Ref(pat, mu) => {
801                 self.hash_pat(pat);
802                 std::mem::discriminant(&mu).hash(&mut self.s);
803             },
804             PatKind::Slice(l, m, r) => {
805                 for pat in l {
806                     self.hash_pat(pat);
807                 }
808                 if let Some(pat) = m {
809                     self.hash_pat(pat);
810                 }
811                 for pat in r {
812                     self.hash_pat(pat);
813                 }
814             },
815             PatKind::Struct(ref qpath, fields, e) => {
816                 self.hash_qpath(qpath);
817                 for f in fields {
818                     self.hash_name(f.ident.name);
819                     self.hash_pat(f.pat);
820                 }
821                 e.hash(&mut self.s);
822             },
823             PatKind::Tuple(pats, e) => {
824                 for pat in pats {
825                     self.hash_pat(pat);
826                 }
827                 e.hash(&mut self.s);
828             },
829             PatKind::TupleStruct(ref qpath, pats, e) => {
830                 self.hash_qpath(qpath);
831                 for pat in pats {
832                     self.hash_pat(pat);
833                 }
834                 e.hash(&mut self.s);
835             },
836             PatKind::Wild => {},
837         }
838     }
839
840     pub fn hash_path(&mut self, path: &Path<'_>) {
841         match path.res {
842             // constant hash since equality is dependant on inter-expression context
843             Res::Local(_) => 1_usize.hash(&mut self.s),
844             _ => {
845                 for seg in path.segments {
846                     self.hash_name(seg.ident.name);
847                     self.hash_generic_args(seg.args().args);
848                 }
849             },
850         }
851     }
852
853     pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
854         std::mem::discriminant(&b.kind).hash(&mut self.s);
855
856         match &b.kind {
857             StmtKind::Local(local) => {
858                 self.hash_pat(local.pat);
859                 if let Some(init) = local.init {
860                     self.hash_expr(init);
861                 }
862             },
863             StmtKind::Item(..) => {},
864             StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
865                 self.hash_expr(expr);
866             },
867         }
868     }
869
870     pub fn hash_guard(&mut self, g: &Guard<'_>) {
871         match g {
872             Guard::If(expr) | Guard::IfLet(_, expr) => {
873                 self.hash_expr(expr);
874             },
875         }
876     }
877
878     pub fn hash_lifetime(&mut self, lifetime: Lifetime) {
879         std::mem::discriminant(&lifetime.name).hash(&mut self.s);
880         if let LifetimeName::Param(ref name) = lifetime.name {
881             std::mem::discriminant(name).hash(&mut self.s);
882             match name {
883                 ParamName::Plain(ref ident) => {
884                     ident.name.hash(&mut self.s);
885                 },
886                 ParamName::Fresh(ref size) => {
887                     size.hash(&mut self.s);
888                 },
889                 ParamName::Error => {},
890             }
891         }
892     }
893
894     pub fn hash_ty(&mut self, ty: &Ty<'_>) {
895         std::mem::discriminant(&ty.kind).hash(&mut self.s);
896         self.hash_tykind(&ty.kind);
897     }
898
899     pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
900         match ty {
901             TyKind::Slice(ty) => {
902                 self.hash_ty(ty);
903             },
904             TyKind::Array(ty, anon_const) => {
905                 self.hash_ty(ty);
906                 self.hash_body(anon_const.body);
907             },
908             TyKind::Ptr(ref mut_ty) => {
909                 self.hash_ty(mut_ty.ty);
910                 mut_ty.mutbl.hash(&mut self.s);
911             },
912             TyKind::Rptr(lifetime, ref mut_ty) => {
913                 self.hash_lifetime(*lifetime);
914                 self.hash_ty(mut_ty.ty);
915                 mut_ty.mutbl.hash(&mut self.s);
916             },
917             TyKind::BareFn(bfn) => {
918                 bfn.unsafety.hash(&mut self.s);
919                 bfn.abi.hash(&mut self.s);
920                 for arg in bfn.decl.inputs {
921                     self.hash_ty(arg);
922                 }
923                 std::mem::discriminant(&bfn.decl.output).hash(&mut self.s);
924                 match bfn.decl.output {
925                     FnRetTy::DefaultReturn(_) => {},
926                     FnRetTy::Return(ty) => {
927                         self.hash_ty(ty);
928                     },
929                 }
930                 bfn.decl.c_variadic.hash(&mut self.s);
931             },
932             TyKind::Tup(ty_list) => {
933                 for ty in *ty_list {
934                     self.hash_ty(ty);
935                 }
936             },
937             TyKind::Path(ref qpath) => self.hash_qpath(qpath),
938             TyKind::OpaqueDef(_, arg_list) => {
939                 self.hash_generic_args(arg_list);
940             },
941             TyKind::TraitObject(_, lifetime, _) => {
942                 self.hash_lifetime(*lifetime);
943             },
944             TyKind::Typeof(anon_const) => {
945                 self.hash_body(anon_const.body);
946             },
947             TyKind::Err | TyKind::Infer | TyKind::Never => {},
948         }
949     }
950
951     pub fn hash_body(&mut self, body_id: BodyId) {
952         // swap out TypeckResults when hashing a body
953         let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
954         self.hash_expr(&self.cx.tcx.hir().body(body_id).value);
955         self.maybe_typeck_results = old_maybe_typeck_results;
956     }
957
958     fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
959         for arg in arg_list {
960             match *arg {
961                 GenericArg::Lifetime(l) => self.hash_lifetime(l),
962                 GenericArg::Type(ref ty) => self.hash_ty(ty),
963                 GenericArg::Const(ref ca) => self.hash_body(ca.value.body),
964                 GenericArg::Infer(ref inf) => self.hash_ty(&inf.to_ty()),
965             }
966         }
967     }
968 }