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 /// Checks 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 /// Checks 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::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
118 (&ExprKind::Loop(ref lb, ref ll, ref lls), &ExprKind::Loop(ref rb, ref rl, ref rls)) => {
119 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
121 (&ExprKind::Match(ref le, ref la, ref ls), &ExprKind::Match(ref re, ref ra, ref rs)) => {
123 && self.eq_expr(le, re)
124 && over(la, ra, |l, r| {
125 self.eq_expr(&l.body, &r.body)
126 && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
127 && over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r))
130 (&ExprKind::MethodCall(ref l_path, _, ref l_args), &ExprKind::MethodCall(ref r_path, _, ref r_args)) => {
131 !self.ignore_fn && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
133 (&ExprKind::Repeat(ref le, ref ll_id), &ExprKind::Repeat(ref re, ref rl_id)) => {
134 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
135 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
136 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
137 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
139 self.eq_expr(le, re) && ll == rl
141 (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
142 (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
143 (&ExprKind::Struct(ref l_path, ref lf, ref lo), &ExprKind::Struct(ref r_path, ref rf, ref ro)) => {
144 self.eq_qpath(l_path, r_path)
145 && both(lo, ro, |l, r| self.eq_expr(l, r))
146 && over(lf, rf, |l, r| self.eq_field(l, r))
148 (&ExprKind::Tup(ref l_tup), &ExprKind::Tup(ref r_tup)) => self.eq_exprs(l_tup, r_tup),
149 (&ExprKind::Unary(l_op, ref le), &ExprKind::Unary(r_op, ref re)) => l_op == r_op && self.eq_expr(le, re),
150 (&ExprKind::Array(ref l), &ExprKind::Array(ref r)) => self.eq_exprs(l, r),
151 (&ExprKind::While(ref lc, ref lb, ref ll), &ExprKind::While(ref rc, ref rb, ref rl)) => {
153 && self.eq_block(lb, rb)
154 && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str())
156 (&ExprKind::DropTemps(ref le), &ExprKind::DropTemps(ref re)) => self.eq_expr(le, re),
161 fn eq_exprs(&mut self, left: &P<[Expr]>, right: &P<[Expr]>) -> bool {
162 over(left, right, |l, r| self.eq_expr(l, r))
165 fn eq_field(&mut self, left: &Field, right: &Field) -> bool {
166 left.ident.name == right.ident.name && self.eq_expr(&left.expr, &right.expr)
169 fn eq_guard(&mut self, left: &Guard, right: &Guard) -> bool {
170 match (left, right) {
171 (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
175 fn eq_generic_arg(&mut self, left: &GenericArg, right: &GenericArg) -> bool {
176 match (left, right) {
177 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => self.eq_lifetime(l_lt, r_lt),
178 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
183 fn eq_lifetime(&mut self, left: &Lifetime, right: &Lifetime) -> bool {
184 left.name == right.name
187 /// Checks whether two patterns are the same.
188 pub fn eq_pat(&mut self, left: &Pat, right: &Pat) -> bool {
189 match (&left.node, &right.node) {
190 (&PatKind::Box(ref l), &PatKind::Box(ref r)) => self.eq_pat(l, r),
191 (&PatKind::TupleStruct(ref lp, ref la, ls), &PatKind::TupleStruct(ref rp, ref ra, rs)) => {
192 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
194 (&PatKind::Binding(ref lb, .., ref li, ref lp), &PatKind::Binding(ref rb, .., ref ri, ref rp)) => {
195 lb == rb && li.name.as_str() == ri.name.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r))
197 (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
198 (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r),
199 (&PatKind::Tuple(ref l, ls), &PatKind::Tuple(ref r, rs)) => {
200 ls == rs && over(l, r, |l, r| self.eq_pat(l, r))
202 (&PatKind::Range(ref ls, ref le, ref li), &PatKind::Range(ref rs, ref re, ref ri)) => {
203 self.eq_expr(ls, rs) && self.eq_expr(le, re) && (*li == *ri)
205 (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => lm == rm && self.eq_pat(le, re),
206 (&PatKind::Slice(ref ls, ref li, ref le), &PatKind::Slice(ref rs, ref ri, ref re)) => {
207 over(ls, rs, |l, r| self.eq_pat(l, r))
208 && over(le, re, |l, r| self.eq_pat(l, r))
209 && both(li, ri, |l, r| self.eq_pat(l, r))
211 (&PatKind::Wild, &PatKind::Wild) => true,
216 #[allow(clippy::similar_names)]
217 fn eq_qpath(&mut self, left: &QPath, right: &QPath) -> bool {
218 match (left, right) {
219 (&QPath::Resolved(ref lty, ref lpath), &QPath::Resolved(ref rty, ref rpath)) => {
220 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
222 (&QPath::TypeRelative(ref lty, ref lseg), &QPath::TypeRelative(ref rty, ref rseg)) => {
223 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
229 fn eq_path(&mut self, left: &Path, right: &Path) -> bool {
230 left.is_global() == right.is_global()
231 && over(&left.segments, &right.segments, |l, r| self.eq_path_segment(l, r))
234 fn eq_path_parameters(&mut self, left: &GenericArgs, right: &GenericArgs) -> bool {
235 if !(left.parenthesized || right.parenthesized) {
236 over(&left.args, &right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
237 && over(&left.bindings, &right.bindings, |l, r| self.eq_type_binding(l, r))
238 } else if left.parenthesized && right.parenthesized {
239 over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
240 && both(&Some(&left.bindings[0].ty), &Some(&right.bindings[0].ty), |l, r| {
248 pub fn eq_path_segments(&mut self, left: &[PathSegment], right: &[PathSegment]) -> bool {
249 left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
252 pub fn eq_path_segment(&mut self, left: &PathSegment, right: &PathSegment) -> bool {
253 // The == of idents doesn't work with different contexts,
254 // we have to be explicit about hygiene
255 if left.ident.as_str() != right.ident.as_str() {
258 match (&left.args, &right.args) {
259 (&None, &None) => true,
260 (&Some(ref l), &Some(ref r)) => self.eq_path_parameters(l, r),
265 pub fn eq_ty(&mut self, left: &Ty, right: &Ty) -> bool {
266 self.eq_ty_kind(&left.node, &right.node)
269 #[allow(clippy::similar_names)]
270 pub fn eq_ty_kind(&mut self, left: &TyKind, right: &TyKind) -> bool {
271 match (left, right) {
272 (&TyKind::Slice(ref l_vec), &TyKind::Slice(ref r_vec)) => self.eq_ty(l_vec, r_vec),
273 (&TyKind::Array(ref lt, ref ll_id), &TyKind::Array(ref rt, ref rl_id)) => {
274 let full_table = self.tables;
276 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body));
277 self.tables = self.cx.tcx.body_tables(ll_id.body);
278 let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value);
280 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body));
281 self.tables = self.cx.tcx.body_tables(rl_id.body);
282 let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value);
284 let eq_ty = self.eq_ty(lt, rt);
285 self.tables = full_table;
288 (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
289 l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty)
291 (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
292 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
294 (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
295 (&TyKind::Tup(ref l), &TyKind::Tup(ref r)) => over(l, r, |l, r| self.eq_ty(l, r)),
296 (&TyKind::Infer, &TyKind::Infer) => true,
301 fn eq_type_binding(&mut self, left: &TypeBinding, right: &TypeBinding) -> bool {
302 left.ident.name == right.ident.name && self.eq_ty(&left.ty, &right.ty)
306 fn swap_binop<'a>(binop: BinOpKind, lhs: &'a Expr, rhs: &'a Expr) -> Option<(BinOpKind, &'a Expr, &'a Expr)> {
314 | BinOpKind::BitOr => Some((binop, rhs, lhs)),
315 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
316 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
317 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
318 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
325 | BinOpKind::Or => None,
329 /// Checks if the two `Option`s are both `None` or some equal values as per
331 fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
333 F: FnMut(&X, &X) -> bool,
336 .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
339 /// Checks if two slices are equal as per `eq_fn`.
340 fn over<X, F>(left: &[X], right: &[X], mut eq_fn: F) -> bool
342 F: FnMut(&X, &X) -> bool,
344 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
347 /// Type used to hash an ast element. This is different from the `Hash` trait
348 /// on ast types as this
349 /// trait would consider IDs and spans.
351 /// All expressions kind are hashed, but some might have a weaker hash.
352 pub struct SpanlessHash<'a, 'tcx: 'a> {
353 /// Context used to evaluate constant expressions.
354 cx: &'a LateContext<'a, 'tcx>,
355 tables: &'a TypeckTables<'tcx>,
359 impl<'a, 'tcx: 'a> SpanlessHash<'a, 'tcx> {
360 pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckTables<'tcx>) -> Self {
364 s: DefaultHasher::new(),
368 pub fn finish(&self) -> u64 {
372 pub fn hash_block(&mut self, b: &Block) {
377 if let Some(ref e) = b.expr {
382 BlockCheckMode::DefaultBlock => 0,
383 BlockCheckMode::UnsafeBlock(_) => 1,
384 BlockCheckMode::PushUnsafeBlock(_) => 2,
385 BlockCheckMode::PopUnsafeBlock(_) => 3,
390 #[allow(clippy::many_single_char_names, clippy::too_many_lines)]
391 pub fn hash_expr(&mut self, e: &Expr) {
392 let simple_const = constant_simple(self.cx, self.tables, e);
394 // const hashing may result in the same hash as some unrelated node, so add a sort of
395 // discriminant depending on which path we're choosing next
396 simple_const.is_some().hash(&mut self.s);
398 if let Some(e) = simple_const {
399 return e.hash(&mut self.s);
402 std::mem::discriminant(&e.node).hash(&mut self.s);
405 ExprKind::AddrOf(m, ref e) => {
406 let c: fn(_, _) -> _ = ExprKind::AddrOf;
411 ExprKind::Continue(i) => {
412 let c: fn(_) -> _ = ExprKind::Continue;
414 if let Some(i) = i.label {
415 self.hash_name(i.ident.name);
418 ExprKind::Yield(ref e) => {
419 let c: fn(_) -> _ = ExprKind::Yield;
423 ExprKind::Assign(ref l, ref r) => {
424 let c: fn(_, _) -> _ = ExprKind::Assign;
429 ExprKind::AssignOp(ref o, ref l, ref r) => {
430 let c: fn(_, _, _) -> _ = ExprKind::AssignOp;
436 ExprKind::Block(ref b, _) => {
437 let c: fn(_, _) -> _ = ExprKind::Block;
441 ExprKind::Binary(op, ref l, ref r) => {
442 let c: fn(_, _, _) -> _ = ExprKind::Binary;
444 op.node.hash(&mut self.s);
448 ExprKind::Break(i, ref j) => {
449 let c: fn(_, _) -> _ = ExprKind::Break;
451 if let Some(i) = i.label {
452 self.hash_name(i.ident.name);
454 if let Some(ref j) = *j {
458 ExprKind::Box(ref e) => {
459 let c: fn(_) -> _ = ExprKind::Box;
463 ExprKind::Call(ref fun, ref args) => {
464 let c: fn(_, _) -> _ = ExprKind::Call;
467 self.hash_exprs(args);
469 ExprKind::Cast(ref e, ref _ty) => {
470 let c: fn(_, _) -> _ = ExprKind::Cast;
475 ExprKind::Closure(cap, _, eid, _, _) => {
476 let c: fn(_, _, _, _, _) -> _ = ExprKind::Closure;
479 CaptureClause::CaptureByValue => 0,
480 CaptureClause::CaptureByRef => 1,
483 self.hash_expr(&self.cx.tcx.hir().body(eid).value);
485 ExprKind::Field(ref e, ref f) => {
486 let c: fn(_, _) -> _ = ExprKind::Field;
489 self.hash_name(f.name);
491 ExprKind::Index(ref a, ref i) => {
492 let c: fn(_, _) -> _ = ExprKind::Index;
497 ExprKind::InlineAsm(..) => {
498 let c: fn(_, _, _) -> _ = ExprKind::InlineAsm;
501 ExprKind::Lit(ref l) => {
502 let c: fn(_) -> _ = ExprKind::Lit;
506 ExprKind::Loop(ref b, ref i, _) => {
507 let c: fn(_, _, _) -> _ = ExprKind::Loop;
510 if let Some(i) = *i {
511 self.hash_name(i.ident.name);
514 ExprKind::Match(ref e, ref arms, ref s) => {
515 let c: fn(_, _, _) -> _ = ExprKind::Match;
521 if let Some(ref e) = arm.guard {
524 self.hash_expr(&arm.body);
529 ExprKind::MethodCall(ref path, ref _tys, ref args) => {
530 let c: fn(_, _, _) -> _ = ExprKind::MethodCall;
532 self.hash_name(path.ident.name);
533 self.hash_exprs(args);
535 ExprKind::Repeat(ref e, ref l_id) => {
536 let c: fn(_, _) -> _ = ExprKind::Repeat;
539 let full_table = self.tables;
540 self.tables = self.cx.tcx.body_tables(l_id.body);
541 self.hash_expr(&self.cx.tcx.hir().body(l_id.body).value);
542 self.tables = full_table;
544 ExprKind::Ret(ref e) => {
545 let c: fn(_) -> _ = ExprKind::Ret;
547 if let Some(ref e) = *e {
551 ExprKind::Path(ref qpath) => {
552 let c: fn(_) -> _ = ExprKind::Path;
554 self.hash_qpath(qpath);
556 ExprKind::Struct(ref path, ref fields, ref expr) => {
557 let c: fn(_, _, _) -> _ = ExprKind::Struct;
560 self.hash_qpath(path);
563 self.hash_name(f.ident.name);
564 self.hash_expr(&f.expr);
567 if let Some(ref e) = *expr {
571 ExprKind::Tup(ref tup) => {
572 let c: fn(_) -> _ = ExprKind::Tup;
574 self.hash_exprs(tup);
576 ExprKind::Type(ref e, ref _ty) => {
577 let c: fn(_, _) -> _ = ExprKind::Type;
582 ExprKind::Unary(lop, ref le) => {
583 let c: fn(_, _) -> _ = ExprKind::Unary;
586 lop.hash(&mut self.s);
589 ExprKind::Array(ref v) => {
590 let c: fn(_) -> _ = ExprKind::Array;
595 ExprKind::While(ref cond, ref b, l) => {
596 let c: fn(_, _, _) -> _ = ExprKind::While;
599 self.hash_expr(cond);
602 self.hash_name(l.ident.name);
606 ExprKind::DropTemps(ref e) => {
607 let c: fn(_) -> _ = ExprKind::DropTemps;
614 pub fn hash_exprs(&mut self, e: &P<[Expr]>) {
620 pub fn hash_name(&mut self, n: Name) {
621 n.as_str().hash(&mut self.s);
624 pub fn hash_qpath(&mut self, p: &QPath) {
626 QPath::Resolved(_, ref path) => {
627 self.hash_path(path);
629 QPath::TypeRelative(_, ref path) => {
630 self.hash_name(path.ident.name);
633 // self.cx.tables.qpath_res(p, id).hash(&mut self.s);
636 pub fn hash_path(&mut self, p: &Path) {
637 p.is_global().hash(&mut self.s);
638 for p in &p.segments {
639 self.hash_name(p.ident.name);
643 pub fn hash_stmt(&mut self, b: &Stmt) {
645 StmtKind::Local(ref local) => {
646 let c: fn(_) -> _ = StmtKind::Local;
648 if let Some(ref init) = local.init {
649 self.hash_expr(init);
652 StmtKind::Item(..) => {
653 let c: fn(_) -> _ = StmtKind::Item;
656 StmtKind::Expr(ref expr) => {
657 let c: fn(_) -> _ = StmtKind::Expr;
659 self.hash_expr(expr);
661 StmtKind::Semi(ref expr) => {
662 let c: fn(_) -> _ = StmtKind::Semi;
664 self.hash_expr(expr);
669 pub fn hash_guard(&mut self, g: &Guard) {
671 Guard::If(ref expr) => {
672 let c: fn(_) -> _ = Guard::If;
674 self.hash_expr(expr);