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