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