]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ast_utils.rs
Rollup merge of #88230 - steffahn:a_an, r=oli-obk
[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, |l, r| eq_qself(l, r)) && 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
55                 && eq_maybe_qself(lqself, rqself)
56                 && eq_path(lp, rp)
57                 && unordered_over(lfs, rfs, |lf, rf| eq_field_pat(lf, rf))
58         },
59         (Or(ls), Or(rs)) => unordered_over(ls, rs, |l, r| eq_pat(l, r)),
60         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
61         _ => false,
62     }
63 }
64
65 pub fn eq_range_end(l: &RangeEnd, r: &RangeEnd) -> bool {
66     match (l, r) {
67         (RangeEnd::Excluded, RangeEnd::Excluded) => true,
68         (RangeEnd::Included(l), RangeEnd::Included(r)) => {
69             matches!(l, RangeSyntax::DotDotEq) == matches!(r, RangeSyntax::DotDotEq)
70         },
71         _ => false,
72     }
73 }
74
75 pub fn eq_field_pat(l: &PatField, r: &PatField) -> bool {
76     l.is_placeholder == r.is_placeholder
77         && eq_id(l.ident, r.ident)
78         && eq_pat(&l.pat, &r.pat)
79         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
80 }
81
82 pub fn eq_qself(l: &QSelf, r: &QSelf) -> bool {
83     l.position == r.position && eq_ty(&l.ty, &r.ty)
84 }
85
86 pub fn eq_maybe_qself(l: &Option<QSelf>, r: &Option<QSelf>) -> bool {
87     match (l, r) {
88         (Some(l), Some(r)) => eq_qself(l, r),
89         (None, None) => true,
90         _ => false,
91     }
92 }
93
94 pub fn eq_path(l: &Path, r: &Path) -> bool {
95     over(&l.segments, &r.segments, |l, r| eq_path_seg(l, r))
96 }
97
98 pub fn eq_path_seg(l: &PathSegment, r: &PathSegment) -> bool {
99     eq_id(l.ident, r.ident) && both(&l.args, &r.args, |l, r| eq_generic_args(l, r))
100 }
101
102 pub fn eq_generic_args(l: &GenericArgs, r: &GenericArgs) -> bool {
103     match (l, r) {
104         (GenericArgs::AngleBracketed(l), GenericArgs::AngleBracketed(r)) => {
105             over(&l.args, &r.args, |l, r| eq_angle_arg(l, r))
106         },
107         (GenericArgs::Parenthesized(l), GenericArgs::Parenthesized(r)) => {
108             over(&l.inputs, &r.inputs, |l, r| eq_ty(l, r)) && eq_fn_ret_ty(&l.output, &r.output)
109         },
110         _ => false,
111     }
112 }
113
114 pub fn eq_angle_arg(l: &AngleBracketedArg, r: &AngleBracketedArg) -> bool {
115     match (l, r) {
116         (AngleBracketedArg::Arg(l), AngleBracketedArg::Arg(r)) => eq_generic_arg(l, r),
117         (AngleBracketedArg::Constraint(l), AngleBracketedArg::Constraint(r)) => eq_assoc_constraint(l, r),
118         _ => false,
119     }
120 }
121
122 pub fn eq_generic_arg(l: &GenericArg, r: &GenericArg) -> bool {
123     match (l, r) {
124         (GenericArg::Lifetime(l), GenericArg::Lifetime(r)) => eq_id(l.ident, r.ident),
125         (GenericArg::Type(l), GenericArg::Type(r)) => eq_ty(l, r),
126         (GenericArg::Const(l), GenericArg::Const(r)) => eq_expr(&l.value, &r.value),
127         _ => false,
128     }
129 }
130
131 pub fn eq_expr_opt(l: &Option<P<Expr>>, r: &Option<P<Expr>>) -> bool {
132     both(l, r, |l, r| eq_expr(l, r))
133 }
134
135 pub fn eq_struct_rest(l: &StructRest, r: &StructRest) -> bool {
136     match (l, r) {
137         (StructRest::Base(lb), StructRest::Base(rb)) => eq_expr(lb, rb),
138         (StructRest::Rest(_), StructRest::Rest(_)) | (StructRest::None, StructRest::None) => true,
139         _ => false,
140     }
141 }
142
143 pub fn eq_expr(l: &Expr, r: &Expr) -> bool {
144     use ExprKind::*;
145     if !over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r)) {
146         return false;
147     }
148     match (&l.kind, &r.kind) {
149         (Paren(l), _) => eq_expr(l, r),
150         (_, Paren(r)) => eq_expr(l, r),
151         (Err, Err) => true,
152         (Box(l), Box(r)) | (Try(l), Try(r)) | (Await(l), Await(r)) => eq_expr(l, r),
153         (Array(l), Array(r)) | (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)),
154         (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value),
155         (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
156         (MethodCall(lc, la, _), MethodCall(rc, ra, _)) => eq_path_seg(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
157         (Binary(lo, ll, lr), Binary(ro, rl, rr)) => lo.node == ro.node && eq_expr(ll, rl) && eq_expr(lr, rr),
158         (Unary(lo, l), Unary(ro, r)) => mem::discriminant(lo) == mem::discriminant(ro) && eq_expr(l, r),
159         (Lit(l), Lit(r)) => l.kind == r.kind,
160         (Cast(l, lt), Cast(r, rt)) | (Type(l, lt), Type(r, rt)) => eq_expr(l, r) && eq_ty(lt, rt),
161         (Let(lp, le, _), Let(rp, re, _)) => eq_pat(lp, rp) && eq_expr(le, re),
162         (If(lc, lt, le), If(rc, rt, re)) => eq_expr(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le, re),
163         (While(lc, lt, ll), While(rc, rt, rl)) => eq_label(ll, rl) && eq_expr(lc, rc) && eq_block(lt, rt),
164         (ForLoop(lp, li, lt, ll), ForLoop(rp, ri, rt, rl)) => {
165             eq_label(ll, rl) && eq_pat(lp, rp) && eq_expr(li, ri) && eq_block(lt, rt)
166         },
167         (Loop(lt, ll), Loop(rt, rl)) => eq_label(ll, rl) && eq_block(lt, rt),
168         (Block(lb, ll), Block(rb, rl)) => eq_label(ll, rl) && eq_block(lb, rb),
169         (TryBlock(l), TryBlock(r)) => eq_block(l, r),
170         (Yield(l), Yield(r)) | (Ret(l), Ret(r)) => eq_expr_opt(l, r),
171         (Break(ll, le), Break(rl, re)) => eq_label(ll, rl) && eq_expr_opt(le, re),
172         (Continue(ll), Continue(rl)) => eq_label(ll, rl),
173         (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2), Index(r1, r2)) => eq_expr(l1, r1) && eq_expr(l2, r2),
174         (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
175         (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
176         (Match(ls, la), Match(rs, ra)) => eq_expr(ls, rs) && over(la, ra, |l, r| eq_arm(l, r)),
177         (Closure(lc, la, lm, lf, lb, _), Closure(rc, ra, rm, rf, rb, _)) => {
178             lc == rc && la.is_async() == ra.is_async() && lm == rm && eq_fn_decl(lf, rf) && eq_expr(lb, rb)
179         },
180         (Async(lc, _, lb), Async(rc, _, rb)) => lc == rc && eq_block(lb, rb),
181         (Range(lf, lt, ll), Range(rf, rt, rl)) => ll == rl && eq_expr_opt(lf, rf) && eq_expr_opt(lt, rt),
182         (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
183         (Path(lq, lp), Path(rq, rp)) => both(lq, rq, |l, r| eq_qself(l, r)) && eq_path(lp, rp),
184         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
185         (Struct(lse), Struct(rse)) => {
186             eq_maybe_qself(&lse.qself, &rse.qself)
187                 && eq_path(&lse.path, &rse.path)
188                 && eq_struct_rest(&lse.rest, &rse.rest)
189                 && unordered_over(&lse.fields, &rse.fields, |l, r| eq_field(l, r))
190         },
191         _ => false,
192     }
193 }
194
195 pub fn eq_field(l: &ExprField, r: &ExprField) -> bool {
196     l.is_placeholder == r.is_placeholder
197         && eq_id(l.ident, r.ident)
198         && eq_expr(&l.expr, &r.expr)
199         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
200 }
201
202 pub fn eq_arm(l: &Arm, r: &Arm) -> bool {
203     l.is_placeholder == r.is_placeholder
204         && eq_pat(&l.pat, &r.pat)
205         && eq_expr(&l.body, &r.body)
206         && eq_expr_opt(&l.guard, &r.guard)
207         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
208 }
209
210 pub fn eq_label(l: &Option<Label>, r: &Option<Label>) -> bool {
211     both(l, r, |l, r| eq_id(l.ident, r.ident))
212 }
213
214 pub fn eq_block(l: &Block, r: &Block) -> bool {
215     l.rules == r.rules && over(&l.stmts, &r.stmts, |l, r| eq_stmt(l, r))
216 }
217
218 pub fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
219     use StmtKind::*;
220     match (&l.kind, &r.kind) {
221         (Local(l), Local(r)) => {
222             eq_pat(&l.pat, &r.pat)
223                 && both(&l.ty, &r.ty, |l, r| eq_ty(l, r))
224                 && eq_expr_opt(&l.init, &r.init)
225                 && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
226         },
227         (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
228         (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
229         (Empty, Empty) => true,
230         (MacCall(l), MacCall(r)) => {
231             l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
232         },
233         _ => false,
234     }
235 }
236
237 pub fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
238     eq_id(l.ident, r.ident)
239         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
240         && eq_vis(&l.vis, &r.vis)
241         && eq_kind(&l.kind, &r.kind)
242 }
243
244 pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
245     use ItemKind::*;
246     match (l, r) {
247         (ExternCrate(l), ExternCrate(r)) => l == r,
248         (Use(l), Use(r)) => eq_use_tree(l, r),
249         (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
250         (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
251         (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
252             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
253         },
254         (Mod(lu, lmk), Mod(ru, rmk)) => {
255             lu == ru
256                 && match (lmk, rmk) {
257                     (ModKind::Loaded(litems, linline, _), ModKind::Loaded(ritems, rinline, _)) => {
258                         linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
259                     },
260                     (ModKind::Unloaded, ModKind::Unloaded) => true,
261                     _ => false,
262                 }
263         },
264         (ForeignMod(l), ForeignMod(r)) => {
265             both(&l.abi, &r.abi, |l, r| eq_str_lit(l, r))
266                 && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
267         },
268         (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
269             eq_defaultness(*ld, *rd)
270                 && eq_generics(lg, rg)
271                 && over(lb, rb, |l, r| eq_generic_bound(l, r))
272                 && both(lt, rt, |l, r| eq_ty(l, r))
273         },
274         (Enum(le, lg), Enum(re, rg)) => {
275             over(&le.variants, &re.variants, |l, r| eq_variant(l, r)) && eq_generics(lg, rg)
276         },
277         (Struct(lv, lg), Struct(rv, rg)) | (Union(lv, lg), Union(rv, rg)) => {
278             eq_variant_data(lv, rv) && eq_generics(lg, rg)
279         },
280         (Trait(box TraitKind(la, lu, lg, lb, li)), Trait(box TraitKind(ra, ru, rg, rb, ri))) => {
281             la == ra
282                 && matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
283                 && eq_generics(lg, rg)
284                 && over(lb, rb, |l, r| eq_generic_bound(l, r))
285                 && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
286         },
287         (TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, |l, r| eq_generic_bound(l, r)),
288         (
289             Impl(box ImplKind {
290                 unsafety: lu,
291                 polarity: lp,
292                 defaultness: ld,
293                 constness: lc,
294                 generics: lg,
295                 of_trait: lot,
296                 self_ty: lst,
297                 items: li,
298             }),
299             Impl(box ImplKind {
300                 unsafety: ru,
301                 polarity: rp,
302                 defaultness: rd,
303                 constness: rc,
304                 generics: rg,
305                 of_trait: rot,
306                 self_ty: rst,
307                 items: ri,
308             }),
309         ) => {
310             matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
311                 && matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive)
312                 && eq_defaultness(*ld, *rd)
313                 && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
314                 && eq_generics(lg, rg)
315                 && both(lot, rot, |l, r| eq_path(&l.path, &r.path))
316                 && eq_ty(lst, rst)
317                 && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
318         },
319         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
320         (MacroDef(l), MacroDef(r)) => l.macro_rules == r.macro_rules && eq_mac_args(&l.body, &r.body),
321         _ => false,
322     }
323 }
324
325 pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
326     use ForeignItemKind::*;
327     match (l, r) {
328         (Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
329         (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
330             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
331         },
332         (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
333             eq_defaultness(*ld, *rd)
334                 && eq_generics(lg, rg)
335                 && over(lb, rb, |l, r| eq_generic_bound(l, r))
336                 && both(lt, rt, |l, r| eq_ty(l, r))
337         },
338         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
339         _ => false,
340     }
341 }
342
343 pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
344     use AssocItemKind::*;
345     match (l, r) {
346         (Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
347         (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
348             eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
349         },
350         (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
351             eq_defaultness(*ld, *rd)
352                 && eq_generics(lg, rg)
353                 && over(lb, rb, |l, r| eq_generic_bound(l, r))
354                 && both(lt, rt, |l, r| eq_ty(l, r))
355         },
356         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
357         _ => false,
358     }
359 }
360
361 pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
362     l.is_placeholder == r.is_placeholder
363         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
364         && eq_vis(&l.vis, &r.vis)
365         && eq_id(l.ident, r.ident)
366         && eq_variant_data(&l.data, &r.data)
367         && both(&l.disr_expr, &r.disr_expr, |l, r| eq_expr(&l.value, &r.value))
368 }
369
370 pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
371     use VariantData::*;
372     match (l, r) {
373         (Unit(_), Unit(_)) => true,
374         (Struct(l, _), Struct(r, _)) | (Tuple(l, _), Tuple(r, _)) => over(l, r, |l, r| eq_struct_field(l, r)),
375         _ => false,
376     }
377 }
378
379 pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
380     l.is_placeholder == r.is_placeholder
381         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
382         && eq_vis(&l.vis, &r.vis)
383         && both(&l.ident, &r.ident, |l, r| eq_id(*l, *r))
384         && eq_ty(&l.ty, &r.ty)
385 }
386
387 pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
388     eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
389 }
390
391 pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
392     matches!(l.unsafety, Unsafe::No) == matches!(r.unsafety, Unsafe::No)
393         && l.asyncness.is_async() == r.asyncness.is_async()
394         && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
395         && eq_ext(&l.ext, &r.ext)
396 }
397
398 pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
399     over(&l.params, &r.params, |l, r| eq_generic_param(l, r))
400         && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
401             eq_where_predicate(l, r)
402         })
403 }
404
405 pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
406     use WherePredicate::*;
407     match (l, r) {
408         (BoundPredicate(l), BoundPredicate(r)) => {
409             over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
410                 eq_generic_param(l, r)
411             }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
412                 && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
413         },
414         (RegionPredicate(l), RegionPredicate(r)) => {
415             eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
416         },
417         (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
418         _ => false,
419     }
420 }
421
422 pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
423     eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
424 }
425
426 pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
427     eq_expr(&l.value, &r.value)
428 }
429
430 pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
431     use UseTreeKind::*;
432     match (l, r) {
433         (Glob, Glob) => true,
434         (Simple(l, _, _), Simple(r, _, _)) => both(l, r, |l, r| eq_id(*l, *r)),
435         (Nested(l), Nested(r)) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
436         _ => false,
437     }
438 }
439
440 pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
441     matches!(
442         (l, r),
443         (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_))
444     )
445 }
446
447 pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
448     use VisibilityKind::*;
449     match (&l.kind, &r.kind) {
450         (Public, Public) | (Inherited, Inherited) | (Crate(_), Crate(_)) => true,
451         (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
452         _ => false,
453     }
454 }
455
456 pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
457     eq_fn_ret_ty(&l.output, &r.output)
458         && over(&l.inputs, &r.inputs, |l, r| {
459             l.is_placeholder == r.is_placeholder
460                 && eq_pat(&l.pat, &r.pat)
461                 && eq_ty(&l.ty, &r.ty)
462                 && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
463         })
464 }
465
466 pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
467     match (l, r) {
468         (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
469         (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
470         _ => false,
471     }
472 }
473
474 pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
475     use TyKind::*;
476     match (&l.kind, &r.kind) {
477         (Paren(l), _) => eq_ty(l, r),
478         (_, Paren(r)) => eq_ty(l, r),
479         (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err, Err) | (CVarArgs, CVarArgs) => true,
480         (Slice(l), Slice(r)) => eq_ty(l, r),
481         (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
482         (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
483         (Rptr(ll, l), Rptr(rl, r)) => {
484             both(ll, rl, |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
485         },
486         (BareFn(l), BareFn(r)) => {
487             l.unsafety == r.unsafety
488                 && eq_ext(&l.ext, &r.ext)
489                 && over(&l.generic_params, &r.generic_params, |l, r| eq_generic_param(l, r))
490                 && eq_fn_decl(&l.decl, &r.decl)
491         },
492         (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
493         (Path(lq, lp), Path(rq, rp)) => both(lq, rq, |l, r| eq_qself(l, r)) && eq_path(lp, rp),
494         (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, |l, r| eq_generic_bound(l, r)),
495         (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, |l, r| eq_generic_bound(l, r)),
496         (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
497         (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
498         _ => false,
499     }
500 }
501
502 pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
503     use Extern::*;
504     match (l, r) {
505         (None, None) | (Implicit, Implicit) => true,
506         (Explicit(l), Explicit(r)) => eq_str_lit(l, r),
507         _ => false,
508     }
509 }
510
511 pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
512     l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
513 }
514
515 pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
516     eq_path(&l.trait_ref.path, &r.trait_ref.path)
517         && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
518             eq_generic_param(l, r)
519         })
520 }
521
522 pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
523     use GenericParamKind::*;
524     l.is_placeholder == r.is_placeholder
525         && eq_id(l.ident, r.ident)
526         && over(&l.bounds, &r.bounds, |l, r| eq_generic_bound(l, r))
527         && match (&l.kind, &r.kind) {
528             (Lifetime, Lifetime) => true,
529             (Type { default: l }, Type { default: r }) => both(l, r, |l, r| eq_ty(l, r)),
530             (
531                 Const {
532                     ty: lt,
533                     kw_span: _,
534                     default: ld,
535                 },
536                 Const {
537                     ty: rt,
538                     kw_span: _,
539                     default: rd,
540                 },
541             ) => eq_ty(lt, rt) && both(ld, rd, |ld, rd| eq_anon_const(ld, rd)),
542             _ => false,
543         }
544         && over(&l.attrs, &r.attrs, |l, r| eq_attr(l, r))
545 }
546
547 pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
548     use GenericBound::*;
549     match (l, r) {
550         (Trait(ptr1, tbm1), Trait(ptr2, tbm2)) => tbm1 == tbm2 && eq_poly_ref_trait(ptr1, ptr2),
551         (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
552         _ => false,
553     }
554 }
555
556 pub fn eq_assoc_constraint(l: &AssocTyConstraint, r: &AssocTyConstraint) -> bool {
557     use AssocTyConstraintKind::*;
558     eq_id(l.ident, r.ident)
559         && match (&l.kind, &r.kind) {
560             (Equality { ty: l }, Equality { ty: r }) => eq_ty(l, r),
561             (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, |l, r| eq_generic_bound(l, r)),
562             _ => false,
563         }
564 }
565
566 pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
567     eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args)
568 }
569
570 pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
571     use AttrKind::*;
572     l.style == r.style
573         && match (&l.kind, &r.kind) {
574             (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
575             (Normal(l, _), Normal(r, _)) => eq_path(&l.path, &r.path) && eq_mac_args(&l.args, &r.args),
576             _ => false,
577         }
578 }
579
580 pub fn eq_mac_args(l: &MacArgs, r: &MacArgs) -> bool {
581     use MacArgs::*;
582     match (l, r) {
583         (Empty, Empty) => true,
584         (Delimited(_, ld, lts), Delimited(_, rd, rts)) => ld == rd && lts.eq_unspanned(rts),
585         (Eq(_, lt), Eq(_, rt)) => lt.kind == rt.kind,
586         _ => false,
587     }
588 }
589
590 /// Extract args from an assert-like macro.
591 ///
592 /// Currently working with:
593 /// - `assert_eq!` and `assert_ne!`
594 /// - `debug_assert_eq!` and `debug_assert_ne!`
595 ///
596 /// For example:
597 ///
598 /// `debug_assert_eq!(a, b)` will return Some([a, b])
599 pub fn extract_assert_macro_args(mut expr: &Expr) -> Option<[&Expr; 2]> {
600     if_chain! {
601         if let ExprKind::If(_, ref block, _) = expr.kind;
602         if let StmtKind::Semi(ref e) = block.stmts.get(0)?.kind;
603         then {
604             expr = e;
605         }
606     }
607     if_chain! {
608         if let ExprKind::Block(ref block, _) = expr.kind;
609         if let StmtKind::Expr(ref expr) = block.stmts.get(0)?.kind;
610         if let ExprKind::Match(ref match_expr, _) = expr.kind;
611         if let ExprKind::Tup(ref tup) = match_expr.kind;
612         if let [a, b, ..] = tup.as_slice();
613         if let (&ExprKind::AddrOf(_, _, ref a), &ExprKind::AddrOf(_, _, ref b)) = (&a.kind, &b.kind);
614         then {
615             return Some([&*a, &*b]);
616         }
617     }
618     None
619 }