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