1 use crate::consts::{constant_context, constant_simple};
2 use crate::utils::differing_macro_contexts;
4 use rustc::lint::LateContext;
5 use rustc::ty::TypeckTables;
6 use std::collections::hash_map::DefaultHasher;
7 use std::hash::{Hash, Hasher};
11 /// Type used to check whether two ast are the same. This is different from the
13 /// `==` on ast types as this operator would compare true equality with ID and
16 /// Note that some expressions kinds are not considered but could be added.
17 pub struct SpanlessEq<'a, 'tcx: 'a> {
18 /// Context used to evaluate constant expressions.
19 cx: &'a LateContext<'a, 'tcx>,
20 tables: &'a TypeckTables<'tcx>,
21 /// If is true, never consider as equal expressions containing function
26 impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
27 pub fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
35 pub fn ignore_fn(self) -> Self {
38 tables: self.cx.tables,
43 /// Check whether two statements are the same.
44 pub fn eq_stmt(&mut self, left: &Stmt, right: &Stmt) -> bool {
45 match (&left.node, &right.node) {
46 (&StmtKind::Local(ref l), &StmtKind::Local(ref r)) => {
47 self.eq_pat(&l.pat, &r.pat)
48 && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r))
49 && both(&l.init, &r.init, |l, r| self.eq_expr(l, r))
51 (&StmtKind::Expr(ref l), &StmtKind::Expr(ref r)) | (&StmtKind::Semi(ref l), &StmtKind::Semi(ref r)) => {
58 /// Check whether two blocks are the same.
59 pub fn eq_block(&mut self, left: &Block, right: &Block) -> bool {
60 over(&left.stmts, &right.stmts, |l, r| self.eq_stmt(l, r))
61 && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
64 #[allow(clippy::similar_names)]
65 pub fn eq_expr(&mut self, left: &Expr, right: &Expr) -> bool {
66 if self.ignore_fn && differing_macro_contexts(left.span, right.span) {
70 if let (Some(l), Some(r)) = (
71 constant_simple(self.cx, self.tables, left),
72 constant_simple(self.cx, self.tables, right),
79 match (&left.node, &right.node) {
80 (&ExprKind::AddrOf(l_mut, ref le), &ExprKind::AddrOf(r_mut, ref re)) => {
81 l_mut == r_mut && self.eq_expr(le, re)
83 (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => {
84 both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str())
86 (&ExprKind::Assign(ref ll, ref lr), &ExprKind::Assign(ref rl, ref rr)) => {
87 self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
89 (&ExprKind::AssignOp(ref lo, ref ll, ref lr), &ExprKind::AssignOp(ref ro, ref rl, ref rr)) => {
90 lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
92 (&ExprKind::Block(ref l, _), &ExprKind::Block(ref r, _)) => self.eq_block(l, r),
93 (&ExprKind::Binary(l_op, ref ll, ref lr), &ExprKind::Binary(r_op, ref rl, ref rr)) => {
94 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
95 || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
96 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
99 (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => {
100 both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str())
101 && both(le, re, |l, r| self.eq_expr(l, r))
103 (&ExprKind::Box(ref l), &ExprKind::Box(ref r)) => self.eq_expr(l, r),
104 (&ExprKind::Call(ref l_fun, ref l_args), &ExprKind::Call(ref r_fun, ref r_args)) => {
105 !self.ignore_fn && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
107 (&ExprKind::Cast(ref lx, ref lt), &ExprKind::Cast(ref rx, ref rt))
108 | (&ExprKind::Type(ref lx, ref lt), &ExprKind::Type(ref rx, ref rt)) => {
109 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
111 (&ExprKind::Field(ref l_f_exp, ref l_f_ident), &ExprKind::Field(ref r_f_exp, ref r_f_ident)) => {
112 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
114 (&ExprKind::Index(ref la, ref li), &ExprKind::Index(ref ra, ref ri)) => {
115 self.eq_expr(la, ra) && self.eq_expr(li, ri)
117 (&ExprKind::If(ref lc, ref lt, ref le), &ExprKind::If(ref rc, ref rt, ref re)) => {
118 self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r))
120 (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
121 (&ExprKind::Loop(ref lb, ref ll, ref lls), &ExprKind::Loop(ref rb, ref rl, ref rls)) => {
122 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
124 (&ExprKind::Match(ref le, ref la, ref ls), &ExprKind::Match(ref re, ref ra, ref rs)) => {
126 && self.eq_expr(le, re)
127 && over(la, ra, |l, r| {
128 self.eq_expr(&l.body, &r.body)
129 && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
130 && over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r))
133 (&ExprKind::MethodCall(ref l_path, _, ref l_args), &ExprKind::MethodCall(ref r_path, _, ref r_args)) => {
134 !self.ignore_fn && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
136 (&ExprKind::Repeat(ref le, ref ll_id), &ExprKind::Repeat(ref re, ref rl_id)) => {
137 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
138 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
139 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
140 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
142 self.eq_expr(le, re) && ll == rl
144 (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
145 (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
146 (&ExprKind::Struct(ref l_path, ref lf, ref lo), &ExprKind::Struct(ref r_path, ref rf, ref ro)) => {
147 self.eq_qpath(l_path, r_path)
148 && both(lo, ro, |l, r| self.eq_expr(l, r))
149 && over(lf, rf, |l, r| self.eq_field(l, r))
151 (&ExprKind::Tup(ref l_tup), &ExprKind::Tup(ref r_tup)) => self.eq_exprs(l_tup, r_tup),
152 (&ExprKind::Unary(l_op, ref le), &ExprKind::Unary(r_op, ref re)) => l_op == r_op && self.eq_expr(le, re),
153 (&ExprKind::Array(ref l), &ExprKind::Array(ref r)) => self.eq_exprs(l, r),
154 (&ExprKind::While(ref lc, ref lb, ref ll), &ExprKind::While(ref rc, ref rb, ref rl)) => {
156 && self.eq_block(lb, rb)
157 && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
163 fn eq_exprs(&mut self, left: &P<[Expr]>, right: &P<[Expr]>) -> bool {
164 over(left, right, |l, r| self.eq_expr(l, r))
167 fn eq_field(&mut self, left: &Field, right: &Field) -> bool {
168 left.ident.name == right.ident.name && self.eq_expr(&left.expr, &right.expr)
171 fn eq_guard(&mut self, left: &Guard, right: &Guard) -> bool {
172 match (left, right) {
173 (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
177 fn eq_generic_arg(&mut self, left: &GenericArg, right: &GenericArg) -> bool {
178 match (left, right) {
179 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => self.eq_lifetime(l_lt, r_lt),
180 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
185 fn eq_lifetime(&mut self, left: &Lifetime, right: &Lifetime) -> bool {
186 left.name == right.name
189 /// Check whether two patterns are the same.
190 pub fn eq_pat(&mut self, left: &Pat, right: &Pat) -> bool {
191 match (&left.node, &right.node) {
192 (&PatKind::Box(ref l), &PatKind::Box(ref r)) => self.eq_pat(l, r),
193 (&PatKind::TupleStruct(ref lp, ref la, ls), &PatKind::TupleStruct(ref rp, ref ra, rs)) => {
194 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
196 (&PatKind::Binding(ref lb, .., ref li, ref lp), &PatKind::Binding(ref rb, .., ref ri, ref rp)) => {
197 lb == rb && li.name.as_str() == ri.name.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r))
199 (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
200 (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r),
201 (&PatKind::Tuple(ref l, ls), &PatKind::Tuple(ref r, rs)) => {
202 ls == rs && over(l, r, |l, r| self.eq_pat(l, r))
204 (&PatKind::Range(ref ls, ref le, ref li), &PatKind::Range(ref rs, ref re, ref ri)) => {
205 self.eq_expr(ls, rs) && self.eq_expr(le, re) && (*li == *ri)
207 (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => lm == rm && self.eq_pat(le, re),
208 (&PatKind::Slice(ref ls, ref li, ref le), &PatKind::Slice(ref rs, ref ri, ref re)) => {
209 over(ls, rs, |l, r| self.eq_pat(l, r))
210 && over(le, re, |l, r| self.eq_pat(l, r))
211 && both(li, ri, |l, r| self.eq_pat(l, r))
213 (&PatKind::Wild, &PatKind::Wild) => true,
218 #[allow(clippy::similar_names)]
219 fn eq_qpath(&mut self, left: &QPath, right: &QPath) -> bool {
220 match (left, right) {
221 (&QPath::Resolved(ref lty, ref lpath), &QPath::Resolved(ref rty, ref rpath)) => {
222 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
224 (&QPath::TypeRelative(ref lty, ref lseg), &QPath::TypeRelative(ref rty, ref rseg)) => {
225 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
231 fn eq_path(&mut self, left: &Path, right: &Path) -> bool {
232 left.is_global() == right.is_global()
233 && over(&left.segments, &right.segments, |l, r| self.eq_path_segment(l, r))
236 fn eq_path_parameters(&mut self, left: &GenericArgs, right: &GenericArgs) -> bool {
237 if !(left.parenthesized || right.parenthesized) {
238 over(&left.args, &right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
239 && over(&left.bindings, &right.bindings, |l, r| self.eq_type_binding(l, r))
240 } else if left.parenthesized && right.parenthesized {
241 over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
242 && both(&Some(&left.bindings[0].ty), &Some(&right.bindings[0].ty), |l, r| {
250 pub fn eq_path_segments(&mut self, left: &[PathSegment], right: &[PathSegment]) -> bool {
251 left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
254 pub fn eq_path_segment(&mut self, left: &PathSegment, right: &PathSegment) -> bool {
255 // The == of idents doesn't work with different contexts,
256 // we have to be explicit about hygiene
257 if left.ident.as_str() != right.ident.as_str() {
260 match (&left.args, &right.args) {
261 (&None, &None) => true,
262 (&Some(ref l), &Some(ref r)) => self.eq_path_parameters(l, r),
267 pub fn eq_ty(&mut self, left: &Ty, right: &Ty) -> bool {
268 self.eq_ty_kind(&left.node, &right.node)
271 #[allow(clippy::similar_names)]
272 pub fn eq_ty_kind(&mut self, left: &TyKind, right: &TyKind) -> bool {
273 match (left, right) {
274 (&TyKind::Slice(ref l_vec), &TyKind::Slice(ref r_vec)) => self.eq_ty(l_vec, r_vec),
275 (&TyKind::Array(ref lt, ref ll_id), &TyKind::Array(ref rt, ref rl_id)) => {
276 let full_table = self.tables;
278 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
279 self.tables = self.cx.tcx.body_tables(ll_id.body);
280 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
282 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
283 self.tables = self.cx.tcx.body_tables(rl_id.body);
284 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
286 let eq_ty = self.eq_ty(lt, rt);
287 self.tables = full_table;
290 (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
291 l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty)
293 (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
294 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
296 (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
297 (&TyKind::Tup(ref l), &TyKind::Tup(ref r)) => over(l, r, |l, r| self.eq_ty(l, r)),
298 (&TyKind::Infer, &TyKind::Infer) => true,
303 fn eq_type_binding(&mut self, left: &TypeBinding, right: &TypeBinding) -> bool {
304 left.ident.name == right.ident.name && self.eq_ty(&left.ty, &right.ty)
308 fn swap_binop<'a>(binop: BinOpKind, lhs: &'a Expr, rhs: &'a Expr) -> Option<(BinOpKind, &'a Expr, &'a Expr)> {
316 | BinOpKind::BitOr => Some((binop, rhs, lhs)),
317 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
318 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
319 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
320 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
327 | BinOpKind::Or => None,
331 /// Check if the two `Option`s are both `None` or some equal values as per
333 fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
335 F: FnMut(&X, &X) -> bool,
338 .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
341 /// Check if two slices are equal as per `eq_fn`.
342 fn over<X, F>(left: &[X], right: &[X], mut eq_fn: F) -> bool
344 F: FnMut(&X, &X) -> bool,
346 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
349 /// Type used to hash an ast element. This is different from the `Hash` trait
350 /// on ast types as this
351 /// trait would consider IDs and spans.
353 /// All expressions kind are hashed, but some might have a weaker hash.
354 pub struct SpanlessHash<'a, 'tcx: 'a> {
355 /// Context used to evaluate constant expressions.
356 cx: &'a LateContext<'a, 'tcx>,
357 tables: &'a TypeckTables<'tcx>,
361 impl<'a, 'tcx: 'a> SpanlessHash<'a, 'tcx> {
362 pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckTables<'tcx>) -> Self {
366 s: DefaultHasher::new(),
370 pub fn finish(&self) -> u64 {
374 pub fn hash_block(&mut self, b: &Block) {
379 if let Some(ref e) = b.expr {
384 BlockCheckMode::DefaultBlock => 0,
385 BlockCheckMode::UnsafeBlock(_) => 1,
386 BlockCheckMode::PushUnsafeBlock(_) => 2,
387 BlockCheckMode::PopUnsafeBlock(_) => 3,
392 #[allow(clippy::many_single_char_names, clippy::too_many_lines)]
393 pub fn hash_expr(&mut self, e: &Expr) {
394 if let Some(e) = constant_simple(self.cx, self.tables, e) {
395 return e.hash(&mut self.s);
399 ExprKind::AddrOf(m, ref e) => {
400 let c: fn(_, _) -> _ = ExprKind::AddrOf;
405 ExprKind::Continue(i) => {
406 let c: fn(_) -> _ = ExprKind::Continue;
408 if let Some(i) = i.label {
409 self.hash_name(i.ident.name);
412 ExprKind::Yield(ref e) => {
413 let c: fn(_) -> _ = ExprKind::Yield;
417 ExprKind::Assign(ref l, ref r) => {
418 let c: fn(_, _) -> _ = ExprKind::Assign;
423 ExprKind::AssignOp(ref o, ref l, ref r) => {
424 let c: fn(_, _, _) -> _ = ExprKind::AssignOp;
430 ExprKind::Block(ref b, _) => {
431 let c: fn(_, _) -> _ = ExprKind::Block;
435 ExprKind::Binary(op, ref l, ref r) => {
436 let c: fn(_, _, _) -> _ = ExprKind::Binary;
438 op.node.hash(&mut self.s);
442 ExprKind::Break(i, ref j) => {
443 let c: fn(_, _) -> _ = ExprKind::Break;
445 if let Some(i) = i.label {
446 self.hash_name(i.ident.name);
448 if let Some(ref j) = *j {
452 ExprKind::Box(ref e) => {
453 let c: fn(_) -> _ = ExprKind::Box;
457 ExprKind::Call(ref fun, ref args) => {
458 let c: fn(_, _) -> _ = ExprKind::Call;
461 self.hash_exprs(args);
463 ExprKind::Cast(ref e, ref _ty) => {
464 let c: fn(_, _) -> _ = ExprKind::Cast;
469 ExprKind::Closure(cap, _, eid, _, _) => {
470 let c: fn(_, _, _, _, _) -> _ = ExprKind::Closure;
473 CaptureClause::CaptureByValue => 0,
474 CaptureClause::CaptureByRef => 1,
477 self.hash_expr(&self.cx.tcx.hir().body(eid).value);
479 ExprKind::Field(ref e, ref f) => {
480 let c: fn(_, _) -> _ = ExprKind::Field;
483 self.hash_name(f.name);
485 ExprKind::Index(ref a, ref i) => {
486 let c: fn(_, _) -> _ = ExprKind::Index;
491 ExprKind::InlineAsm(..) => {
492 let c: fn(_, _, _) -> _ = ExprKind::InlineAsm;
495 ExprKind::If(ref cond, ref t, ref e) => {
496 let c: fn(_, _, _) -> _ = ExprKind::If;
498 self.hash_expr(cond);
499 self.hash_expr(&**t);
500 if let Some(ref e) = *e {
504 ExprKind::Lit(ref l) => {
505 let c: fn(_) -> _ = ExprKind::Lit;
509 ExprKind::Loop(ref b, ref i, _) => {
510 let c: fn(_, _, _) -> _ = ExprKind::Loop;
513 if let Some(i) = *i {
514 self.hash_name(i.ident.name);
517 ExprKind::Match(ref e, ref arms, ref s) => {
518 let c: fn(_, _, _) -> _ = ExprKind::Match;
524 if let Some(ref e) = arm.guard {
527 self.hash_expr(&arm.body);
532 ExprKind::MethodCall(ref path, ref _tys, ref args) => {
533 let c: fn(_, _, _) -> _ = ExprKind::MethodCall;
535 self.hash_name(path.ident.name);
536 self.hash_exprs(args);
538 ExprKind::Repeat(ref e, ref l_id) => {
539 let c: fn(_, _) -> _ = ExprKind::Repeat;
542 let full_table = self.tables;
543 self.tables = self.cx.tcx.body_tables(l_id.body);
544 self.hash_expr(&self.cx.tcx.hir().body(l_id.body).value);
545 self.tables = full_table;
547 ExprKind::Ret(ref e) => {
548 let c: fn(_) -> _ = ExprKind::Ret;
550 if let Some(ref e) = *e {
554 ExprKind::Path(ref qpath) => {
555 let c: fn(_) -> _ = ExprKind::Path;
557 self.hash_qpath(qpath);
559 ExprKind::Struct(ref path, ref fields, ref expr) => {
560 let c: fn(_, _, _) -> _ = ExprKind::Struct;
563 self.hash_qpath(path);
566 self.hash_name(f.ident.name);
567 self.hash_expr(&f.expr);
570 if let Some(ref e) = *expr {
574 ExprKind::Tup(ref tup) => {
575 let c: fn(_) -> _ = ExprKind::Tup;
577 self.hash_exprs(tup);
579 ExprKind::Type(ref e, ref _ty) => {
580 let c: fn(_, _) -> _ = ExprKind::Type;
585 ExprKind::Unary(lop, ref le) => {
586 let c: fn(_, _) -> _ = ExprKind::Unary;
589 lop.hash(&mut self.s);
592 ExprKind::Array(ref v) => {
593 let c: fn(_) -> _ = ExprKind::Array;
598 ExprKind::While(ref cond, ref b, l) => {
599 let c: fn(_, _, _) -> _ = ExprKind::While;
602 self.hash_expr(cond);
605 self.hash_name(l.ident.name);
612 pub fn hash_exprs(&mut self, e: &P<[Expr]>) {
618 pub fn hash_name(&mut self, n: Name) {
619 n.as_str().hash(&mut self.s);
622 pub fn hash_qpath(&mut self, p: &QPath) {
624 QPath::Resolved(_, ref path) => {
625 self.hash_path(path);
627 QPath::TypeRelative(_, ref path) => {
628 self.hash_name(path.ident.name);
631 // self.cx.tables.qpath_def(p, id).hash(&mut self.s);
634 pub fn hash_path(&mut self, p: &Path) {
635 p.is_global().hash(&mut self.s);
636 for p in &p.segments {
637 self.hash_name(p.ident.name);
641 pub fn hash_stmt(&mut self, b: &Stmt) {
643 StmtKind::Local(ref local) => {
644 let c: fn(_) -> _ = StmtKind::Local;
646 if let Some(ref init) = local.init {
647 self.hash_expr(init);
650 StmtKind::Item(..) => {
651 let c: fn(_) -> _ = StmtKind::Item;
654 StmtKind::Expr(ref expr) => {
655 let c: fn(_) -> _ = StmtKind::Expr;
657 self.hash_expr(expr);
659 StmtKind::Semi(ref expr) => {
660 let c: fn(_) -> _ = StmtKind::Semi;
662 self.hash_expr(expr);
667 pub fn hash_guard(&mut self, g: &Guard) {
669 Guard::If(ref expr) => {
670 let c: fn(_) -> _ = Guard::If;
672 self.hash_expr(expr);