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