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