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))
52 | (&StmtKind::Semi(ref l), &StmtKind::Semi(ref r)) => self.eq_expr(l, r),
57 /// Check whether two blocks are the same.
58 pub fn eq_block(&mut self, left: &Block, right: &Block) -> bool {
59 over(&left.stmts, &right.stmts, |l, r| self.eq_stmt(l, r))
60 && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
63 #[allow(clippy::similar_names)]
64 pub fn eq_expr(&mut self, left: &Expr, right: &Expr) -> bool {
65 if self.ignore_fn && differing_macro_contexts(left.span, right.span) {
69 if let (Some(l), Some(r)) = (
70 constant_simple(self.cx, self.tables, left),
71 constant_simple(self.cx, self.tables, right),
78 match (&left.node, &right.node) {
79 (&ExprKind::AddrOf(l_mut, ref le), &ExprKind::AddrOf(r_mut, ref re)) => {
80 l_mut == r_mut && self.eq_expr(le, re)
82 (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => {
83 both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str())
85 (&ExprKind::Assign(ref ll, ref lr), &ExprKind::Assign(ref rl, ref rr)) => {
86 self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
88 (&ExprKind::AssignOp(ref lo, ref ll, ref lr), &ExprKind::AssignOp(ref ro, ref rl, ref rr)) => {
89 lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
91 (&ExprKind::Block(ref l, _), &ExprKind::Block(ref r, _)) => self.eq_block(l, r),
92 (&ExprKind::Binary(l_op, ref ll, ref lr), &ExprKind::Binary(r_op, ref rl, ref rr)) => {
93 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
94 || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
95 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
98 (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => {
99 both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str())
100 && both(le, re, |l, r| self.eq_expr(l, r))
102 (&ExprKind::Box(ref l), &ExprKind::Box(ref r)) => self.eq_expr(l, r),
103 (&ExprKind::Call(ref l_fun, ref l_args), &ExprKind::Call(ref r_fun, ref r_args)) => {
104 !self.ignore_fn && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
106 (&ExprKind::Cast(ref lx, ref lt), &ExprKind::Cast(ref rx, ref rt))
107 | (&ExprKind::Type(ref lx, ref lt), &ExprKind::Type(ref rx, ref rt)) => {
108 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
110 (&ExprKind::Field(ref l_f_exp, ref l_f_ident), &ExprKind::Field(ref r_f_exp, ref r_f_ident)) => {
111 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
113 (&ExprKind::Index(ref la, ref li), &ExprKind::Index(ref ra, ref ri)) => {
114 self.eq_expr(la, ra) && self.eq_expr(li, ri)
116 (&ExprKind::If(ref lc, ref lt, ref le), &ExprKind::If(ref rc, ref rt, ref re)) => {
117 self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r))
119 (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
120 (&ExprKind::Loop(ref lb, ref ll, ref lls), &ExprKind::Loop(ref rb, ref rl, ref rls)) => {
121 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
123 (&ExprKind::Match(ref le, ref la, ref ls), &ExprKind::Match(ref re, ref ra, ref rs)) => {
125 && self.eq_expr(le, re)
126 && over(la, ra, |l, r| {
127 self.eq_expr(&l.body, &r.body)
128 && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
129 && over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r))
132 (&ExprKind::MethodCall(ref l_path, _, ref l_args), &ExprKind::MethodCall(ref r_path, _, ref r_args)) => {
133 !self.ignore_fn && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
135 (&ExprKind::Repeat(ref le, ref ll_id), &ExprKind::Repeat(ref re, ref rl_id)) => {
136 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
137 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
138 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
139 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
141 self.eq_expr(le, re) && ll == rl
143 (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
144 (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
145 (&ExprKind::Struct(ref l_path, ref lf, ref lo), &ExprKind::Struct(ref r_path, ref rf, ref ro)) => {
146 self.eq_qpath(l_path, r_path)
147 && both(lo, ro, |l, r| self.eq_expr(l, r))
148 && over(lf, rf, |l, r| self.eq_field(l, r))
150 (&ExprKind::Tup(ref l_tup), &ExprKind::Tup(ref r_tup)) => self.eq_exprs(l_tup, r_tup),
151 (&ExprKind::Unary(l_op, ref le), &ExprKind::Unary(r_op, ref re)) => l_op == r_op && self.eq_expr(le, re),
152 (&ExprKind::Array(ref l), &ExprKind::Array(ref r)) => self.eq_exprs(l, r),
153 (&ExprKind::While(ref lc, ref lb, ref ll), &ExprKind::While(ref rc, ref rb, ref rl)) => {
155 && self.eq_block(lb, rb)
156 && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
162 fn eq_exprs(&mut self, left: &P<[Expr]>, right: &P<[Expr]>) -> bool {
163 over(left, right, |l, r| self.eq_expr(l, r))
166 fn eq_field(&mut self, left: &Field, right: &Field) -> bool {
167 left.ident.name == right.ident.name && self.eq_expr(&left.expr, &right.expr)
170 fn eq_guard(&mut self, left: &Guard, right: &Guard) -> bool {
171 match (left, right) {
172 (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
176 fn eq_generic_arg(&mut self, left: &GenericArg, right: &GenericArg) -> bool {
177 match (left, right) {
178 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => self.eq_lifetime(l_lt, r_lt),
179 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
184 fn eq_lifetime(&mut self, left: &Lifetime, right: &Lifetime) -> bool {
185 left.name == right.name
188 /// Check whether two patterns are the same.
189 pub fn eq_pat(&mut self, left: &Pat, right: &Pat) -> bool {
190 match (&left.node, &right.node) {
191 (&PatKind::Box(ref l), &PatKind::Box(ref r)) => self.eq_pat(l, r),
192 (&PatKind::TupleStruct(ref lp, ref la, ls), &PatKind::TupleStruct(ref rp, ref ra, rs)) => {
193 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
195 (&PatKind::Binding(ref lb, _, ref li, ref lp), &PatKind::Binding(ref rb, _, ref ri, ref rp)) => {
196 lb == rb && li.name.as_str() == ri.name.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r))
198 (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
199 (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r),
200 (&PatKind::Tuple(ref l, ls), &PatKind::Tuple(ref r, rs)) => {
201 ls == rs && over(l, r, |l, r| self.eq_pat(l, r))
203 (&PatKind::Range(ref ls, ref le, ref li), &PatKind::Range(ref rs, ref re, ref ri)) => {
204 self.eq_expr(ls, rs) && self.eq_expr(le, re) && (*li == *ri)
206 (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => lm == rm && self.eq_pat(le, re),
207 (&PatKind::Slice(ref ls, ref li, ref le), &PatKind::Slice(ref rs, ref ri, ref re)) => {
208 over(ls, rs, |l, r| self.eq_pat(l, r))
209 && over(le, re, |l, r| self.eq_pat(l, r))
210 && both(li, ri, |l, r| self.eq_pat(l, r))
212 (&PatKind::Wild, &PatKind::Wild) => true,
217 #[allow(clippy::similar_names)]
218 fn eq_qpath(&mut self, left: &QPath, right: &QPath) -> bool {
219 match (left, right) {
220 (&QPath::Resolved(ref lty, ref lpath), &QPath::Resolved(ref rty, ref rpath)) => {
221 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
223 (&QPath::TypeRelative(ref lty, ref lseg), &QPath::TypeRelative(ref rty, ref rseg)) => {
224 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
230 fn eq_path(&mut self, left: &Path, right: &Path) -> bool {
231 left.is_global() == right.is_global()
232 && over(&left.segments, &right.segments, |l, r| self.eq_path_segment(l, r))
235 fn eq_path_parameters(&mut self, left: &GenericArgs, right: &GenericArgs) -> bool {
236 if !(left.parenthesized || right.parenthesized) {
237 over(&left.args, &right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
238 && over(&left.bindings, &right.bindings, |l, r| self.eq_type_binding(l, r))
239 } else if left.parenthesized && right.parenthesized {
240 over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
241 && both(&Some(&left.bindings[0].ty), &Some(&right.bindings[0].ty), |l, r| {
249 pub fn eq_path_segments(&mut self, left: &[PathSegment], right: &[PathSegment]) -> bool {
250 left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
253 pub fn eq_path_segment(&mut self, left: &PathSegment, right: &PathSegment) -> bool {
254 // The == of idents doesn't work with different contexts,
255 // we have to be explicit about hygiene
256 if left.ident.as_str() != right.ident.as_str() {
259 match (&left.args, &right.args) {
260 (&None, &None) => true,
261 (&Some(ref l), &Some(ref r)) => self.eq_path_parameters(l, r),
266 pub fn eq_ty(&mut self, left: &Ty, right: &Ty) -> bool {
267 self.eq_ty_kind(&left.node, &right.node)
270 #[allow(clippy::similar_names)]
271 pub fn eq_ty_kind(&mut self, left: &TyKind, right: &TyKind) -> bool {
272 match (left, right) {
273 (&TyKind::Slice(ref l_vec), &TyKind::Slice(ref r_vec)) => self.eq_ty(l_vec, r_vec),
274 (&TyKind::Array(ref lt, ref ll_id), &TyKind::Array(ref rt, ref rl_id)) => {
275 let full_table = self.tables;
277 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
278 self.tables = self.cx.tcx.body_tables(ll_id.body);
279 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
281 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
282 self.tables = self.cx.tcx.body_tables(rl_id.body);
283 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
285 let eq_ty = self.eq_ty(lt, rt);
286 self.tables = full_table;
289 (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
290 l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty)
292 (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
293 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
295 (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
296 (&TyKind::Tup(ref l), &TyKind::Tup(ref r)) => over(l, r, |l, r| self.eq_ty(l, r)),
297 (&TyKind::Infer, &TyKind::Infer) => true,
302 fn eq_type_binding(&mut self, left: &TypeBinding, right: &TypeBinding) -> bool {
303 left.ident.name == right.ident.name && self.eq_ty(&left.ty, &right.ty)
307 fn swap_binop<'a>(binop: BinOpKind, lhs: &'a Expr, rhs: &'a Expr) -> Option<(BinOpKind, &'a Expr, &'a Expr)> {
315 | BinOpKind::BitOr => Some((binop, rhs, lhs)),
316 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
317 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
318 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
319 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
326 | BinOpKind::Or => None,
330 /// Check if the two `Option`s are both `None` or some equal values as per
332 fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
334 F: FnMut(&X, &X) -> bool,
337 .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
340 /// Check if two slices are equal as per `eq_fn`.
341 fn over<X, F>(left: &[X], right: &[X], mut eq_fn: F) -> bool
343 F: FnMut(&X, &X) -> bool,
345 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
348 /// Type used to hash an ast element. This is different from the `Hash` trait
349 /// on ast types as this
350 /// trait would consider IDs and spans.
352 /// All expressions kind are hashed, but some might have a weaker hash.
353 pub struct SpanlessHash<'a, 'tcx: 'a> {
354 /// Context used to evaluate constant expressions.
355 cx: &'a LateContext<'a, 'tcx>,
356 tables: &'a TypeckTables<'tcx>,
360 impl<'a, 'tcx: 'a> SpanlessHash<'a, 'tcx> {
361 pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckTables<'tcx>) -> Self {
365 s: DefaultHasher::new(),
369 pub fn finish(&self) -> u64 {
373 pub fn hash_block(&mut self, b: &Block) {
378 if let Some(ref e) = b.expr {
383 BlockCheckMode::DefaultBlock => 0,
384 BlockCheckMode::UnsafeBlock(_) => 1,
385 BlockCheckMode::PushUnsafeBlock(_) => 2,
386 BlockCheckMode::PopUnsafeBlock(_) => 3,
391 #[allow(clippy::many_single_char_names)]
392 pub fn hash_expr(&mut self, e: &Expr) {
393 if let Some(e) = constant_simple(self.cx, self.tables, e) {
394 return e.hash(&mut self.s);
398 ExprKind::AddrOf(m, ref e) => {
399 let c: fn(_, _) -> _ = ExprKind::AddrOf;
404 ExprKind::Continue(i) => {
405 let c: fn(_) -> _ = ExprKind::Continue;
407 if let Some(i) = i.label {
408 self.hash_name(i.ident.name);
411 ExprKind::Yield(ref e) => {
412 let c: fn(_) -> _ = ExprKind::Yield;
416 ExprKind::Assign(ref l, ref r) => {
417 let c: fn(_, _) -> _ = ExprKind::Assign;
422 ExprKind::AssignOp(ref o, ref l, ref r) => {
423 let c: fn(_, _, _) -> _ = ExprKind::AssignOp;
429 ExprKind::Block(ref b, _) => {
430 let c: fn(_, _) -> _ = ExprKind::Block;
434 ExprKind::Binary(op, ref l, ref r) => {
435 let c: fn(_, _, _) -> _ = ExprKind::Binary;
437 op.node.hash(&mut self.s);
441 ExprKind::Break(i, ref j) => {
442 let c: fn(_, _) -> _ = ExprKind::Break;
444 if let Some(i) = i.label {
445 self.hash_name(i.ident.name);
447 if let Some(ref j) = *j {
451 ExprKind::Box(ref e) => {
452 let c: fn(_) -> _ = ExprKind::Box;
456 ExprKind::Call(ref fun, ref args) => {
457 let c: fn(_, _) -> _ = ExprKind::Call;
460 self.hash_exprs(args);
462 ExprKind::Cast(ref e, ref _ty) => {
463 let c: fn(_, _) -> _ = ExprKind::Cast;
468 ExprKind::Closure(cap, _, eid, _, _) => {
469 let c: fn(_, _, _, _, _) -> _ = ExprKind::Closure;
472 CaptureClause::CaptureByValue => 0,
473 CaptureClause::CaptureByRef => 1,
476 self.hash_expr(&self.cx.tcx.hir().body(eid).value);
478 ExprKind::Field(ref e, ref f) => {
479 let c: fn(_, _) -> _ = ExprKind::Field;
482 self.hash_name(f.name);
484 ExprKind::Index(ref a, ref i) => {
485 let c: fn(_, _) -> _ = ExprKind::Index;
490 ExprKind::InlineAsm(..) => {
491 let c: fn(_, _, _) -> _ = ExprKind::InlineAsm;
494 ExprKind::If(ref cond, ref t, ref e) => {
495 let c: fn(_, _, _) -> _ = ExprKind::If;
497 self.hash_expr(cond);
498 self.hash_expr(&**t);
499 if let Some(ref e) = *e {
503 ExprKind::Lit(ref l) => {
504 let c: fn(_) -> _ = ExprKind::Lit;
508 ExprKind::Loop(ref b, ref i, _) => {
509 let c: fn(_, _, _) -> _ = ExprKind::Loop;
512 if let Some(i) = *i {
513 self.hash_name(i.ident.name);
516 ExprKind::Match(ref e, ref arms, ref s) => {
517 let c: fn(_, _, _) -> _ = ExprKind::Match;
523 if let Some(ref e) = arm.guard {
526 self.hash_expr(&arm.body);
531 ExprKind::MethodCall(ref path, ref _tys, ref args) => {
532 let c: fn(_, _, _) -> _ = ExprKind::MethodCall;
534 self.hash_name(path.ident.name);
535 self.hash_exprs(args);
537 ExprKind::Repeat(ref e, ref l_id) => {
538 let c: fn(_, _) -> _ = ExprKind::Repeat;
541 let full_table = self.tables;
542 self.tables = self.cx.tcx.body_tables(l_id.body);
543 self.hash_expr(&self.cx.tcx.hir().body(l_id.body).value);
544 self.tables = full_table;
546 ExprKind::Ret(ref e) => {
547 let c: fn(_) -> _ = ExprKind::Ret;
549 if let Some(ref e) = *e {
553 ExprKind::Path(ref qpath) => {
554 let c: fn(_) -> _ = ExprKind::Path;
556 self.hash_qpath(qpath);
558 ExprKind::Struct(ref path, ref fields, ref expr) => {
559 let c: fn(_, _, _) -> _ = ExprKind::Struct;
562 self.hash_qpath(path);
565 self.hash_name(f.ident.name);
566 self.hash_expr(&f.expr);
569 if let Some(ref e) = *expr {
573 ExprKind::Tup(ref tup) => {
574 let c: fn(_) -> _ = ExprKind::Tup;
576 self.hash_exprs(tup);
578 ExprKind::Type(ref e, ref _ty) => {
579 let c: fn(_, _) -> _ = ExprKind::Type;
584 ExprKind::Unary(lop, ref le) => {
585 let c: fn(_, _) -> _ = ExprKind::Unary;
588 lop.hash(&mut self.s);
591 ExprKind::Array(ref v) => {
592 let c: fn(_) -> _ = ExprKind::Array;
597 ExprKind::While(ref cond, ref b, l) => {
598 let c: fn(_, _, _) -> _ = ExprKind::While;
601 self.hash_expr(cond);
604 self.hash_name(l.ident.name);
611 pub fn hash_exprs(&mut self, e: &P<[Expr]>) {
617 pub fn hash_name(&mut self, n: Name) {
618 n.as_str().hash(&mut self.s);
621 pub fn hash_qpath(&mut self, p: &QPath) {
623 QPath::Resolved(_, ref path) => {
624 self.hash_path(path);
626 QPath::TypeRelative(_, ref path) => {
627 self.hash_name(path.ident.name);
630 // self.cx.tables.qpath_def(p, id).hash(&mut self.s);
633 pub fn hash_path(&mut self, p: &Path) {
634 p.is_global().hash(&mut self.s);
635 for p in &p.segments {
636 self.hash_name(p.ident.name);
640 pub fn hash_stmt(&mut self, b: &Stmt) {
642 StmtKind::Local(ref local) => {
643 let c: fn(_) -> _ = StmtKind::Local;
645 if let Some(ref init) = local.init {
646 self.hash_expr(init);
649 StmtKind::Item(..) => {
650 let c: fn(_) -> _ = StmtKind::Item;
653 StmtKind::Expr(ref expr) => {
654 let c: fn(_) -> _ = StmtKind::Expr;
656 self.hash_expr(expr);
658 StmtKind::Semi(ref expr) => {
659 let c: fn(_) -> _ = StmtKind::Semi;
661 self.hash_expr(expr);
666 pub fn hash_guard(&mut self, g: &Guard) {
668 Guard::If(ref expr) => {
669 let c: fn(_) -> _ = Guard::If;
671 self.hash_expr(expr);