]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ast_utils.rs
Merge remote-tracking branch 'upstream/beta' into backport_remerge
[rust.git] / clippy_utils / src / ast_utils.rs
1 //! Utilities for manipulating and extracting information from `rustc_ast::ast`.
2 //!
3 //! - The `eq_foobar` functions test for semantic equality but ignores `NodeId`s and `Span`s.
4
5 #![allow(clippy::similar_names, clippy::wildcard_imports, clippy::enum_glob_use)]
6
7 use crate::{both, over};
8 use if_chain::if_chain;
9 use rustc_ast::ptr::P;
10 use rustc_ast::{self as ast, *};
11 use rustc_span::symbol::Ident;
12 use std::mem;
13
14 pub mod ident_iter;
15 pub use ident_iter::IdentIter;
16
17 pub fn is_useless_with_eq_exprs(kind: BinOpKind) -> bool {
18     use BinOpKind::*;
19     matches!(
20         kind,
21         Sub | Div | Eq | Lt | Le | Gt | Ge | Ne | And | Or | BitXor | BitAnd | BitOr
22     )
23 }
24
25 /// Checks if each element in the first slice is contained within the latter as per `eq_fn`.
26 pub fn unordered_over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
27     left.len() == right.len() && left.iter().all(|l| right.iter().any(|r| eq_fn(l, r)))
28 }
29
30 pub fn eq_id(l: Ident, r: Ident) -> bool {
31     l.name == r.name
32 }
33
34 pub fn eq_pat(l: &Pat, r: &Pat) -> bool {
35     use PatKind::*;
36     match (&l.kind, &r.kind) {
37         (Paren(l), _) => eq_pat(l, r),
38         (_, Paren(r)) => eq_pat(l, r),
39         (Wild, Wild) | (Rest, Rest) => true,
40         (Lit(l), Lit(r)) => eq_expr(l, r),
41         (Ident(b1, i1, s1), Ident(b2, i2, s2)) => b1 == b2 && eq_id(*i1, *i2) && both(s1, s2, |l, r| eq_pat(l, r)),
42         (Range(lf, lt, le), Range(rf, rt, re)) => {
43             eq_expr_opt(lf, rf) && eq_expr_opt(lt, rt) && eq_range_end(&le.node, &re.node)
44         },
45         (Box(l), Box(r))
46         | (Ref(l, Mutability::Not), Ref(r, Mutability::Not))
47         | (Ref(l, Mutability::Mut), Ref(r, Mutability::Mut)) => eq_pat(l, r),
48         (Tuple(l), Tuple(r)) | (Slice(l), Slice(r)) => over(l, r, |l, r| eq_pat(l, r)),
49         (Path(lq, lp), Path(rq, rp)) => both(lq, rq, eq_qself) && eq_path(lp, rp),
50         (TupleStruct(lqself, lp, lfs), TupleStruct(rqself, rp, rfs)) => {
51             eq_maybe_qself(lqself, rqself) && eq_path(lp, rp) && over(lfs, rfs, |l, r| eq_pat(l, r))
52         },
53         (Struct(lqself, lp, lfs, lr), Struct(rqself, rp, rfs, rr)) => {
54             lr == rr && eq_maybe_qself(lqself, rqself) && eq_path(lp, rp) && unordered_over(lfs, rfs, eq_field_pat)
55         },
56         (Or(ls), Or(rs)) => unordered_over(ls, rs, |l, r| eq_pat(l, r)),
57         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
58         _ => false,
59     }
60 }
61
62 pub fn eq_range_end(l: &RangeEnd, r: &RangeEnd) -> bool {
63     match (l, r) {
64         (RangeEnd::Excluded, RangeEnd::Excluded) => true,
65         (RangeEnd::Included(l), RangeEnd::Included(r)) => {
66             matches!(l, RangeSyntax::DotDotEq) == matches!(r, RangeSyntax::DotDotEq)
67         },
68         _ => false,
69     }
70 }
71
72 pub fn eq_field_pat(l: &PatField, r: &PatField) -> bool {
73     l.is_placeholder == r.is_placeholder
74         && eq_id(l.ident, r.ident)
75         && eq_pat(&l.pat, &r.pat)
76         && over(&l.attrs, &r.attrs, eq_attr)
77 }
78
79 pub fn eq_qself(l: &QSelf, r: &QSelf) -> bool {
80     l.position == r.position && eq_ty(&l.ty, &r.ty)
81 }
82
83 pub fn eq_maybe_qself(l: &Option<QSelf>, r: &Option<QSelf>) -> bool {
84     match (l, r) {
85         (Some(l), Some(r)) => eq_qself(l, r),
86         (None, None) => true,
87         _ => false,
88     }
89 }
90
91 pub fn eq_path(l: &Path, r: &Path) -> bool {
92     over(&l.segments, &r.segments, eq_path_seg)
93 }
94
95 pub fn eq_path_seg(l: &PathSegment, r: &PathSegment) -> bool {
96     eq_id(l.ident, r.ident) && both(&l.args, &r.args, |l, r| eq_generic_args(l, r))
97 }
98
99 pub fn eq_generic_args(l: &GenericArgs, r: &GenericArgs) -> bool {
100     match (l, r) {
101         (GenericArgs::AngleBracketed(l), GenericArgs::AngleBracketed(r)) => over(&l.args, &r.args, eq_angle_arg),
102         (GenericArgs::Parenthesized(l), GenericArgs::Parenthesized(r)) => {
103             over(&l.inputs, &r.inputs, |l, r| eq_ty(l, r)) && eq_fn_ret_ty(&l.output, &r.output)
104         },
105         _ => false,
106     }
107 }
108
109 pub fn eq_angle_arg(l: &AngleBracketedArg, r: &AngleBracketedArg) -> bool {
110     match (l, r) {
111         (AngleBracketedArg::Arg(l), AngleBracketedArg::Arg(r)) => eq_generic_arg(l, r),
112         (AngleBracketedArg::Constraint(l), AngleBracketedArg::Constraint(r)) => eq_assoc_constraint(l, r),
113         _ => false,
114     }
115 }
116
117 pub fn eq_generic_arg(l: &GenericArg, r: &GenericArg) -> bool {
118     match (l, r) {
119         (GenericArg::Lifetime(l), GenericArg::Lifetime(r)) => eq_id(l.ident, r.ident),
120         (GenericArg::Type(l), GenericArg::Type(r)) => eq_ty(l, r),
121         (GenericArg::Const(l), GenericArg::Const(r)) => eq_expr(&l.value, &r.value),
122         _ => false,
123     }
124 }
125
126 pub fn eq_expr_opt(l: &Option<P<Expr>>, r: &Option<P<Expr>>) -> bool {
127     both(l, r, |l, r| eq_expr(l, r))
128 }
129
130 pub fn eq_struct_rest(l: &StructRest, r: &StructRest) -> bool {
131     match (l, r) {
132         (StructRest::Base(lb), StructRest::Base(rb)) => eq_expr(lb, rb),
133         (StructRest::Rest(_), StructRest::Rest(_)) | (StructRest::None, StructRest::None) => true,
134         _ => false,
135     }
136 }
137
138 pub fn eq_expr(l: &Expr, r: &Expr) -> bool {
139     use ExprKind::*;
140     if !over(&l.attrs, &r.attrs, eq_attr) {
141         return false;
142     }
143     match (&l.kind, &r.kind) {
144         (Paren(l), _) => eq_expr(l, r),
145         (_, Paren(r)) => eq_expr(l, r),
146         (Err, Err) => true,
147         (Box(l), Box(r)) | (Try(l), Try(r)) | (Await(l), Await(r)) => eq_expr(l, r),
148         (Array(l), Array(r)) | (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)),
149         (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value),
150         (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
151         (MethodCall(lc, la, _), MethodCall(rc, ra, _)) => eq_path_seg(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
152         (Binary(lo, ll, lr), Binary(ro, rl, rr)) => lo.node == ro.node && eq_expr(ll, rl) && eq_expr(lr, rr),
153         (Unary(lo, l), Unary(ro, r)) => mem::discriminant(lo) == mem::discriminant(ro) && eq_expr(l, r),
154         (Lit(l), Lit(r)) => l.kind == r.kind,
155         (Cast(l, lt), Cast(r, rt)) | (Type(l, lt), Type(r, rt)) => eq_expr(l, r) && eq_ty(lt, rt),
156         (Let(lp, le, _), Let(rp, re, _)) => eq_pat(lp, rp) && eq_expr(le, re),
157         (If(lc, lt, le), If(rc, rt, re)) => eq_expr(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le, re),
158         (While(lc, lt, ll), While(rc, rt, rl)) => eq_label(ll, rl) && eq_expr(lc, rc) && eq_block(lt, rt),
159         (ForLoop(lp, li, lt, ll), ForLoop(rp, ri, rt, rl)) => {
160             eq_label(ll, rl) && eq_pat(lp, rp) && eq_expr(li, ri) && eq_block(lt, rt)
161         },
162         (Loop(lt, ll), Loop(rt, rl)) => eq_label(ll, rl) && eq_block(lt, rt),
163         (Block(lb, ll), Block(rb, rl)) => eq_label(ll, rl) && eq_block(lb, rb),
164         (TryBlock(l), TryBlock(r)) => eq_block(l, r),
165         (Yield(l), Yield(r)) | (Ret(l), Ret(r)) => eq_expr_opt(l, r),
166         (Break(ll, le), Break(rl, re)) => eq_label(ll, rl) && eq_expr_opt(le, re),
167         (Continue(ll), Continue(rl)) => eq_label(ll, rl),
168         (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2), Index(r1, r2)) => eq_expr(l1, r1) && eq_expr(l2, r2),
169         (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
170         (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
171         (Match(ls, la), Match(rs, ra)) => eq_expr(ls, rs) && over(la, ra, eq_arm),
172         (Closure(lc, la, lm, lf, lb, _), Closure(rc, ra, rm, rf, rb, _)) => {
173             lc == rc && la.is_async() == ra.is_async() && lm == rm && eq_fn_decl(lf, rf) && eq_expr(lb, rb)
174         },
175         (Async(lc, _, lb), Async(rc, _, rb)) => lc == rc && eq_block(lb, rb),
176         (Range(lf, lt, ll), Range(rf, rt, rl)) => ll == rl && eq_expr_opt(lf, rf) && eq_expr_opt(lt, rt),
177         (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
178         (Path(lq, lp), Path(rq, rp)) => both(lq, rq, eq_qself) && eq_path(lp, rp),
179         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
180         (Struct(lse), Struct(rse)) => {
181             eq_maybe_qself(&lse.qself, &rse.qself)
182                 && eq_path(&lse.path, &rse.path)
183                 && eq_struct_rest(&lse.rest, &rse.rest)
184                 && unordered_over(&lse.fields, &rse.fields, eq_field)
185         },
186         _ => false,
187     }
188 }
189
190 pub fn eq_field(l: &ExprField, r: &ExprField) -> bool {
191     l.is_placeholder == r.is_placeholder
192         && eq_id(l.ident, r.ident)
193         && eq_expr(&l.expr, &r.expr)
194         && over(&l.attrs, &r.attrs, eq_attr)
195 }
196
197 pub fn eq_arm(l: &Arm, r: &Arm) -> bool {
198     l.is_placeholder == r.is_placeholder
199         && eq_pat(&l.pat, &r.pat)
200         && eq_expr(&l.body, &r.body)
201         && eq_expr_opt(&l.guard, &r.guard)
202         && over(&l.attrs, &r.attrs, eq_attr)
203 }
204
205 pub fn eq_label(l: &Option<Label>, r: &Option<Label>) -> bool {
206     both(l, r, |l, r| eq_id(l.ident, r.ident))
207 }
208
209 pub fn eq_block(l: &Block, r: &Block) -> bool {
210     l.rules == r.rules && over(&l.stmts, &r.stmts, eq_stmt)
211 }
212
213 pub fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
214     use StmtKind::*;
215     match (&l.kind, &r.kind) {
216         (Local(l), Local(r)) => {
217             eq_pat(&l.pat, &r.pat)
218                 && both(&l.ty, &r.ty, |l, r| eq_ty(l, r))
219                 && eq_local_kind(&l.kind, &r.kind)
220                 && over(&l.attrs, &r.attrs, eq_attr)
221         },
222         (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
223         (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
224         (Empty, Empty) => true,
225         (MacCall(l), MacCall(r)) => {
226             l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, eq_attr)
227         },
228         _ => false,
229     }
230 }
231
232 pub fn eq_local_kind(l: &LocalKind, r: &LocalKind) -> bool {
233     use LocalKind::*;
234     match (l, r) {
235         (Decl, Decl) => true,
236         (Init(l), Init(r)) => eq_expr(l, r),
237         (InitElse(li, le), InitElse(ri, re)) => eq_expr(li, ri) && eq_block(le, re),
238         _ => false,
239     }
240 }
241
242 pub fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
243     eq_id(l.ident, r.ident) && over(&l.attrs, &r.attrs, eq_attr) && eq_vis(&l.vis, &r.vis) && eq_kind(&l.kind, &r.kind)
244 }
245
246 #[allow(clippy::too_many_lines)] // Just a big match statement
247 pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
248     use ItemKind::*;
249     match (l, r) {
250         (ExternCrate(l), ExternCrate(r)) => l == r,
251         (Use(l), Use(r)) => eq_use_tree(l, r),
252         (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
253         (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
254         (
255             Fn(box ast::Fn {
256                 defaultness: ld,
257                 sig: lf,
258                 generics: lg,
259                 body: lb,
260             }),
261             Fn(box ast::Fn {
262                 defaultness: rd,
263                 sig: rf,
264                 generics: rg,
265                 body: rb,
266             }),
267         ) => {
268             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
269         },
270         (Mod(lu, lmk), Mod(ru, rmk)) => {
271             lu == ru
272                 && match (lmk, rmk) {
273                     (ModKind::Loaded(litems, linline, _), ModKind::Loaded(ritems, rinline, _)) => {
274                         linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
275                     },
276                     (ModKind::Unloaded, ModKind::Unloaded) => true,
277                     _ => false,
278                 }
279         },
280         (ForeignMod(l), ForeignMod(r)) => {
281             both(&l.abi, &r.abi, eq_str_lit) && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
282         },
283         (
284             TyAlias(box ast::TyAlias {
285                 defaultness: ld,
286                 generics: lg,
287                 bounds: lb,
288                 ty: lt,
289             }),
290             TyAlias(box ast::TyAlias {
291                 defaultness: rd,
292                 generics: rg,
293                 bounds: rb,
294                 ty: rt,
295             }),
296         ) => {
297             eq_defaultness(*ld, *rd)
298                 && eq_generics(lg, rg)
299                 && over(lb, rb, eq_generic_bound)
300                 && both(lt, rt, |l, r| eq_ty(l, r))
301         },
302         (Enum(le, lg), Enum(re, rg)) => over(&le.variants, &re.variants, eq_variant) && eq_generics(lg, rg),
303         (Struct(lv, lg), Struct(rv, rg)) | (Union(lv, lg), Union(rv, rg)) => {
304             eq_variant_data(lv, rv) && eq_generics(lg, rg)
305         },
306         (
307             Trait(box ast::Trait {
308                 is_auto: la,
309                 unsafety: lu,
310                 generics: lg,
311                 bounds: lb,
312                 items: li,
313             }),
314             Trait(box ast::Trait {
315                 is_auto: ra,
316                 unsafety: ru,
317                 generics: rg,
318                 bounds: rb,
319                 items: ri,
320             }),
321         ) => {
322             la == ra
323                 && matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
324                 && eq_generics(lg, rg)
325                 && over(lb, rb, eq_generic_bound)
326                 && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
327         },
328         (TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, eq_generic_bound),
329         (
330             Impl(box ast::Impl {
331                 unsafety: lu,
332                 polarity: lp,
333                 defaultness: ld,
334                 constness: lc,
335                 generics: lg,
336                 of_trait: lot,
337                 self_ty: lst,
338                 items: li,
339             }),
340             Impl(box ast::Impl {
341                 unsafety: ru,
342                 polarity: rp,
343                 defaultness: rd,
344                 constness: rc,
345                 generics: rg,
346                 of_trait: rot,
347                 self_ty: rst,
348                 items: ri,
349             }),
350         ) => {
351             matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
352                 && matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive)
353                 && eq_defaultness(*ld, *rd)
354                 && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
355                 && eq_generics(lg, rg)
356                 && both(lot, rot, |l, r| eq_path(&l.path, &r.path))
357                 && eq_ty(lst, rst)
358                 && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
359         },
360         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
361         (MacroDef(l), MacroDef(r)) => l.macro_rules == r.macro_rules && eq_mac_args(&l.body, &r.body),
362         _ => false,
363     }
364 }
365
366 pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
367     use ForeignItemKind::*;
368     match (l, r) {
369         (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
370         (
371             Fn(box ast::Fn {
372                 defaultness: ld,
373                 sig: lf,
374                 generics: lg,
375                 body: lb,
376             }),
377             Fn(box ast::Fn {
378                 defaultness: rd,
379                 sig: rf,
380                 generics: rg,
381                 body: rb,
382             }),
383         ) => {
384             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
385         },
386         (
387             TyAlias(box ast::TyAlias {
388                 defaultness: ld,
389                 generics: lg,
390                 bounds: lb,
391                 ty: lt,
392             }),
393             TyAlias(box ast::TyAlias {
394                 defaultness: rd,
395                 generics: rg,
396                 bounds: rb,
397                 ty: rt,
398             }),
399         ) => {
400             eq_defaultness(*ld, *rd)
401                 && eq_generics(lg, rg)
402                 && over(lb, rb, eq_generic_bound)
403                 && both(lt, rt, |l, r| eq_ty(l, r))
404         },
405         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
406         _ => false,
407     }
408 }
409
410 pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
411     use AssocItemKind::*;
412     match (l, r) {
413         (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
414         (
415             Fn(box ast::Fn {
416                 defaultness: ld,
417                 sig: lf,
418                 generics: lg,
419                 body: lb,
420             }),
421             Fn(box ast::Fn {
422                 defaultness: rd,
423                 sig: rf,
424                 generics: rg,
425                 body: rb,
426             }),
427         ) => {
428             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
429         },
430         (
431             TyAlias(box ast::TyAlias {
432                 defaultness: ld,
433                 generics: lg,
434                 bounds: lb,
435                 ty: lt,
436             }),
437             TyAlias(box ast::TyAlias {
438                 defaultness: rd,
439                 generics: rg,
440                 bounds: rb,
441                 ty: rt,
442             }),
443         ) => {
444             eq_defaultness(*ld, *rd)
445                 && eq_generics(lg, rg)
446                 && over(lb, rb, eq_generic_bound)
447                 && both(lt, rt, |l, r| eq_ty(l, r))
448         },
449         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
450         _ => false,
451     }
452 }
453
454 pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
455     l.is_placeholder == r.is_placeholder
456         && over(&l.attrs, &r.attrs, eq_attr)
457         && eq_vis(&l.vis, &r.vis)
458         && eq_id(l.ident, r.ident)
459         && eq_variant_data(&l.data, &r.data)
460         && both(&l.disr_expr, &r.disr_expr, |l, r| eq_expr(&l.value, &r.value))
461 }
462
463 pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
464     use VariantData::*;
465     match (l, r) {
466         (Unit(_), Unit(_)) => true,
467         (Struct(l, _), Struct(r, _)) | (Tuple(l, _), Tuple(r, _)) => over(l, r, eq_struct_field),
468         _ => false,
469     }
470 }
471
472 pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
473     l.is_placeholder == r.is_placeholder
474         && over(&l.attrs, &r.attrs, eq_attr)
475         && eq_vis(&l.vis, &r.vis)
476         && both(&l.ident, &r.ident, |l, r| eq_id(*l, *r))
477         && eq_ty(&l.ty, &r.ty)
478 }
479
480 pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
481     eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
482 }
483
484 pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
485     matches!(l.unsafety, Unsafe::No) == matches!(r.unsafety, Unsafe::No)
486         && l.asyncness.is_async() == r.asyncness.is_async()
487         && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
488         && eq_ext(&l.ext, &r.ext)
489 }
490
491 pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
492     over(&l.params, &r.params, eq_generic_param)
493         && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
494             eq_where_predicate(l, r)
495         })
496 }
497
498 pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
499     use WherePredicate::*;
500     match (l, r) {
501         (BoundPredicate(l), BoundPredicate(r)) => {
502             over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
503                 eq_generic_param(l, r)
504             }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
505                 && over(&l.bounds, &r.bounds, eq_generic_bound)
506         },
507         (RegionPredicate(l), RegionPredicate(r)) => {
508             eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
509         },
510         (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
511         _ => false,
512     }
513 }
514
515 pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
516     eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
517 }
518
519 pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
520     eq_expr(&l.value, &r.value)
521 }
522
523 pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
524     use UseTreeKind::*;
525     match (l, r) {
526         (Glob, Glob) => true,
527         (Simple(l, _, _), Simple(r, _, _)) => both(l, r, |l, r| eq_id(*l, *r)),
528         (Nested(l), Nested(r)) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
529         _ => false,
530     }
531 }
532
533 pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
534     matches!(
535         (l, r),
536         (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_))
537     )
538 }
539
540 pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
541     use VisibilityKind::*;
542     match (&l.kind, &r.kind) {
543         (Public, Public) | (Inherited, Inherited) | (Crate(_), Crate(_)) => true,
544         (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
545         _ => false,
546     }
547 }
548
549 pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
550     eq_fn_ret_ty(&l.output, &r.output)
551         && over(&l.inputs, &r.inputs, |l, r| {
552             l.is_placeholder == r.is_placeholder
553                 && eq_pat(&l.pat, &r.pat)
554                 && eq_ty(&l.ty, &r.ty)
555                 && over(&l.attrs, &r.attrs, eq_attr)
556         })
557 }
558
559 pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
560     match (l, r) {
561         (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
562         (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
563         _ => false,
564     }
565 }
566
567 pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
568     use TyKind::*;
569     match (&l.kind, &r.kind) {
570         (Paren(l), _) => eq_ty(l, r),
571         (_, Paren(r)) => eq_ty(l, r),
572         (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err, Err) | (CVarArgs, CVarArgs) => true,
573         (Slice(l), Slice(r)) => eq_ty(l, r),
574         (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
575         (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
576         (Rptr(ll, l), Rptr(rl, r)) => {
577             both(ll, rl, |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
578         },
579         (BareFn(l), BareFn(r)) => {
580             l.unsafety == r.unsafety
581                 && eq_ext(&l.ext, &r.ext)
582                 && over(&l.generic_params, &r.generic_params, eq_generic_param)
583                 && eq_fn_decl(&l.decl, &r.decl)
584         },
585         (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
586         (Path(lq, lp), Path(rq, rp)) => both(lq, rq, eq_qself) && eq_path(lp, rp),
587         (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
588         (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
589         (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
590         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
591         _ => false,
592     }
593 }
594
595 pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
596     use Extern::*;
597     match (l, r) {
598         (None, None) | (Implicit, Implicit) => true,
599         (Explicit(l), Explicit(r)) => eq_str_lit(l, r),
600         _ => false,
601     }
602 }
603
604 pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
605     l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
606 }
607
608 pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
609     eq_path(&l.trait_ref.path, &r.trait_ref.path)
610         && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
611             eq_generic_param(l, r)
612         })
613 }
614
615 pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
616     use GenericParamKind::*;
617     l.is_placeholder == r.is_placeholder
618         && eq_id(l.ident, r.ident)
619         && over(&l.bounds, &r.bounds, eq_generic_bound)
620         && match (&l.kind, &r.kind) {
621             (Lifetime, Lifetime) => true,
622             (Type { default: l }, Type { default: r }) => both(l, r, |l, r| eq_ty(l, r)),
623             (
624                 Const {
625                     ty: lt,
626                     kw_span: _,
627                     default: ld,
628                 },
629                 Const {
630                     ty: rt,
631                     kw_span: _,
632                     default: rd,
633                 },
634             ) => eq_ty(lt, rt) && both(ld, rd, eq_anon_const),
635             _ => false,
636         }
637         && over(&l.attrs, &r.attrs, eq_attr)
638 }
639
640 pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
641     use GenericBound::*;
642     match (l, r) {
643         (Trait(ptr1, tbm1), Trait(ptr2, tbm2)) => tbm1 == tbm2 && eq_poly_ref_trait(ptr1, ptr2),
644         (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
645         _ => false,
646     }
647 }
648
649 pub fn eq_assoc_constraint(l: &AssocTyConstraint, r: &AssocTyConstraint) -> bool {
650     use AssocTyConstraintKind::*;
651     eq_id(l.ident, r.ident)
652         && match (&l.kind, &r.kind) {
653             (Equality { ty: l }, Equality { ty: r }) => eq_ty(l, r),
654             (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
655             _ => false,
656         }
657 }
658
659 pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
660     eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args)
661 }
662
663 pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
664     use AttrKind::*;
665     l.style == r.style
666         && match (&l.kind, &r.kind) {
667             (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
668             (Normal(l, _), Normal(r, _)) => eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args),
669             _ => false,
670         }
671 }
672
673 pub fn eq_mac_args(l: &MacArgs, r: &MacArgs) -> bool {
674     use MacArgs::*;
675     match (l, r) {
676         (Empty, Empty) => true,
677         (Delimited(_, ld, lts), Delimited(_, rd, rts)) => ld == rd && lts.eq_unspanned(rts),
678         (Eq(_, lt), Eq(_, rt)) => lt.kind == rt.kind,
679         _ => false,
680     }
681 }
682
683 /// Extract args from an assert-like macro.
684 ///
685 /// Currently working with:
686 /// - `assert_eq!` and `assert_ne!`
687 /// - `debug_assert_eq!` and `debug_assert_ne!`
688 ///
689 /// For example:
690 ///
691 /// `debug_assert_eq!(a, b)` will return Some([a, b])
692 pub fn extract_assert_macro_args(mut expr: &Expr) -> Option<[&Expr; 2]> {
693     if_chain! {
694         if let ExprKind::If(_, ref block, _) = expr.kind;
695         if let StmtKind::Semi(ref e) = block.stmts.get(0)?.kind;
696         then {
697             expr = e;
698         }
699     }
700     if_chain! {
701         if let ExprKind::Block(ref block, _) = expr.kind;
702         if let StmtKind::Expr(ref expr) = block.stmts.get(0)?.kind;
703         if let ExprKind::Match(ref match_expr, _) = expr.kind;
704         if let ExprKind::Tup(ref tup) = match_expr.kind;
705         if let [a, b, ..] = tup.as_slice();
706         if let (&ExprKind::AddrOf(_, _, ref a), &ExprKind::AddrOf(_, _, ref b)) = (&a.kind, &b.kind);
707         then {
708             return Some([&*a, &*b]);
709         }
710     }
711     None
712 }