1 use crate::consts::{constant_context, constant_simple};
2 use crate::differing_macro_contexts;
3 use crate::source::snippet_opt;
4 use rustc_ast::ast::InlineAsmTemplatePiece;
5 use rustc_data_structures::fx::FxHasher;
6 use rustc_hir::def::Res;
7 use rustc_hir::HirIdMap;
9 BinOpKind, Block, BodyId, Expr, ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, Guard, HirId,
10 InlineAsmOperand, Lifetime, LifetimeName, ParamName, Pat, PatField, PatKind, Path, PathSegment, QPath, Stmt,
11 StmtKind, Ty, TyKind, TypeBinding,
13 use rustc_lexer::{tokenize, TokenKind};
14 use rustc_lint::LateContext;
15 use rustc_middle::ty::TypeckResults;
16 use rustc_span::Symbol;
17 use std::hash::{Hash, Hasher};
19 /// Type used to check whether two ast are the same. This is different from the
21 /// `==` on ast types as this operator would compare true equality with ID and
24 /// Note that some expressions kinds are not considered but could be added.
25 pub struct SpanlessEq<'a, 'tcx> {
26 /// Context used to evaluate constant expressions.
27 cx: &'a LateContext<'tcx>,
28 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
29 allow_side_effects: bool,
30 expr_fallback: Option<Box<dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a>>,
33 impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
34 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
37 maybe_typeck_results: cx.maybe_typeck_results(),
38 allow_side_effects: true,
43 /// Consider expressions containing potential side effects as not equal.
44 pub fn deny_side_effects(self) -> Self {
46 allow_side_effects: false,
51 pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
53 expr_fallback: Some(Box::new(expr_fallback)),
58 /// Use this method to wrap comparisons that may involve inter-expression context.
59 /// See `self.locals`.
60 pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
63 locals: HirIdMap::default(),
68 pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
69 self.inter_expr().eq_block(left, right)
72 pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
73 self.inter_expr().eq_expr(left, right)
76 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
77 self.inter_expr().eq_path_segment(left, right)
80 pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
81 self.inter_expr().eq_path_segments(left, right)
85 pub struct HirEqInterExpr<'a, 'b, 'tcx> {
86 inner: &'a mut SpanlessEq<'b, 'tcx>,
88 // When binding are declared, the binding ID in the left expression is mapped to the one on the
89 // right. For example, when comparing `{ let x = 1; x + 2 }` and `{ let y = 1; y + 2 }`,
90 // these blocks are considered equal since `x` is mapped to `y`.
91 locals: HirIdMap<HirId>,
94 impl HirEqInterExpr<'_, '_, '_> {
95 pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
96 match (&left.kind, &right.kind) {
97 (&StmtKind::Local(l), &StmtKind::Local(r)) => {
98 // This additional check ensures that the type of the locals are equivalent even if the init
99 // expression or type have some inferred parts.
100 if let Some(typeck) = self.inner.maybe_typeck_results {
101 let l_ty = typeck.pat_ty(l.pat);
102 let r_ty = typeck.pat_ty(r.pat);
103 if !rustc_middle::ty::TyS::same_type(l_ty, r_ty) {
108 // eq_pat adds the HirIds to the locals map. We therefor call it last to make sure that
109 // these only get added if the init and type is equal.
110 both(&l.init, &r.init, |l, r| self.eq_expr(l, r))
111 && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r))
112 && self.eq_pat(l.pat, r.pat)
114 (&StmtKind::Expr(l), &StmtKind::Expr(r)) | (&StmtKind::Semi(l), &StmtKind::Semi(r)) => self.eq_expr(l, r),
119 /// Checks whether two blocks are the same.
120 fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
121 match (left.stmts, left.expr, right.stmts, right.expr) {
122 ([], None, [], None) => {
123 // For empty blocks, check to see if the tokens are equal. This will catch the case where a macro
124 // expanded to nothing, or the cfg attribute was used.
125 let (left, right) = match (
126 snippet_opt(self.inner.cx, left.span),
127 snippet_opt(self.inner.cx, right.span),
129 (Some(left), Some(right)) => (left, right),
132 let mut left_pos = 0;
133 let left = tokenize(&left)
135 let end = left_pos + t.len;
136 let s = &left[left_pos..end];
143 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
147 let mut right_pos = 0;
148 let right = tokenize(&right)
150 let end = right_pos + t.len;
151 let s = &right[right_pos..end];
158 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
165 over(left.stmts, right.stmts, |l, r| self.eq_stmt(l, r))
166 && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
171 #[allow(clippy::similar_names)]
172 pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
173 if !self.inner.allow_side_effects && differing_macro_contexts(left.span, right.span) {
177 if let Some(typeck_results) = self.inner.maybe_typeck_results {
178 if let (Some(l), Some(r)) = (
179 constant_simple(self.inner.cx, typeck_results, left),
180 constant_simple(self.inner.cx, typeck_results, right),
189 &reduce_exprkind(self.inner.cx, &left.kind),
190 &reduce_exprkind(self.inner.cx, &right.kind),
192 (&ExprKind::AddrOf(lb, l_mut, le), &ExprKind::AddrOf(rb, r_mut, re)) => {
193 lb == rb && l_mut == r_mut && self.eq_expr(le, re)
195 (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => {
196 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
198 (&ExprKind::Assign(ll, lr, _), &ExprKind::Assign(rl, rr, _)) => {
199 self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
201 (&ExprKind::AssignOp(ref lo, ll, lr), &ExprKind::AssignOp(ref ro, rl, rr)) => {
202 self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
204 (&ExprKind::Block(l, _), &ExprKind::Block(r, _)) => self.eq_block(l, r),
205 (&ExprKind::Binary(l_op, ll, lr), &ExprKind::Binary(r_op, rl, rr)) => {
206 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
207 || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
208 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
211 (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => {
212 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
213 && both(le, re, |l, r| self.eq_expr(l, r))
215 (&ExprKind::Box(l), &ExprKind::Box(r)) => self.eq_expr(l, r),
216 (&ExprKind::Call(l_fun, l_args), &ExprKind::Call(r_fun, r_args)) => {
217 self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
219 (&ExprKind::Cast(lx, lt), &ExprKind::Cast(rx, rt)) | (&ExprKind::Type(lx, lt), &ExprKind::Type(rx, rt)) => {
220 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
222 (&ExprKind::Field(l_f_exp, ref l_f_ident), &ExprKind::Field(r_f_exp, ref r_f_ident)) => {
223 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
225 (&ExprKind::Index(la, li), &ExprKind::Index(ra, ri)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
226 (&ExprKind::If(lc, lt, ref le), &ExprKind::If(rc, rt, ref re)) => {
227 self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r))
229 (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
230 (&ExprKind::Loop(lb, ref ll, ref lls, _), &ExprKind::Loop(rb, ref rl, ref rls, _)) => {
231 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.name == r.ident.name)
233 (&ExprKind::Match(le, la, ref ls), &ExprKind::Match(re, ra, ref rs)) => {
235 && self.eq_expr(le, re)
236 && over(la, ra, |l, r| {
237 self.eq_pat(l.pat, r.pat)
238 && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
239 && self.eq_expr(l.body, r.body)
242 (&ExprKind::MethodCall(l_path, _, l_args, _), &ExprKind::MethodCall(r_path, _, r_args, _)) => {
243 self.inner.allow_side_effects && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
245 (&ExprKind::Repeat(le, ref ll_id), &ExprKind::Repeat(re, ref rl_id)) => {
246 let mut celcx = constant_context(self.inner.cx, self.inner.cx.tcx.typeck_body(ll_id.body));
247 let ll = celcx.expr(&self.inner.cx.tcx.hir().body(ll_id.body).value);
248 let mut celcx = constant_context(self.inner.cx, self.inner.cx.tcx.typeck_body(rl_id.body));
249 let rl = celcx.expr(&self.inner.cx.tcx.hir().body(rl_id.body).value);
251 self.eq_expr(le, re) && ll == rl
253 (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
254 (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
255 (&ExprKind::Struct(l_path, lf, ref lo), &ExprKind::Struct(r_path, rf, ref ro)) => {
256 self.eq_qpath(l_path, r_path)
257 && both(lo, ro, |l, r| self.eq_expr(l, r))
258 && over(lf, rf, |l, r| self.eq_expr_field(l, r))
260 (&ExprKind::Tup(l_tup), &ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
261 (&ExprKind::Unary(l_op, le), &ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
262 (&ExprKind::Array(l), &ExprKind::Array(r)) => self.eq_exprs(l, r),
263 (&ExprKind::DropTemps(le), &ExprKind::DropTemps(re)) => self.eq_expr(le, re),
266 is_eq || self.inner.expr_fallback.as_mut().map_or(false, |f| f(left, right))
269 fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
270 over(left, right, |l, r| self.eq_expr(l, r))
273 fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
274 left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
277 fn eq_guard(&mut self, left: &Guard<'_>, right: &Guard<'_>) -> bool {
278 match (left, right) {
279 (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
280 (Guard::IfLet(lp, le), Guard::IfLet(rp, re)) => self.eq_pat(lp, rp) && self.eq_expr(le, re),
285 fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
286 match (left, right) {
287 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
288 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
293 fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
294 left.name == right.name
297 fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
298 let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
299 li.name == ri.name && self.eq_pat(lp, rp)
302 /// Checks whether two patterns are the same.
303 fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
304 match (&left.kind, &right.kind) {
305 (&PatKind::Box(l), &PatKind::Box(r)) => self.eq_pat(l, r),
306 (&PatKind::Struct(ref lp, la, ..), &PatKind::Struct(ref rp, ra, ..)) => {
307 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
309 (&PatKind::TupleStruct(ref lp, la, ls), &PatKind::TupleStruct(ref rp, ra, rs)) => {
310 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
312 (&PatKind::Binding(lb, li, _, ref lp), &PatKind::Binding(rb, ri, _, ref rp)) => {
313 let eq = lb == rb && both(lp, rp, |l, r| self.eq_pat(l, r));
315 self.locals.insert(li, ri);
319 (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
320 (&PatKind::Lit(l), &PatKind::Lit(r)) => self.eq_expr(l, r),
321 (&PatKind::Tuple(l, ls), &PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
322 (&PatKind::Range(ref ls, ref le, li), &PatKind::Range(ref rs, ref re, ri)) => {
323 both(ls, rs, |a, b| self.eq_expr(a, b)) && both(le, re, |a, b| self.eq_expr(a, b)) && (li == ri)
325 (&PatKind::Ref(le, ref lm), &PatKind::Ref(re, ref rm)) => lm == rm && self.eq_pat(le, re),
326 (&PatKind::Slice(ls, ref li, le), &PatKind::Slice(rs, ref ri, re)) => {
327 over(ls, rs, |l, r| self.eq_pat(l, r))
328 && over(le, re, |l, r| self.eq_pat(l, r))
329 && both(li, ri, |l, r| self.eq_pat(l, r))
331 (&PatKind::Wild, &PatKind::Wild) => true,
336 #[allow(clippy::similar_names)]
337 fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
338 match (left, right) {
339 (&QPath::Resolved(ref lty, lpath), &QPath::Resolved(ref rty, rpath)) => {
340 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
342 (&QPath::TypeRelative(lty, lseg), &QPath::TypeRelative(rty, rseg)) => {
343 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
345 (&QPath::LangItem(llang_item, _), &QPath::LangItem(rlang_item, _)) => llang_item == rlang_item,
350 fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
351 match (left.res, right.res) {
352 (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
353 (Res::Local(_), _) | (_, Res::Local(_)) => false,
354 _ => over(left.segments, right.segments, |l, r| self.eq_path_segment(l, r)),
358 fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
359 if !(left.parenthesized || right.parenthesized) {
360 over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
361 && over(left.bindings, right.bindings, |l, r| self.eq_type_binding(l, r))
362 } else if left.parenthesized && right.parenthesized {
363 over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
364 && both(&Some(&left.bindings[0].ty()), &Some(&right.bindings[0].ty()), |l, r| {
372 pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
373 left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
376 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
377 // The == of idents doesn't work with different contexts,
378 // we have to be explicit about hygiene
379 left.ident.name == right.ident.name && both(&left.args, &right.args, |l, r| self.eq_path_parameters(l, r))
382 #[allow(clippy::similar_names)]
383 fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
384 match (&left.kind, &right.kind) {
385 (&TyKind::Slice(l_vec), &TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
386 (&TyKind::Array(lt, ref ll_id), &TyKind::Array(rt, ref rl_id)) => {
387 let cx = self.inner.cx;
389 |body| constant_context(cx, cx.tcx.typeck_body(body)).expr(&cx.tcx.hir().body(body).value);
390 self.eq_ty(lt, rt) && eval_const(ll_id.body) == eval_const(rl_id.body)
392 (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
393 l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty)
395 (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
396 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
398 (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
399 (&TyKind::Tup(l), &TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
400 (&TyKind::Infer, &TyKind::Infer) => true,
405 fn eq_type_binding(&mut self, left: &TypeBinding<'_>, right: &TypeBinding<'_>) -> bool {
406 left.ident.name == right.ident.name && self.eq_ty(left.ty(), right.ty())
410 /// Some simple reductions like `{ return }` => `return`
411 fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
412 if let ExprKind::Block(block, _) = kind {
413 match (block.stmts, block.expr) {
414 // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
415 // block with an empty span.
416 ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
418 ([], None) => match snippet_opt(cx, block.span) {
419 // Don't reduce if there are any tokens contained in the braces
426 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
429 .ne([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied()) =>
433 _ => &ExprKind::Tup(&[]),
435 ([], Some(expr)) => match expr.kind {
436 // `{ return .. }` => `return ..`
437 ExprKind::Ret(..) => &expr.kind,
440 ([stmt], None) => match stmt.kind {
441 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
442 // `{ return ..; }` => `return ..`
443 ExprKind::Ret(..) => &expr.kind,
459 ) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
461 BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
462 Some((binop, rhs, lhs))
464 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
465 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
466 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
467 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
468 BinOpKind::Mul // Not always commutative, e.g. with matrices. See issue #5698
475 | BinOpKind::Or => None,
479 /// Checks if the two `Option`s are both `None` or some equal values as per
481 pub fn both<X>(l: &Option<X>, r: &Option<X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
483 .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
486 /// Checks if two slices are equal as per `eq_fn`.
487 pub fn over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
488 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
491 /// Counts how many elements of the slices are equal as per `eq_fn`.
492 pub fn count_eq<X: Sized>(
493 left: &mut dyn Iterator<Item = X>,
494 right: &mut dyn Iterator<Item = X>,
495 mut eq_fn: impl FnMut(&X, &X) -> bool,
497 left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
500 /// Checks if two expressions evaluate to the same value, and don't contain any side effects.
501 pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
502 SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
505 /// Type used to hash an ast element. This is different from the `Hash` trait
506 /// on ast types as this
507 /// trait would consider IDs and spans.
509 /// All expressions kind are hashed, but some might have a weaker hash.
510 pub struct SpanlessHash<'a, 'tcx> {
511 /// Context used to evaluate constant expressions.
512 cx: &'a LateContext<'tcx>,
513 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
517 impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
518 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
521 maybe_typeck_results: cx.maybe_typeck_results(),
522 s: FxHasher::default(),
526 pub fn finish(self) -> u64 {
530 pub fn hash_block(&mut self, b: &Block<'_>) {
535 if let Some(e) = b.expr {
539 std::mem::discriminant(&b.rules).hash(&mut self.s);
542 #[allow(clippy::many_single_char_names, clippy::too_many_lines)]
543 pub fn hash_expr(&mut self, e: &Expr<'_>) {
544 let simple_const = self
545 .maybe_typeck_results
546 .and_then(|typeck_results| constant_simple(self.cx, typeck_results, e));
548 // const hashing may result in the same hash as some unrelated node, so add a sort of
549 // discriminant depending on which path we're choosing next
550 simple_const.hash(&mut self.s);
551 if simple_const.is_some() {
555 std::mem::discriminant(&e.kind).hash(&mut self.s);
558 ExprKind::AddrOf(kind, m, e) => {
559 std::mem::discriminant(&kind).hash(&mut self.s);
563 ExprKind::Continue(i) => {
564 if let Some(i) = i.label {
565 self.hash_name(i.ident.name);
568 ExprKind::Assign(l, r, _) => {
572 ExprKind::AssignOp(ref o, l, r) => {
573 std::mem::discriminant(&o.node).hash(&mut self.s);
577 ExprKind::Block(b, _) => {
580 ExprKind::Binary(op, l, r) => {
581 std::mem::discriminant(&op.node).hash(&mut self.s);
585 ExprKind::Break(i, ref j) => {
586 if let Some(i) = i.label {
587 self.hash_name(i.ident.name);
589 if let Some(j) = *j {
593 ExprKind::Box(e) | ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
596 ExprKind::Call(fun, args) => {
598 self.hash_exprs(args);
600 ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
604 ExprKind::Closure(cap, _, eid, _, _) => {
605 std::mem::discriminant(&cap).hash(&mut self.s);
606 // closures inherit TypeckResults
607 self.hash_expr(&self.cx.tcx.hir().body(eid).value);
609 ExprKind::Field(e, ref f) => {
611 self.hash_name(f.name);
613 ExprKind::Index(a, i) => {
617 ExprKind::InlineAsm(asm) => {
618 for piece in asm.template {
620 InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
621 InlineAsmTemplatePiece::Placeholder {
626 operand_idx.hash(&mut self.s);
627 modifier.hash(&mut self.s);
631 asm.options.hash(&mut self.s);
632 for (op, _op_sp) in asm.operands {
634 InlineAsmOperand::In { reg, expr } => {
635 reg.hash(&mut self.s);
636 self.hash_expr(expr);
638 InlineAsmOperand::Out { reg, late, expr } => {
639 reg.hash(&mut self.s);
640 late.hash(&mut self.s);
641 if let Some(expr) = expr {
642 self.hash_expr(expr);
645 InlineAsmOperand::InOut { reg, late, expr } => {
646 reg.hash(&mut self.s);
647 late.hash(&mut self.s);
648 self.hash_expr(expr);
650 InlineAsmOperand::SplitInOut {
656 reg.hash(&mut self.s);
657 late.hash(&mut self.s);
658 self.hash_expr(in_expr);
659 if let Some(out_expr) = out_expr {
660 self.hash_expr(out_expr);
663 InlineAsmOperand::Const { anon_const } => self.hash_body(anon_const.body),
664 InlineAsmOperand::Sym { expr } => self.hash_expr(expr),
668 ExprKind::LlvmInlineAsm(..) | ExprKind::Err => {},
669 ExprKind::Lit(ref l) => {
670 l.node.hash(&mut self.s);
672 ExprKind::Loop(b, ref i, ..) => {
674 if let Some(i) = *i {
675 self.hash_name(i.ident.name);
678 ExprKind::If(cond, then, ref else_opt) => {
679 self.hash_expr(cond);
680 self.hash_expr(then);
681 if let Some(e) = *else_opt {
685 ExprKind::Match(e, arms, ref s) => {
689 self.hash_pat(arm.pat);
690 if let Some(ref e) = arm.guard {
693 self.hash_expr(arm.body);
698 ExprKind::MethodCall(path, ref _tys, args, ref _fn_span) => {
699 self.hash_name(path.ident.name);
700 self.hash_exprs(args);
702 ExprKind::ConstBlock(ref l_id) => {
703 self.hash_body(l_id.body);
705 ExprKind::Repeat(e, ref l_id) => {
707 self.hash_body(l_id.body);
709 ExprKind::Ret(ref e) => {
710 if let Some(e) = *e {
714 ExprKind::Path(ref qpath) => {
715 self.hash_qpath(qpath);
717 ExprKind::Struct(path, fields, ref expr) => {
718 self.hash_qpath(path);
721 self.hash_name(f.ident.name);
722 self.hash_expr(f.expr);
725 if let Some(e) = *expr {
729 ExprKind::Tup(tup) => {
730 self.hash_exprs(tup);
732 ExprKind::Array(v) => {
735 ExprKind::Unary(lop, le) => {
736 std::mem::discriminant(&lop).hash(&mut self.s);
742 pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
748 pub fn hash_name(&mut self, n: Symbol) {
749 n.as_str().hash(&mut self.s);
752 pub fn hash_qpath(&mut self, p: &QPath<'_>) {
754 QPath::Resolved(_, path) => {
755 self.hash_path(path);
757 QPath::TypeRelative(_, path) => {
758 self.hash_name(path.ident.name);
760 QPath::LangItem(lang_item, ..) => {
761 std::mem::discriminant(&lang_item).hash(&mut self.s);
764 // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
767 pub fn hash_pat(&mut self, pat: &Pat<'_>) {
768 std::mem::discriminant(&pat.kind).hash(&mut self.s);
770 PatKind::Binding(ann, _, _, pat) => {
771 std::mem::discriminant(&ann).hash(&mut self.s);
772 if let Some(pat) = pat {
776 PatKind::Box(pat) => self.hash_pat(pat),
777 PatKind::Lit(expr) => self.hash_expr(expr),
778 PatKind::Or(pats) => {
783 PatKind::Path(ref qpath) => self.hash_qpath(qpath),
784 PatKind::Range(s, e, i) => {
791 std::mem::discriminant(&i).hash(&mut self.s);
793 PatKind::Ref(pat, mu) => {
795 std::mem::discriminant(&mu).hash(&mut self.s);
797 PatKind::Slice(l, m, r) => {
801 if let Some(pat) = m {
808 PatKind::Struct(ref qpath, fields, e) => {
809 self.hash_qpath(qpath);
811 self.hash_name(f.ident.name);
812 self.hash_pat(f.pat);
816 PatKind::Tuple(pats, e) => {
822 PatKind::TupleStruct(ref qpath, pats, e) => {
823 self.hash_qpath(qpath);
833 pub fn hash_path(&mut self, path: &Path<'_>) {
835 // constant hash since equality is dependant on inter-expression context
836 Res::Local(_) => 1_usize.hash(&mut self.s),
838 for seg in path.segments {
839 self.hash_name(seg.ident.name);
845 pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
846 std::mem::discriminant(&b.kind).hash(&mut self.s);
849 StmtKind::Local(local) => {
850 self.hash_pat(local.pat);
851 if let Some(init) = local.init {
852 self.hash_expr(init);
855 StmtKind::Item(..) => {},
856 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
857 self.hash_expr(expr);
862 pub fn hash_guard(&mut self, g: &Guard<'_>) {
864 Guard::If(expr) | Guard::IfLet(_, expr) => {
865 self.hash_expr(expr);
870 pub fn hash_lifetime(&mut self, lifetime: Lifetime) {
871 std::mem::discriminant(&lifetime.name).hash(&mut self.s);
872 if let LifetimeName::Param(ref name) = lifetime.name {
873 std::mem::discriminant(name).hash(&mut self.s);
875 ParamName::Plain(ref ident) => {
876 ident.name.hash(&mut self.s);
878 ParamName::Fresh(ref size) => {
879 size.hash(&mut self.s);
881 ParamName::Error => {},
886 pub fn hash_ty(&mut self, ty: &Ty<'_>) {
887 std::mem::discriminant(&ty.kind).hash(&mut self.s);
889 TyKind::Slice(ty) => {
892 TyKind::Array(ty, anon_const) => {
894 self.hash_body(anon_const.body);
896 TyKind::Ptr(ref mut_ty) => {
897 self.hash_ty(mut_ty.ty);
898 mut_ty.mutbl.hash(&mut self.s);
900 TyKind::Rptr(lifetime, ref mut_ty) => {
901 self.hash_lifetime(lifetime);
902 self.hash_ty(mut_ty.ty);
903 mut_ty.mutbl.hash(&mut self.s);
905 TyKind::BareFn(bfn) => {
906 bfn.unsafety.hash(&mut self.s);
907 bfn.abi.hash(&mut self.s);
908 for arg in bfn.decl.inputs {
911 std::mem::discriminant(&bfn.decl.output).hash(&mut self.s);
912 match bfn.decl.output {
913 FnRetTy::DefaultReturn(_) => {},
914 FnRetTy::Return(ty) => {
918 bfn.decl.c_variadic.hash(&mut self.s);
920 TyKind::Tup(ty_list) => {
925 TyKind::Path(ref qpath) => self.hash_qpath(qpath),
926 TyKind::OpaqueDef(_, arg_list) => {
927 self.hash_generic_args(arg_list);
929 TyKind::TraitObject(_, lifetime, _) => {
930 self.hash_lifetime(lifetime);
932 TyKind::Typeof(anon_const) => {
933 self.hash_body(anon_const.body);
935 TyKind::Err | TyKind::Infer | TyKind::Never => {},
939 pub fn hash_body(&mut self, body_id: BodyId) {
940 // swap out TypeckResults when hashing a body
941 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
942 self.hash_expr(&self.cx.tcx.hir().body(body_id).value);
943 self.maybe_typeck_results = old_maybe_typeck_results;
946 fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
947 for arg in arg_list {
949 GenericArg::Lifetime(l) => self.hash_lifetime(l),
950 GenericArg::Type(ref ty) => self.hash_ty(ty),
951 GenericArg::Const(ref ca) => self.hash_body(ca.value.body),