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