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