clippy_utils/ast_utils/
mod.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::wildcard_imports, clippy::enum_glob_use)]
6
7use crate::{both, over};
8use rustc_ast::{self as ast, *};
9use rustc_span::symbol::Ident;
10use std::mem;
11
12pub mod ident_iter;
13pub use ident_iter::IdentIter;
14
15pub fn is_useless_with_eq_exprs(kind: BinOpKind) -> bool {
16    use BinOpKind::*;
17    matches!(
18        kind,
19        Sub | Div | Eq | Lt | Le | Gt | Ge | Ne | And | Or | BitXor | BitAnd | BitOr
20    )
21}
22
23/// Checks if each element in the first slice is contained within the latter as per `eq_fn`.
24pub fn unordered_over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
25    left.len() == right.len() && left.iter().all(|l| right.iter().any(|r| eq_fn(l, r)))
26}
27
28pub fn eq_id(l: Ident, r: Ident) -> bool {
29    l.name == r.name
30}
31
32pub fn eq_pat(l: &Pat, r: &Pat) -> bool {
33    use PatKind::*;
34    match (&l.kind, &r.kind) {
35        (Missing, _) | (_, Missing) => unreachable!(),
36        (Paren(l), _) => eq_pat(l, r),
37        (_, Paren(r)) => eq_pat(l, r),
38        (Wild, Wild) | (Rest, Rest) => true,
39        (Expr(l), Expr(r)) => eq_expr(l, r),
40        (Ident(b1, i1, s1), Ident(b2, i2, s2)) => {
41            b1 == b2 && eq_id(*i1, *i2) && both(s1.as_deref(), s2.as_deref(), eq_pat)
42        },
43        (Range(lf, lt, le), Range(rf, rt, re)) => {
44            eq_expr_opt(lf.as_ref(), rf.as_ref())
45                && eq_expr_opt(lt.as_ref(), rt.as_ref())
46                && eq_range_end(&le.node, &re.node)
47        },
48        (Box(l), Box(r))
49        | (Ref(l, Mutability::Not), Ref(r, Mutability::Not))
50        | (Ref(l, Mutability::Mut), Ref(r, Mutability::Mut)) => eq_pat(l, r),
51        (Tuple(l), Tuple(r)) | (Slice(l), Slice(r)) => over(l, r, |l, r| eq_pat(l, r)),
52        (Path(lq, lp), Path(rq, rp)) => both(lq.as_ref(), rq.as_ref(), eq_qself) && eq_path(lp, rp),
53        (TupleStruct(lqself, lp, lfs), TupleStruct(rqself, rp, rfs)) => {
54            eq_maybe_qself(lqself.as_ref(), rqself.as_ref()) && eq_path(lp, rp) && over(lfs, rfs, |l, r| eq_pat(l, r))
55        },
56        (Struct(lqself, lp, lfs, lr), Struct(rqself, rp, rfs, rr)) => {
57            lr == rr
58                && eq_maybe_qself(lqself.as_ref(), rqself.as_ref())
59                && eq_path(lp, rp)
60                && unordered_over(lfs, rfs, eq_field_pat)
61        },
62        (Or(ls), Or(rs)) => unordered_over(ls, rs, |l, r| eq_pat(l, r)),
63        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
64        _ => false,
65    }
66}
67
68pub fn eq_range_end(l: &RangeEnd, r: &RangeEnd) -> bool {
69    match (l, r) {
70        (RangeEnd::Excluded, RangeEnd::Excluded) => true,
71        (RangeEnd::Included(l), RangeEnd::Included(r)) => {
72            matches!(l, RangeSyntax::DotDotEq) == matches!(r, RangeSyntax::DotDotEq)
73        },
74        _ => false,
75    }
76}
77
78pub fn eq_field_pat(l: &PatField, r: &PatField) -> bool {
79    l.is_placeholder == r.is_placeholder
80        && eq_id(l.ident, r.ident)
81        && eq_pat(&l.pat, &r.pat)
82        && over(&l.attrs, &r.attrs, eq_attr)
83}
84
85pub fn eq_qself(l: &Box<QSelf>, r: &Box<QSelf>) -> bool {
86    l.position == r.position && eq_ty(&l.ty, &r.ty)
87}
88
89pub fn eq_maybe_qself(l: Option<&Box<QSelf>>, r: Option<&Box<QSelf>>) -> bool {
90    match (l, r) {
91        (Some(l), Some(r)) => eq_qself(l, r),
92        (None, None) => true,
93        _ => false,
94    }
95}
96
97pub fn eq_path(l: &Path, r: &Path) -> bool {
98    over(&l.segments, &r.segments, eq_path_seg)
99}
100
101pub fn eq_path_seg(l: &PathSegment, r: &PathSegment) -> bool {
102    eq_id(l.ident, r.ident) && both(l.args.as_ref(), r.args.as_ref(), |l, r| eq_generic_args(l, r))
103}
104
105pub fn eq_generic_args(l: &GenericArgs, r: &GenericArgs) -> bool {
106    match (l, r) {
107        (AngleBracketed(l), AngleBracketed(r)) => over(&l.args, &r.args, eq_angle_arg),
108        (Parenthesized(l), Parenthesized(r)) => {
109            over(&l.inputs, &r.inputs, |l, r| eq_ty(l, r)) && eq_fn_ret_ty(&l.output, &r.output)
110        },
111        _ => false,
112    }
113}
114
115pub fn eq_angle_arg(l: &AngleBracketedArg, r: &AngleBracketedArg) -> bool {
116    match (l, r) {
117        (AngleBracketedArg::Arg(l), AngleBracketedArg::Arg(r)) => eq_generic_arg(l, r),
118        (AngleBracketedArg::Constraint(l), AngleBracketedArg::Constraint(r)) => eq_assoc_item_constraint(l, r),
119        _ => false,
120    }
121}
122
123pub fn eq_generic_arg(l: &GenericArg, r: &GenericArg) -> bool {
124    match (l, r) {
125        (GenericArg::Lifetime(l), GenericArg::Lifetime(r)) => eq_id(l.ident, r.ident),
126        (GenericArg::Type(l), GenericArg::Type(r)) => eq_ty(l, r),
127        (GenericArg::Const(l), GenericArg::Const(r)) => eq_expr(&l.value, &r.value),
128        _ => false,
129    }
130}
131
132pub fn eq_expr_opt(l: Option<&Box<Expr>>, r: Option<&Box<Expr>>) -> bool {
133    both(l, r, |l, r| eq_expr(l, r))
134}
135
136pub fn eq_struct_rest(l: &StructRest, r: &StructRest) -> bool {
137    match (l, r) {
138        (StructRest::Base(lb), StructRest::Base(rb)) => eq_expr(lb, rb),
139        (StructRest::Rest(_), StructRest::Rest(_)) | (StructRest::None, StructRest::None) => true,
140        _ => false,
141    }
142}
143
144#[allow(clippy::too_many_lines)] // Just a big match statement
145pub fn eq_expr(l: &Expr, r: &Expr) -> bool {
146    use ExprKind::*;
147    if !over(&l.attrs, &r.attrs, eq_attr) {
148        return false;
149    }
150    match (&l.kind, &r.kind) {
151        (Paren(l), _) => eq_expr(l, r),
152        (_, Paren(r)) => eq_expr(l, r),
153        (Err(_), Err(_)) => true,
154        (Dummy, _) | (_, Dummy) => unreachable!("comparing `ExprKind::Dummy`"),
155        (Try(l), Try(r)) | (Await(l, _), Await(r, _)) => eq_expr(l, r),
156        (Array(l), Array(r)) => over(l, r, |l, r| eq_expr(l, r)),
157        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)),
158        (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value),
159        (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
160        (
161            MethodCall(box ast::MethodCall {
162                seg: ls,
163                receiver: lr,
164                args: la,
165                ..
166            }),
167            MethodCall(box ast::MethodCall {
168                seg: rs,
169                receiver: rr,
170                args: ra,
171                ..
172            }),
173        ) => eq_path_seg(ls, rs) && eq_expr(lr, rr) && over(la, ra, |l, r| eq_expr(l, r)),
174        (Binary(lo, ll, lr), Binary(ro, rl, rr)) => lo.node == ro.node && eq_expr(ll, rl) && eq_expr(lr, rr),
175        (Unary(lo, l), Unary(ro, r)) => mem::discriminant(lo) == mem::discriminant(ro) && eq_expr(l, r),
176        (Lit(l), Lit(r)) => l == r,
177        (Cast(l, lt), Cast(r, rt)) | (Type(l, lt), Type(r, rt)) => eq_expr(l, r) && eq_ty(lt, rt),
178        (Let(lp, le, _, _), Let(rp, re, _, _)) => eq_pat(lp, rp) && eq_expr(le, re),
179        (If(lc, lt, le), If(rc, rt, re)) => {
180            eq_expr(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref())
181        },
182        (While(lc, lt, ll), While(rc, rt, rl)) => {
183            eq_label(ll.as_ref(), rl.as_ref()) && eq_expr(lc, rc) && eq_block(lt, rt)
184        },
185        (
186            ForLoop {
187                pat: lp,
188                iter: li,
189                body: lt,
190                label: ll,
191                kind: lk,
192            },
193            ForLoop {
194                pat: rp,
195                iter: ri,
196                body: rt,
197                label: rl,
198                kind: rk,
199            },
200        ) => eq_label(ll.as_ref(), rl.as_ref()) && eq_pat(lp, rp) && eq_expr(li, ri) && eq_block(lt, rt) && lk == rk,
201        (Loop(lt, ll, _), Loop(rt, rl, _)) => eq_label(ll.as_ref(), rl.as_ref()) && eq_block(lt, rt),
202        (Block(lb, ll), Block(rb, rl)) => eq_label(ll.as_ref(), rl.as_ref()) && eq_block(lb, rb),
203        (TryBlock(l), TryBlock(r)) => eq_block(l, r),
204        (Yield(l), Yield(r)) => eq_expr_opt(l.expr(), r.expr()) && l.same_kind(r),
205        (Ret(l), Ret(r)) => eq_expr_opt(l.as_ref(), r.as_ref()),
206        (Break(ll, le), Break(rl, re)) => eq_label(ll.as_ref(), rl.as_ref()) && eq_expr_opt(le.as_ref(), re.as_ref()),
207        (Continue(ll), Continue(rl)) => eq_label(ll.as_ref(), rl.as_ref()),
208        (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2, _), Index(r1, r2, _)) => {
209            eq_expr(l1, r1) && eq_expr(l2, r2)
210        },
211        (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
212        (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
213        (Match(ls, la, lkind), Match(rs, ra, rkind)) => (lkind == rkind) && eq_expr(ls, rs) && over(la, ra, eq_arm),
214        (
215            Closure(box ast::Closure {
216                binder: lb,
217                capture_clause: lc,
218                coroutine_kind: la,
219                movability: lm,
220                fn_decl: lf,
221                body: le,
222                ..
223            }),
224            Closure(box ast::Closure {
225                binder: rb,
226                capture_clause: rc,
227                coroutine_kind: ra,
228                movability: rm,
229                fn_decl: rf,
230                body: re,
231                ..
232            }),
233        ) => {
234            eq_closure_binder(lb, rb)
235                && lc == rc
236                && eq_coroutine_kind(*la, *ra)
237                && lm == rm
238                && eq_fn_decl(lf, rf)
239                && eq_expr(le, re)
240        },
241        (Gen(lc, lb, lk, _), Gen(rc, rb, rk, _)) => lc == rc && eq_block(lb, rb) && lk == rk,
242        (Range(lf, lt, ll), Range(rf, rt, rl)) => {
243            ll == rl && eq_expr_opt(lf.as_ref(), rf.as_ref()) && eq_expr_opt(lt.as_ref(), rt.as_ref())
244        },
245        (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
246        (Path(lq, lp), Path(rq, rp)) => both(lq.as_ref(), rq.as_ref(), eq_qself) && eq_path(lp, rp),
247        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
248        (Struct(lse), Struct(rse)) => {
249            eq_maybe_qself(lse.qself.as_ref(), rse.qself.as_ref())
250                && eq_path(&lse.path, &rse.path)
251                && eq_struct_rest(&lse.rest, &rse.rest)
252                && unordered_over(&lse.fields, &rse.fields, eq_field)
253        },
254        _ => false,
255    }
256}
257
258fn eq_coroutine_kind(a: Option<CoroutineKind>, b: Option<CoroutineKind>) -> bool {
259    matches!(
260        (a, b),
261        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
262            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
263            | (
264                Some(CoroutineKind::AsyncGen { .. }),
265                Some(CoroutineKind::AsyncGen { .. })
266            )
267            | (None, None)
268    )
269}
270
271pub fn eq_field(l: &ExprField, r: &ExprField) -> bool {
272    l.is_placeholder == r.is_placeholder
273        && eq_id(l.ident, r.ident)
274        && eq_expr(&l.expr, &r.expr)
275        && over(&l.attrs, &r.attrs, eq_attr)
276}
277
278pub fn eq_arm(l: &Arm, r: &Arm) -> bool {
279    l.is_placeholder == r.is_placeholder
280        && eq_pat(&l.pat, &r.pat)
281        && eq_expr_opt(l.body.as_ref(), r.body.as_ref())
282        && eq_expr_opt(l.guard.as_ref(), r.guard.as_ref())
283        && over(&l.attrs, &r.attrs, eq_attr)
284}
285
286pub fn eq_label(l: Option<&Label>, r: Option<&Label>) -> bool {
287    both(l, r, |l, r| eq_id(l.ident, r.ident))
288}
289
290pub fn eq_block(l: &Block, r: &Block) -> bool {
291    l.rules == r.rules && over(&l.stmts, &r.stmts, eq_stmt)
292}
293
294pub fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
295    use StmtKind::*;
296    match (&l.kind, &r.kind) {
297        (Let(l), Let(r)) => {
298            eq_pat(&l.pat, &r.pat)
299                && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| eq_ty(l, r))
300                && eq_local_kind(&l.kind, &r.kind)
301                && over(&l.attrs, &r.attrs, eq_attr)
302        },
303        (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
304        (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
305        (Empty, Empty) => true,
306        (MacCall(l), MacCall(r)) => {
307            l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, eq_attr)
308        },
309        _ => false,
310    }
311}
312
313pub fn eq_local_kind(l: &LocalKind, r: &LocalKind) -> bool {
314    use LocalKind::*;
315    match (l, r) {
316        (Decl, Decl) => true,
317        (Init(l), Init(r)) => eq_expr(l, r),
318        (InitElse(li, le), InitElse(ri, re)) => eq_expr(li, ri) && eq_block(le, re),
319        _ => false,
320    }
321}
322
323pub fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
324    over(&l.attrs, &r.attrs, eq_attr) && eq_vis(&l.vis, &r.vis) && eq_kind(&l.kind, &r.kind)
325}
326
327#[expect(clippy::similar_names, clippy::too_many_lines)] // Just a big match statement
328pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
329    use ItemKind::*;
330    match (l, r) {
331        (ExternCrate(ls, li), ExternCrate(rs, ri)) => ls == rs && eq_id(*li, *ri),
332        (Use(l), Use(r)) => eq_use_tree(l, r),
333        (
334            Static(box StaticItem {
335                ident: li,
336                ty: lt,
337                mutability: lm,
338                expr: le,
339                safety: ls,
340                define_opaque: _,
341            }),
342            Static(box StaticItem {
343                ident: ri,
344                ty: rt,
345                mutability: rm,
346                expr: re,
347                safety: rs,
348                define_opaque: _,
349            }),
350        ) => eq_id(*li, *ri) && lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref()),
351        (
352            Const(box ConstItem {
353                defaultness: ld,
354                ident: li,
355                generics: lg,
356                ty: lt,
357                expr: le,
358                define_opaque: _,
359            }),
360            Const(box ConstItem {
361                defaultness: rd,
362                ident: ri,
363                generics: rg,
364                ty: rt,
365                expr: re,
366                define_opaque: _,
367            }),
368        ) => {
369            eq_defaultness(*ld, *rd)
370                && eq_id(*li, *ri)
371                && eq_generics(lg, rg)
372                && eq_ty(lt, rt)
373                && eq_expr_opt(le.as_ref(), re.as_ref())
374        },
375        (
376            Fn(box ast::Fn {
377                defaultness: ld,
378                sig: lf,
379                ident: li,
380                generics: lg,
381                contract: lc,
382                body: lb,
383                define_opaque: _,
384            }),
385            Fn(box ast::Fn {
386                defaultness: rd,
387                sig: rf,
388                ident: ri,
389                generics: rg,
390                contract: rc,
391                body: rb,
392                define_opaque: _,
393            }),
394        ) => {
395            eq_defaultness(*ld, *rd)
396                && eq_fn_sig(lf, rf)
397                && eq_id(*li, *ri)
398                && eq_generics(lg, rg)
399                && eq_opt_fn_contract(lc, rc)
400                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
401        },
402        (Mod(ls, li, lmk), Mod(rs, ri, rmk)) => {
403            ls == rs
404                && eq_id(*li, *ri)
405                && match (lmk, rmk) {
406                    (ModKind::Loaded(litems, linline, _, _), ModKind::Loaded(ritems, rinline, _, _)) => {
407                        linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
408                    },
409                    (ModKind::Unloaded, ModKind::Unloaded) => true,
410                    _ => false,
411                }
412        },
413        (ForeignMod(l), ForeignMod(r)) => {
414            both(l.abi.as_ref(), r.abi.as_ref(), eq_str_lit)
415                && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
416        },
417        (
418            TyAlias(box ast::TyAlias {
419                defaultness: ld,
420                generics: lg,
421                bounds: lb,
422                ty: lt,
423                ..
424            }),
425            TyAlias(box ast::TyAlias {
426                defaultness: rd,
427                generics: rg,
428                bounds: rb,
429                ty: rt,
430                ..
431            }),
432        ) => {
433            eq_defaultness(*ld, *rd)
434                && eq_generics(lg, rg)
435                && over(lb, rb, eq_generic_bound)
436                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
437        },
438        (Enum(li, lg, le), Enum(ri, rg, re)) => {
439            eq_id(*li, *ri) && eq_generics(lg, rg) && over(&le.variants, &re.variants, eq_variant)
440        },
441        (Struct(li, lg, lv), Struct(ri, rg, rv)) | (Union(li, lg, lv), Union(ri, rg, rv)) => {
442            eq_id(*li, *ri) && eq_generics(lg, rg) && eq_variant_data(lv, rv)
443        },
444        (
445            Trait(box ast::Trait {
446                constness: lc,
447                is_auto: la,
448                safety: lu,
449                ident: li,
450                generics: lg,
451                bounds: lb,
452                items: lis,
453            }),
454            Trait(box ast::Trait {
455                constness: rc,
456                is_auto: ra,
457                safety: ru,
458                ident: ri,
459                generics: rg,
460                bounds: rb,
461                items: ris,
462            }),
463        ) => {
464            matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
465                && la == ra
466                && matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
467                && eq_id(*li, *ri)
468                && eq_generics(lg, rg)
469                && over(lb, rb, eq_generic_bound)
470                && over(lis, ris, |l, r| eq_item(l, r, eq_assoc_item_kind))
471        },
472        (TraitAlias(li, lg, lb), TraitAlias(ri, rg, rb)) => {
473            eq_id(*li, *ri) && eq_generics(lg, rg) && over(lb, rb, eq_generic_bound)
474        },
475        (
476            Impl(ast::Impl {
477                generics: lg,
478                of_trait: lot,
479                self_ty: lst,
480                items: li,
481            }),
482            Impl(ast::Impl {
483                generics: rg,
484                of_trait: rot,
485                self_ty: rst,
486                items: ri,
487            }),
488        ) => {
489            eq_generics(lg, rg)
490                && both(lot.as_deref(), rot.as_deref(), |l, r| {
491                    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
492                        && matches!(l.polarity, ImplPolarity::Positive) == matches!(r.polarity, ImplPolarity::Positive)
493                        && eq_defaultness(l.defaultness, r.defaultness)
494                        && matches!(l.constness, ast::Const::No) == matches!(r.constness, ast::Const::No)
495                        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
496                })
497                && eq_ty(lst, rst)
498                && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
499        },
500        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
501        (MacroDef(li, ld), MacroDef(ri, rd)) => {
502            eq_id(*li, *ri) && ld.macro_rules == rd.macro_rules && eq_delim_args(&ld.body, &rd.body)
503        },
504        _ => false,
505    }
506}
507
508pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
509    use ForeignItemKind::*;
510    match (l, r) {
511        (
512            Static(box StaticItem {
513                ident: li,
514                ty: lt,
515                mutability: lm,
516                expr: le,
517                safety: ls,
518                define_opaque: _,
519            }),
520            Static(box StaticItem {
521                ident: ri,
522                ty: rt,
523                mutability: rm,
524                expr: re,
525                safety: rs,
526                define_opaque: _,
527            }),
528        ) => eq_id(*li, *ri) && eq_ty(lt, rt) && lm == rm && eq_expr_opt(le.as_ref(), re.as_ref()) && ls == rs,
529        (
530            Fn(box ast::Fn {
531                defaultness: ld,
532                sig: lf,
533                ident: li,
534                generics: lg,
535                contract: lc,
536                body: lb,
537                define_opaque: _,
538            }),
539            Fn(box ast::Fn {
540                defaultness: rd,
541                sig: rf,
542                ident: ri,
543                generics: rg,
544                contract: rc,
545                body: rb,
546                define_opaque: _,
547            }),
548        ) => {
549            eq_defaultness(*ld, *rd)
550                && eq_fn_sig(lf, rf)
551                && eq_id(*li, *ri)
552                && eq_generics(lg, rg)
553                && eq_opt_fn_contract(lc, rc)
554                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
555        },
556        (
557            TyAlias(box ast::TyAlias {
558                defaultness: ld,
559                ident: li,
560                generics: lg,
561                where_clauses: _,
562                bounds: lb,
563                ty: lt,
564            }),
565            TyAlias(box ast::TyAlias {
566                defaultness: rd,
567                ident: ri,
568                generics: rg,
569                where_clauses: _,
570                bounds: rb,
571                ty: rt,
572            }),
573        ) => {
574            eq_defaultness(*ld, *rd)
575                && eq_id(*li, *ri)
576                && eq_generics(lg, rg)
577                && over(lb, rb, eq_generic_bound)
578                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
579        },
580        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
581        _ => false,
582    }
583}
584
585pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
586    use AssocItemKind::*;
587    match (l, r) {
588        (
589            Const(box ConstItem {
590                defaultness: ld,
591                ident: li,
592                generics: lg,
593                ty: lt,
594                expr: le,
595                define_opaque: _,
596            }),
597            Const(box ConstItem {
598                defaultness: rd,
599                ident: ri,
600                generics: rg,
601                ty: rt,
602                expr: re,
603                define_opaque: _,
604            }),
605        ) => {
606            eq_defaultness(*ld, *rd)
607                && eq_id(*li, *ri)
608                && eq_generics(lg, rg)
609                && eq_ty(lt, rt)
610                && eq_expr_opt(le.as_ref(), re.as_ref())
611        },
612        (
613            Fn(box ast::Fn {
614                defaultness: ld,
615                sig: lf,
616                ident: li,
617                generics: lg,
618                contract: lc,
619                body: lb,
620                define_opaque: _,
621            }),
622            Fn(box ast::Fn {
623                defaultness: rd,
624                sig: rf,
625                ident: ri,
626                generics: rg,
627                contract: rc,
628                body: rb,
629                define_opaque: _,
630            }),
631        ) => {
632            eq_defaultness(*ld, *rd)
633                && eq_fn_sig(lf, rf)
634                && eq_id(*li, *ri)
635                && eq_generics(lg, rg)
636                && eq_opt_fn_contract(lc, rc)
637                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
638        },
639        (
640            Type(box TyAlias {
641                defaultness: ld,
642                ident: li,
643                generics: lg,
644                where_clauses: _,
645                bounds: lb,
646                ty: lt,
647            }),
648            Type(box TyAlias {
649                defaultness: rd,
650                ident: ri,
651                generics: rg,
652                where_clauses: _,
653                bounds: rb,
654                ty: rt,
655            }),
656        ) => {
657            eq_defaultness(*ld, *rd)
658                && eq_id(*li, *ri)
659                && eq_generics(lg, rg)
660                && over(lb, rb, eq_generic_bound)
661                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
662        },
663        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
664        _ => false,
665    }
666}
667
668pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
669    l.is_placeholder == r.is_placeholder
670        && over(&l.attrs, &r.attrs, eq_attr)
671        && eq_vis(&l.vis, &r.vis)
672        && eq_id(l.ident, r.ident)
673        && eq_variant_data(&l.data, &r.data)
674        && both(l.disr_expr.as_ref(), r.disr_expr.as_ref(), |l, r| {
675            eq_expr(&l.value, &r.value)
676        })
677}
678
679pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
680    use VariantData::*;
681    match (l, r) {
682        (Unit(_), Unit(_)) => true,
683        (Struct { fields: l, .. }, Struct { fields: r, .. }) | (Tuple(l, _), Tuple(r, _)) => {
684            over(l, r, eq_struct_field)
685        },
686        _ => false,
687    }
688}
689
690pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
691    l.is_placeholder == r.is_placeholder
692        && over(&l.attrs, &r.attrs, eq_attr)
693        && eq_vis(&l.vis, &r.vis)
694        && both(l.ident.as_ref(), r.ident.as_ref(), |l, r| eq_id(*l, *r))
695        && eq_ty(&l.ty, &r.ty)
696}
697
698pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
699    eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
700}
701
702fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) -> bool {
703    matches!(
704        (l, r),
705        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
706            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
707            | (
708                Some(CoroutineKind::AsyncGen { .. }),
709                Some(CoroutineKind::AsyncGen { .. })
710            )
711            | (None, None)
712    )
713}
714
715pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
716    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
717        && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
718        && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
719        && eq_ext(&l.ext, &r.ext)
720}
721
722#[expect(clippy::ref_option, reason = "This is the type how it is stored in the AST")]
723pub fn eq_opt_fn_contract(l: &Option<Box<FnContract>>, r: &Option<Box<FnContract>>) -> bool {
724    match (l, r) {
725        (Some(l), Some(r)) => {
726            eq_expr_opt(l.requires.as_ref(), r.requires.as_ref()) && eq_expr_opt(l.ensures.as_ref(), r.ensures.as_ref())
727        },
728        (None, None) => true,
729        (Some(_), None) | (None, Some(_)) => false,
730    }
731}
732
733pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
734    over(&l.params, &r.params, eq_generic_param)
735        && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
736            eq_where_predicate(l, r)
737        })
738}
739
740pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
741    use WherePredicateKind::*;
742    over(&l.attrs, &r.attrs, eq_attr)
743        && match (&l.kind, &r.kind) {
744            (BoundPredicate(l), BoundPredicate(r)) => {
745                over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
746                    eq_generic_param(l, r)
747                }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
748                    && over(&l.bounds, &r.bounds, eq_generic_bound)
749            },
750            (RegionPredicate(l), RegionPredicate(r)) => {
751                eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
752            },
753            (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
754            _ => false,
755        }
756}
757
758pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
759    eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
760}
761
762pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
763    eq_expr(&l.value, &r.value)
764}
765
766pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
767    use UseTreeKind::*;
768    match (l, r) {
769        (Glob, Glob) => true,
770        (Simple(l), Simple(r)) => both(l.as_ref(), r.as_ref(), |l, r| eq_id(*l, *r)),
771        (Nested { items: l, .. }, Nested { items: r, .. }) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
772        _ => false,
773    }
774}
775
776pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
777    matches!(
778        (l, r),
779        (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_))
780    )
781}
782
783pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
784    use VisibilityKind::*;
785    match (&l.kind, &r.kind) {
786        (Public, Public) | (Inherited, Inherited) => true,
787        (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
788        _ => false,
789    }
790}
791
792pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
793    eq_fn_ret_ty(&l.output, &r.output)
794        && over(&l.inputs, &r.inputs, |l, r| {
795            l.is_placeholder == r.is_placeholder
796                && eq_pat(&l.pat, &r.pat)
797                && eq_ty(&l.ty, &r.ty)
798                && over(&l.attrs, &r.attrs, eq_attr)
799        })
800}
801
802pub fn eq_closure_binder(l: &ClosureBinder, r: &ClosureBinder) -> bool {
803    match (l, r) {
804        (ClosureBinder::NotPresent, ClosureBinder::NotPresent) => true,
805        (ClosureBinder::For { generic_params: lp, .. }, ClosureBinder::For { generic_params: rp, .. }) => {
806            lp.len() == rp.len() && std::iter::zip(lp.iter(), rp.iter()).all(|(l, r)| eq_generic_param(l, r))
807        },
808        _ => false,
809    }
810}
811
812pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
813    match (l, r) {
814        (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
815        (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
816        _ => false,
817    }
818}
819
820pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
821    use TyKind::*;
822    match (&l.kind, &r.kind) {
823        (Paren(l), _) => eq_ty(l, r),
824        (_, Paren(r)) => eq_ty(l, r),
825        (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err(_), Err(_)) | (CVarArgs, CVarArgs) => {
826            true
827        },
828        (Slice(l), Slice(r)) => eq_ty(l, r),
829        (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
830        (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
831        (Ref(ll, l), Ref(rl, r)) => {
832            both(ll.as_ref(), rl.as_ref(), |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
833        },
834        (PinnedRef(ll, l), PinnedRef(rl, r)) => {
835            both(ll.as_ref(), rl.as_ref(), |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty)
836        },
837        (FnPtr(l), FnPtr(r)) => {
838            l.safety == r.safety
839                && eq_ext(&l.ext, &r.ext)
840                && over(&l.generic_params, &r.generic_params, eq_generic_param)
841                && eq_fn_decl(&l.decl, &r.decl)
842        },
843        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
844        (Path(lq, lp), Path(rq, rp)) => both(lq.as_ref(), rq.as_ref(), eq_qself) && eq_path(lp, rp),
845        (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
846        (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
847        (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
848        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
849        _ => false,
850    }
851}
852
853pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
854    use Extern::*;
855    match (l, r) {
856        (None, None) | (Implicit(_), Implicit(_)) => true,
857        (Explicit(l, _), Explicit(r, _)) => eq_str_lit(l, r),
858        _ => false,
859    }
860}
861
862pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
863    l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
864}
865
866pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
867    l.modifiers == r.modifiers
868        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
869        && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
870            eq_generic_param(l, r)
871        })
872}
873
874pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
875    use GenericParamKind::*;
876    l.is_placeholder == r.is_placeholder
877        && eq_id(l.ident, r.ident)
878        && over(&l.bounds, &r.bounds, eq_generic_bound)
879        && match (&l.kind, &r.kind) {
880            (Lifetime, Lifetime) => true,
881            (Type { default: l }, Type { default: r }) => both(l.as_ref(), r.as_ref(), |l, r| eq_ty(l, r)),
882            (
883                Const {
884                    ty: lt,
885                    default: ld,
886                    span: _,
887                },
888                Const {
889                    ty: rt,
890                    default: rd,
891                    span: _,
892                },
893            ) => eq_ty(lt, rt) && both(ld.as_ref(), rd.as_ref(), eq_anon_const),
894            _ => false,
895        }
896        && over(&l.attrs, &r.attrs, eq_attr)
897}
898
899pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
900    use GenericBound::*;
901    match (l, r) {
902        (Trait(ptr1), Trait(ptr2)) => eq_poly_ref_trait(ptr1, ptr2),
903        (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
904        _ => false,
905    }
906}
907
908pub fn eq_precise_capture(l: &PreciseCapturingArg, r: &PreciseCapturingArg) -> bool {
909    match (l, r) {
910        (PreciseCapturingArg::Lifetime(l), PreciseCapturingArg::Lifetime(r)) => l.ident == r.ident,
911        (PreciseCapturingArg::Arg(l, _), PreciseCapturingArg::Arg(r, _)) => l.segments[0].ident == r.segments[0].ident,
912        _ => false,
913    }
914}
915
916fn eq_term(l: &Term, r: &Term) -> bool {
917    match (l, r) {
918        (Term::Ty(l), Term::Ty(r)) => eq_ty(l, r),
919        (Term::Const(l), Term::Const(r)) => eq_anon_const(l, r),
920        _ => false,
921    }
922}
923
924pub fn eq_assoc_item_constraint(l: &AssocItemConstraint, r: &AssocItemConstraint) -> bool {
925    use AssocItemConstraintKind::*;
926    eq_id(l.ident, r.ident)
927        && match (&l.kind, &r.kind) {
928            (Equality { term: l }, Equality { term: r }) => eq_term(l, r),
929            (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
930            _ => false,
931        }
932}
933
934pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
935    eq_path(&l.path, &r.path) && eq_delim_args(&l.args, &r.args)
936}
937
938pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
939    use AttrKind::*;
940    l.style == r.style
941        && match (&l.kind, &r.kind) {
942            (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
943            (Normal(l), Normal(r)) => eq_path(&l.item.path, &r.item.path) && eq_attr_args(&l.item.args, &r.item.args),
944            _ => false,
945        }
946}
947
948pub fn eq_attr_args(l: &AttrArgs, r: &AttrArgs) -> bool {
949    use AttrArgs::*;
950    match (l, r) {
951        (Empty, Empty) => true,
952        (Delimited(la), Delimited(ra)) => eq_delim_args(la, ra),
953        (Eq { eq_span: _, expr: le }, Eq { eq_span: _, expr: re }) => eq_expr(le, re),
954        _ => false,
955    }
956}
957
958pub fn eq_delim_args(l: &DelimArgs, r: &DelimArgs) -> bool {
959    l.delim == r.delim
960        && l.tokens.len() == r.tokens.len()
961        && l.tokens.iter().zip(r.tokens.iter()).all(|(a, b)| a.eq_unspanned(b))
962}