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