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