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