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