1 use consts::{constant_simple, constant_context};
4 use rustc::ty::{TypeckTables};
5 use std::hash::{Hash, Hasher};
6 use std::collections::hash_map::DefaultHasher;
9 use utils::differing_macro_contexts;
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 (&StmtDecl(ref l, _), &StmtDecl(ref r, _)) => {
47 if let (&DeclLocal(ref l), &DeclLocal(ref r)) = (&l.node, &r.node) {
48 both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r)) && both(&l.init, &r.init, |l, r| self.eq_expr(l, r))
53 (&StmtExpr(ref l, _), &StmtExpr(ref r, _)) | (&StmtSemi(ref l, _), &StmtSemi(ref r, _)) => {
60 /// Check whether two blocks are the same.
61 pub fn eq_block(&mut self, left: &Block, right: &Block) -> bool {
62 over(&left.stmts, &right.stmts, |l, r| self.eq_stmt(l, r))
63 && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
66 pub fn eq_expr(&mut self, left: &Expr, right: &Expr) -> bool {
67 if self.ignore_fn && differing_macro_contexts(left.span, right.span) {
71 if let (Some(l), Some(r)) = (constant_simple(self.cx, self.tables, left), constant_simple(self.cx, self.tables, right)) {
77 match (&left.node, &right.node) {
78 (&ExprAddrOf(l_mut, ref le), &ExprAddrOf(r_mut, ref re)) => l_mut == r_mut && self.eq_expr(le, re),
79 (&ExprAgain(li), &ExprAgain(ri)) => {
80 both(&li.label, &ri.label, |l, r| l.name.as_str() == r.name.as_str())
82 (&ExprAssign(ref ll, ref lr), &ExprAssign(ref rl, ref rr)) => self.eq_expr(ll, rl) && self.eq_expr(lr, rr),
83 (&ExprAssignOp(ref lo, ref ll, ref lr), &ExprAssignOp(ref ro, ref rl, ref rr)) => {
84 lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
86 (&ExprBlock(ref l, _), &ExprBlock(ref r, _)) => self.eq_block(l, r),
87 (&ExprBinary(l_op, ref ll, ref lr), &ExprBinary(r_op, ref rl, ref rr)) => {
88 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
89 || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
90 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
93 (&ExprBreak(li, ref le), &ExprBreak(ri, ref re)) => {
94 both(&li.label, &ri.label, |l, r| l.name.as_str() == r.name.as_str())
95 && both(le, re, |l, r| self.eq_expr(l, r))
97 (&ExprBox(ref l), &ExprBox(ref r)) => self.eq_expr(l, r),
98 (&ExprCall(ref l_fun, ref l_args), &ExprCall(ref r_fun, ref r_args)) => {
99 !self.ignore_fn && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
101 (&ExprCast(ref lx, ref lt), &ExprCast(ref rx, ref rt)) |
102 (&ExprType(ref lx, ref lt), &ExprType(ref rx, ref rt)) => self.eq_expr(lx, rx) && self.eq_ty(lt, rt),
103 (&ExprField(ref l_f_exp, ref l_f_ident), &ExprField(ref r_f_exp, ref r_f_ident)) => {
104 l_f_ident.node == r_f_ident.node && self.eq_expr(l_f_exp, r_f_exp)
106 (&ExprIndex(ref la, ref li), &ExprIndex(ref ra, ref ri)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
107 (&ExprIf(ref lc, ref lt, ref le), &ExprIf(ref rc, ref rt, ref re)) => {
108 self.eq_expr(lc, rc) && self.eq_expr(&**lt, &**rt) && both(le, re, |l, r| self.eq_expr(l, r))
110 (&ExprLit(ref l), &ExprLit(ref r)) => l.node == r.node,
111 (&ExprLoop(ref lb, ref ll, ref lls), &ExprLoop(ref rb, ref rl, ref rls)) => {
112 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.name.as_str() == r.name.as_str())
114 (&ExprMatch(ref le, ref la, ref ls), &ExprMatch(ref re, ref ra, ref rs)) => {
115 ls == rs && self.eq_expr(le, re) && over(la, ra, |l, r| {
116 self.eq_expr(&l.body, &r.body) && both(&l.guard, &r.guard, |l, r| self.eq_expr(l, r))
117 && over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r))
120 (&ExprMethodCall(ref l_path, _, ref l_args), &ExprMethodCall(ref r_path, _, ref r_args)) => {
121 !self.ignore_fn && l_path == r_path && self.eq_exprs(l_args, r_args)
123 (&ExprRepeat(ref le, ll_id), &ExprRepeat(ref re, rl_id)) => {
124 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id));
125 let ll = celcx.expr(&self.cx.tcx.hir.body(ll_id).value);
126 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id));
127 let rl = celcx.expr(&self.cx.tcx.hir.body(rl_id).value);
129 self.eq_expr(le, re) && ll == rl
131 (&ExprRet(ref l), &ExprRet(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
132 (&ExprPath(ref l), &ExprPath(ref r)) => self.eq_qpath(l, r),
133 (&ExprStruct(ref l_path, ref lf, ref lo), &ExprStruct(ref r_path, ref rf, ref ro)) => {
134 self.eq_qpath(l_path, r_path) && both(lo, ro, |l, r| self.eq_expr(l, r))
135 && over(lf, rf, |l, r| self.eq_field(l, r))
137 (&ExprTup(ref l_tup), &ExprTup(ref r_tup)) => self.eq_exprs(l_tup, r_tup),
138 (&ExprUnary(l_op, ref le), &ExprUnary(r_op, ref re)) => l_op == r_op && self.eq_expr(le, re),
139 (&ExprArray(ref l), &ExprArray(ref r)) => self.eq_exprs(l, r),
140 (&ExprWhile(ref lc, ref lb, ref ll), &ExprWhile(ref rc, ref rb, ref rl)) => {
141 self.eq_expr(lc, rc) && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.name.as_str() == r.name.as_str())
147 fn eq_exprs(&mut self, left: &P<[Expr]>, right: &P<[Expr]>) -> bool {
148 over(left, right, |l, r| self.eq_expr(l, r))
151 fn eq_field(&mut self, left: &Field, right: &Field) -> bool {
152 left.name.node == right.name.node && self.eq_expr(&left.expr, &right.expr)
155 fn eq_lifetime(&mut self, left: &Lifetime, right: &Lifetime) -> bool {
156 left.name == right.name
159 /// Check whether two patterns are the same.
160 pub fn eq_pat(&mut self, left: &Pat, right: &Pat) -> bool {
161 match (&left.node, &right.node) {
162 (&PatKind::Box(ref l), &PatKind::Box(ref r)) => self.eq_pat(l, r),
163 (&PatKind::TupleStruct(ref lp, ref la, ls), &PatKind::TupleStruct(ref rp, ref ra, rs)) => {
164 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
166 (&PatKind::Binding(ref lb, _, ref li, ref lp), &PatKind::Binding(ref rb, _, ref ri, ref rp)) => {
167 lb == rb && li.node.as_str() == ri.node.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r))
169 (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
170 (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r),
171 (&PatKind::Tuple(ref l, ls), &PatKind::Tuple(ref r, rs)) => {
172 ls == rs && over(l, r, |l, r| self.eq_pat(l, r))
174 (&PatKind::Range(ref ls, ref le, ref li), &PatKind::Range(ref rs, ref re, ref ri)) => {
175 self.eq_expr(ls, rs) && self.eq_expr(le, re) && (*li == *ri)
177 (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => lm == rm && self.eq_pat(le, re),
178 (&PatKind::Slice(ref ls, ref li, ref le), &PatKind::Slice(ref rs, ref ri, ref re)) => {
179 over(ls, rs, |l, r| self.eq_pat(l, r)) && over(le, re, |l, r| self.eq_pat(l, r))
180 && both(li, ri, |l, r| self.eq_pat(l, r))
182 (&PatKind::Wild, &PatKind::Wild) => true,
187 fn eq_qpath(&mut self, left: &QPath, right: &QPath) -> bool {
188 match (left, right) {
189 (&QPath::Resolved(ref lty, ref lpath), &QPath::Resolved(ref rty, ref rpath)) => {
190 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
192 (&QPath::TypeRelative(ref lty, ref lseg), &QPath::TypeRelative(ref rty, ref rseg)) => {
193 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
199 fn eq_path(&mut self, left: &Path, right: &Path) -> bool {
200 left.is_global() == right.is_global()
201 && over(&left.segments, &right.segments, |l, r| self.eq_path_segment(l, r))
204 fn eq_path_parameters(&mut self, left: &PathParameters, right: &PathParameters) -> bool {
205 if !(left.parenthesized || right.parenthesized) {
206 over(&left.lifetimes, &right.lifetimes, |l, r| self.eq_lifetime(l, r))
207 && over(&left.types, &right.types, |l, r| self.eq_ty(l, r))
208 && over(&left.bindings, &right.bindings, |l, r| self.eq_type_binding(l, r))
209 } else if left.parenthesized && right.parenthesized {
210 over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
212 &Some(&left.bindings[0].ty),
213 &Some(&right.bindings[0].ty),
214 |l, r| self.eq_ty(l, r),
221 fn eq_path_segment(&mut self, left: &PathSegment, right: &PathSegment) -> bool {
222 // The == of idents doesn't work with different contexts,
223 // we have to be explicit about hygiene
224 if left.name.as_str() != right.name.as_str() {
227 match (&left.parameters, &right.parameters) {
228 (&None, &None) => true,
229 (&Some(ref l), &Some(ref r)) => self.eq_path_parameters(l, r),
234 fn eq_ty(&mut self, left: &Ty, right: &Ty) -> bool {
235 match (&left.node, &right.node) {
236 (&TySlice(ref l_vec), &TySlice(ref r_vec)) => self.eq_ty(l_vec, r_vec),
237 (&TyArray(ref lt, ll_id), &TyArray(ref rt, rl_id)) => {
238 let full_table = self.tables;
240 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id));
241 self.tables = self.cx.tcx.body_tables(ll_id);
242 let ll = celcx.expr(&self.cx.tcx.hir.body(ll_id).value);
244 let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id));
245 self.tables = self.cx.tcx.body_tables(rl_id);
246 let rl = celcx.expr(&self.cx.tcx.hir.body(rl_id).value);
248 let eq_ty = self.eq_ty(lt, rt);
249 self.tables = full_table;
252 (&TyPtr(ref l_mut), &TyPtr(ref r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty),
253 (&TyRptr(_, ref l_rmut), &TyRptr(_, ref r_rmut)) => {
254 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty)
256 (&TyPath(ref l), &TyPath(ref r)) => self.eq_qpath(l, r),
257 (&TyTup(ref l), &TyTup(ref r)) => over(l, r, |l, r| self.eq_ty(l, r)),
258 (&TyInfer, &TyInfer) => true,
263 fn eq_type_binding(&mut self, left: &TypeBinding, right: &TypeBinding) -> bool {
264 left.name == right.name && self.eq_ty(&left.ty, &right.ty)
268 fn swap_binop<'a>(binop: BinOp_, lhs: &'a Expr, rhs: &'a Expr) -> Option<(BinOp_, &'a Expr, &'a Expr)> {
270 BiAdd | BiMul | BiBitXor | BiBitAnd | BiEq | BiNe | BiBitOr => Some((binop, rhs, lhs)),
271 BiLt => Some((BiGt, rhs, lhs)),
272 BiLe => Some((BiGe, rhs, lhs)),
273 BiGe => Some((BiLe, rhs, lhs)),
274 BiGt => Some((BiLt, rhs, lhs)),
275 BiShl | BiShr | BiRem | BiSub | BiDiv | BiAnd | BiOr => None,
279 /// Check if the two `Option`s are both `None` or some equal values as per
281 fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
283 F: FnMut(&X, &X) -> bool,
286 .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
289 /// Check if two slices are equal as per `eq_fn`.
290 fn over<X, F>(left: &[X], right: &[X], mut eq_fn: F) -> bool
292 F: FnMut(&X, &X) -> bool,
294 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
298 /// Type used to hash an ast element. This is different from the `Hash` trait
299 /// on ast types as this
300 /// trait would consider IDs and spans.
302 /// All expressions kind are hashed, but some might have a weaker hash.
303 pub struct SpanlessHash<'a, 'tcx: 'a> {
304 /// Context used to evaluate constant expressions.
305 cx: &'a LateContext<'a, 'tcx>,
306 tables: &'a TypeckTables<'tcx>,
310 impl<'a, 'tcx: 'a> SpanlessHash<'a, 'tcx> {
311 pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckTables<'tcx>) -> Self {
315 s: DefaultHasher::new(),
319 pub fn finish(&self) -> u64 {
323 pub fn hash_block(&mut self, b: &Block) {
328 if let Some(ref e) = b.expr {
332 b.rules.hash(&mut self.s);
335 #[allow(many_single_char_names)]
336 pub fn hash_expr(&mut self, e: &Expr) {
337 if let Some(e) = constant_simple(self.cx, self.tables, e) {
338 return e.hash(&mut self.s);
342 ExprAddrOf(m, ref e) => {
343 let c: fn(_, _) -> _ = ExprAddrOf;
349 let c: fn(_) -> _ = ExprAgain;
351 if let Some(i) = i.label {
352 self.hash_name(&i.name);
355 ExprYield(ref e) => {
356 let c: fn(_) -> _ = ExprYield;
360 ExprAssign(ref l, ref r) => {
361 let c: fn(_, _) -> _ = ExprAssign;
366 ExprAssignOp(ref o, ref l, ref r) => {
367 let c: fn(_, _, _) -> _ = ExprAssignOp;
373 ExprBlock(ref b, _) => {
374 let c: fn(_, _) -> _ = ExprBlock;
378 ExprBinary(op, ref l, ref r) => {
379 let c: fn(_, _, _) -> _ = ExprBinary;
381 op.node.hash(&mut self.s);
385 ExprBreak(i, ref j) => {
386 let c: fn(_, _) -> _ = ExprBreak;
388 if let Some(i) = i.label {
389 self.hash_name(&i.name);
391 if let Some(ref j) = *j {
396 let c: fn(_) -> _ = ExprBox;
400 ExprCall(ref fun, ref args) => {
401 let c: fn(_, _) -> _ = ExprCall;
404 self.hash_exprs(args);
406 ExprCast(ref e, ref _ty) => {
407 let c: fn(_, _) -> _ = ExprCast;
412 ExprClosure(cap, _, eid, _, _) => {
413 let c: fn(_, _, _, _, _) -> _ = ExprClosure;
415 cap.hash(&mut self.s);
416 self.hash_expr(&self.cx.tcx.hir.body(eid).value);
418 ExprField(ref e, ref f) => {
419 let c: fn(_, _) -> _ = ExprField;
422 self.hash_name(&f.node);
424 ExprIndex(ref a, ref i) => {
425 let c: fn(_, _) -> _ = ExprIndex;
430 ExprInlineAsm(..) => {
431 let c: fn(_, _, _) -> _ = ExprInlineAsm;
434 ExprIf(ref cond, ref t, ref e) => {
435 let c: fn(_, _, _) -> _ = ExprIf;
437 self.hash_expr(cond);
438 self.hash_expr(&**t);
439 if let Some(ref e) = *e {
444 let c: fn(_) -> _ = ExprLit;
448 ExprLoop(ref b, ref i, _) => {
449 let c: fn(_, _, _) -> _ = ExprLoop;
452 if let Some(i) = *i {
453 self.hash_name(&i.name);
456 ExprMatch(ref e, ref arms, ref s) => {
457 let c: fn(_, _, _) -> _ = ExprMatch;
463 if let Some(ref e) = arm.guard {
466 self.hash_expr(&arm.body);
471 ExprMethodCall(ref path, ref _tys, ref args) => {
472 let c: fn(_, _, _) -> _ = ExprMethodCall;
474 self.hash_name(&path.name);
475 self.hash_exprs(args);
477 ExprRepeat(ref e, l_id) => {
478 let c: fn(_, _) -> _ = ExprRepeat;
481 let full_table = self.tables;
482 self.tables = self.cx.tcx.body_tables(l_id);
483 self.hash_expr(&self.cx.tcx.hir.body(l_id).value);
484 self.tables = full_table;
487 let c: fn(_) -> _ = ExprRet;
489 if let Some(ref e) = *e {
493 ExprPath(ref qpath) => {
494 let c: fn(_) -> _ = ExprPath;
496 self.hash_qpath(qpath);
498 ExprStruct(ref path, ref fields, ref expr) => {
499 let c: fn(_, _, _) -> _ = ExprStruct;
502 self.hash_qpath(path);
505 self.hash_name(&f.name.node);
506 self.hash_expr(&f.expr);
509 if let Some(ref e) = *expr {
513 ExprTup(ref tup) => {
514 let c: fn(_) -> _ = ExprTup;
516 self.hash_exprs(tup);
518 ExprType(ref e, ref _ty) => {
519 let c: fn(_, _) -> _ = ExprType;
524 ExprUnary(lop, ref le) => {
525 let c: fn(_, _) -> _ = ExprUnary;
528 lop.hash(&mut self.s);
531 ExprArray(ref v) => {
532 let c: fn(_) -> _ = ExprArray;
537 ExprWhile(ref cond, ref b, l) => {
538 let c: fn(_, _, _) -> _ = ExprWhile;
541 self.hash_expr(cond);
544 self.hash_name(&l.name);
550 pub fn hash_exprs(&mut self, e: &P<[Expr]>) {
556 pub fn hash_name(&mut self, n: &Name) {
557 n.as_str().hash(&mut self.s);
560 pub fn hash_qpath(&mut self, p: &QPath) {
562 QPath::Resolved(_, ref path) => {
563 self.hash_path(path);
565 QPath::TypeRelative(_, ref path) => {
566 self.hash_name(&path.name);
569 // self.cx.tables.qpath_def(p, id).hash(&mut self.s);
572 pub fn hash_path(&mut self, p: &Path) {
573 p.is_global().hash(&mut self.s);
574 for p in &p.segments {
575 self.hash_name(&p.name);
579 pub fn hash_stmt(&mut self, b: &Stmt) {
581 StmtDecl(ref decl, _) => {
582 let c: fn(_, _) -> _ = StmtDecl;
585 if let DeclLocal(ref local) = decl.node {
586 if let Some(ref init) = local.init {
587 self.hash_expr(init);
591 StmtExpr(ref expr, _) => {
592 let c: fn(_, _) -> _ = StmtExpr;
594 self.hash_expr(expr);
596 StmtSemi(ref expr, _) => {
597 let c: fn(_, _) -> _ = StmtSemi;
599 self.hash_expr(expr);