Skip to main content

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().map(|g| &g.cond), r.guard.as_deref().map(|g| &g.cond))
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                eii_impls: _,
343            }),
344            Static(box StaticItem {
345                ident: ri,
346                ty: rt,
347                mutability: rm,
348                expr: re,
349                safety: rs,
350                define_opaque: _,
351                eii_impls: _,
352            }),
353        ) => eq_id(*li, *ri) && lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_deref(), re.as_deref()),
354        (
355            Const(box ConstItem {
356                defaultness: ld,
357                ident: li,
358                generics: lg,
359                ty: lt,
360                rhs_kind: lb,
361                define_opaque: _,
362            }),
363            Const(box ConstItem {
364                defaultness: rd,
365                ident: ri,
366                generics: rg,
367                ty: rt,
368                rhs_kind: rb,
369                define_opaque: _,
370            }),
371        ) => {
372            eq_defaultness(*ld, *rd)
373                && eq_id(*li, *ri)
374                && eq_generics(lg, rg)
375                && eq_ty(lt, rt)
376                && both(Some(lb), Some(rb), eq_const_item_rhs)
377        },
378        (
379            Fn(box ast::Fn {
380                defaultness: ld,
381                sig: lf,
382                ident: li,
383                generics: lg,
384                contract: lc,
385                body: lb,
386                define_opaque: _,
387                eii_impls: _,
388            }),
389            Fn(box ast::Fn {
390                defaultness: rd,
391                sig: rf,
392                ident: ri,
393                generics: rg,
394                contract: rc,
395                body: rb,
396                define_opaque: _,
397                eii_impls: _,
398            }),
399        ) => {
400            eq_defaultness(*ld, *rd)
401                && eq_fn_sig(lf, rf)
402                && eq_id(*li, *ri)
403                && eq_generics(lg, rg)
404                && eq_opt_fn_contract(lc, rc)
405                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
406        },
407        (Mod(ls, li, lmk), Mod(rs, ri, rmk)) => {
408            ls == rs
409                && eq_id(*li, *ri)
410                && match (lmk, rmk) {
411                    (ModKind::Loaded(litems, linline, _), ModKind::Loaded(ritems, rinline, _)) => {
412                        linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
413                    },
414                    (ModKind::Unloaded, ModKind::Unloaded) => true,
415                    _ => false,
416                }
417        },
418        (ForeignMod(l), ForeignMod(r)) => {
419            both(l.abi.as_ref(), r.abi.as_ref(), eq_str_lit)
420                && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
421        },
422        (
423            TyAlias(box ast::TyAlias {
424                defaultness: ld,
425                generics: lg,
426                bounds: lb,
427                ty: lt,
428                ..
429            }),
430            TyAlias(box ast::TyAlias {
431                defaultness: rd,
432                generics: rg,
433                bounds: rb,
434                ty: rt,
435                ..
436            }),
437        ) => {
438            eq_defaultness(*ld, *rd)
439                && eq_generics(lg, rg)
440                && over(lb, rb, eq_generic_bound)
441                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
442        },
443        (Enum(li, lg, le), Enum(ri, rg, re)) => {
444            eq_id(*li, *ri) && eq_generics(lg, rg) && over(&le.variants, &re.variants, eq_variant)
445        },
446        (Struct(li, lg, lv), Struct(ri, rg, rv)) | (Union(li, lg, lv), Union(ri, rg, rv)) => {
447            eq_id(*li, *ri) && eq_generics(lg, rg) && eq_variant_data(lv, rv)
448        },
449        (
450            Trait(box ast::Trait {
451                impl_restriction: liprt,
452                constness: lc,
453                is_auto: la,
454                safety: lu,
455                ident: li,
456                generics: lg,
457                bounds: lb,
458                items: lis,
459            }),
460            Trait(box ast::Trait {
461                impl_restriction: riprt,
462                constness: rc,
463                is_auto: ra,
464                safety: ru,
465                ident: ri,
466                generics: rg,
467                bounds: rb,
468                items: ris,
469            }),
470        ) => {
471            eq_impl_restriction(liprt, riprt)
472                && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
473                && la == ra
474                && matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
475                && eq_id(*li, *ri)
476                && eq_generics(lg, rg)
477                && over(lb, rb, eq_generic_bound)
478                && over(lis, ris, |l, r| eq_item(l, r, eq_assoc_item_kind))
479        },
480        (
481            TraitAlias(box ast::TraitAlias {
482                ident: li,
483                generics: lg,
484                bounds: lb,
485                constness: lc,
486            }),
487            TraitAlias(box ast::TraitAlias {
488                ident: ri,
489                generics: rg,
490                bounds: rb,
491                constness: rc,
492            }),
493        ) => {
494            matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
495                && eq_id(*li, *ri)
496                && eq_generics(lg, rg)
497                && over(lb, rb, eq_generic_bound)
498        },
499        (
500            Impl(ast::Impl {
501                generics: lg,
502                of_trait: lot,
503                self_ty: lst,
504                items: li,
505                constness: lc,
506            }),
507            Impl(ast::Impl {
508                generics: rg,
509                of_trait: rot,
510                self_ty: rst,
511                items: ri,
512                constness: rc,
513            }),
514        ) => {
515            eq_generics(lg, rg)
516                && both(lot.as_deref(), rot.as_deref(), |l, r| {
517                    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
518                        && matches!(l.polarity, ImplPolarity::Positive) == matches!(r.polarity, ImplPolarity::Positive)
519                        && eq_defaultness(l.defaultness, r.defaultness)
520                        && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
521                        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
522                })
523                && eq_ty(lst, rst)
524                && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
525        },
526        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
527        (MacroDef(li, ld), MacroDef(ri, rd)) => {
528            eq_id(*li, *ri) && ld.macro_rules == rd.macro_rules && eq_delim_args(&ld.body, &rd.body)
529        },
530        _ => false,
531    }
532}
533
534pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
535    use ForeignItemKind::*;
536    match (l, r) {
537        (
538            Static(box StaticItem {
539                ident: li,
540                ty: lt,
541                mutability: lm,
542                expr: le,
543                safety: ls,
544                define_opaque: _,
545                eii_impls: _,
546            }),
547            Static(box StaticItem {
548                ident: ri,
549                ty: rt,
550                mutability: rm,
551                expr: re,
552                safety: rs,
553                define_opaque: _,
554                eii_impls: _,
555            }),
556        ) => eq_id(*li, *ri) && eq_ty(lt, rt) && lm == rm && eq_expr_opt(le.as_deref(), re.as_deref()) && ls == rs,
557        (
558            Fn(box ast::Fn {
559                defaultness: ld,
560                sig: lf,
561                ident: li,
562                generics: lg,
563                contract: lc,
564                body: lb,
565                define_opaque: _,
566                eii_impls: _,
567            }),
568            Fn(box ast::Fn {
569                defaultness: rd,
570                sig: rf,
571                ident: ri,
572                generics: rg,
573                contract: rc,
574                body: rb,
575                define_opaque: _,
576                eii_impls: _,
577            }),
578        ) => {
579            eq_defaultness(*ld, *rd)
580                && eq_fn_sig(lf, rf)
581                && eq_id(*li, *ri)
582                && eq_generics(lg, rg)
583                && eq_opt_fn_contract(lc, rc)
584                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
585        },
586        (
587            TyAlias(box ast::TyAlias {
588                defaultness: ld,
589                ident: li,
590                generics: lg,
591                after_where_clause: lw,
592                bounds: lb,
593                ty: lt,
594            }),
595            TyAlias(box ast::TyAlias {
596                defaultness: rd,
597                ident: ri,
598                generics: rg,
599                after_where_clause: rw,
600                bounds: rb,
601                ty: rt,
602            }),
603        ) => {
604            eq_defaultness(*ld, *rd)
605                && eq_id(*li, *ri)
606                && eq_generics(lg, rg)
607                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
608                && over(lb, rb, eq_generic_bound)
609                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
610        },
611        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
612        _ => false,
613    }
614}
615
616pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
617    use AssocItemKind::*;
618    match (l, r) {
619        (
620            Const(box ConstItem {
621                defaultness: ld,
622                ident: li,
623                generics: lg,
624                ty: lt,
625                rhs_kind: lb,
626                define_opaque: _,
627            }),
628            Const(box ConstItem {
629                defaultness: rd,
630                ident: ri,
631                generics: rg,
632                ty: rt,
633                rhs_kind: rb,
634                define_opaque: _,
635            }),
636        ) => {
637            eq_defaultness(*ld, *rd)
638                && eq_id(*li, *ri)
639                && eq_generics(lg, rg)
640                && eq_ty(lt, rt)
641                && both(Some(lb), Some(rb), eq_const_item_rhs)
642        },
643        (
644            Fn(box ast::Fn {
645                defaultness: ld,
646                sig: lf,
647                ident: li,
648                generics: lg,
649                contract: lc,
650                body: lb,
651                define_opaque: _,
652                eii_impls: _,
653            }),
654            Fn(box ast::Fn {
655                defaultness: rd,
656                sig: rf,
657                ident: ri,
658                generics: rg,
659                contract: rc,
660                body: rb,
661                define_opaque: _,
662                eii_impls: _,
663            }),
664        ) => {
665            eq_defaultness(*ld, *rd)
666                && eq_fn_sig(lf, rf)
667                && eq_id(*li, *ri)
668                && eq_generics(lg, rg)
669                && eq_opt_fn_contract(lc, rc)
670                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
671        },
672        (
673            Type(box TyAlias {
674                defaultness: ld,
675                ident: li,
676                generics: lg,
677                after_where_clause: lw,
678                bounds: lb,
679                ty: lt,
680            }),
681            Type(box TyAlias {
682                defaultness: rd,
683                ident: ri,
684                generics: rg,
685                after_where_clause: rw,
686                bounds: rb,
687                ty: rt,
688            }),
689        ) => {
690            eq_defaultness(*ld, *rd)
691                && eq_id(*li, *ri)
692                && eq_generics(lg, rg)
693                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
694                && over(lb, rb, eq_generic_bound)
695                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
696        },
697        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
698        _ => false,
699    }
700}
701
702pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
703    l.is_placeholder == r.is_placeholder
704        && over(&l.attrs, &r.attrs, eq_attr)
705        && eq_vis(&l.vis, &r.vis)
706        && eq_id(l.ident, r.ident)
707        && eq_variant_data(&l.data, &r.data)
708        && both(l.disr_expr.as_ref(), r.disr_expr.as_ref(), |l, r| {
709            eq_expr(&l.value, &r.value)
710        })
711}
712
713pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
714    use VariantData::*;
715    match (l, r) {
716        (Unit(_), Unit(_)) => true,
717        (Struct { fields: l, .. }, Struct { fields: r, .. }) | (Tuple(l, _), Tuple(r, _)) => {
718            over(l, r, eq_struct_field)
719        },
720        _ => false,
721    }
722}
723
724pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
725    l.is_placeholder == r.is_placeholder
726        && over(&l.attrs, &r.attrs, eq_attr)
727        && eq_vis(&l.vis, &r.vis)
728        && both(l.ident.as_ref(), r.ident.as_ref(), |l, r| eq_id(*l, *r))
729        && eq_ty(&l.ty, &r.ty)
730}
731
732pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
733    eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
734}
735
736fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) -> bool {
737    matches!(
738        (l, r),
739        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
740            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
741            | (
742                Some(CoroutineKind::AsyncGen { .. }),
743                Some(CoroutineKind::AsyncGen { .. })
744            )
745            | (None, None)
746    )
747}
748
749pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
750    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
751        && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
752        && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
753        && eq_ext(&l.ext, &r.ext)
754}
755
756#[expect(clippy::ref_option, reason = "This is the type how it is stored in the AST")]
757pub fn eq_opt_fn_contract(l: &Option<Box<FnContract>>, r: &Option<Box<FnContract>>) -> bool {
758    match (l, r) {
759        (Some(l), Some(r)) => {
760            eq_expr_opt(l.requires.as_deref(), r.requires.as_deref())
761                && eq_expr_opt(l.ensures.as_deref(), r.ensures.as_deref())
762        },
763        (None, None) => true,
764        (Some(_), None) | (None, Some(_)) => false,
765    }
766}
767
768pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
769    over(&l.params, &r.params, eq_generic_param)
770        && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
771            eq_where_predicate(l, r)
772        })
773}
774
775pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
776    use WherePredicateKind::*;
777    over(&l.attrs, &r.attrs, eq_attr)
778        && match (&l.kind, &r.kind) {
779            (BoundPredicate(l), BoundPredicate(r)) => {
780                over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
781                    eq_generic_param(l, r)
782                }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
783                    && over(&l.bounds, &r.bounds, eq_generic_bound)
784            },
785            (RegionPredicate(l), RegionPredicate(r)) => {
786                eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
787            },
788            (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
789            _ => false,
790        }
791}
792
793pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
794    eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
795}
796
797pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
798    eq_expr(&l.value, &r.value)
799}
800
801pub fn eq_const_item_rhs(l: &ConstItemRhsKind, r: &ConstItemRhsKind) -> bool {
802    use ConstItemRhsKind::*;
803    match (l, r) {
804        (TypeConst { rhs: Some(l) }, TypeConst { rhs: Some(r) }) => eq_anon_const(l, r),
805        (TypeConst { rhs: None }, TypeConst { rhs: None }) | (Body { rhs: None }, Body { rhs: None }) => true,
806        (Body { rhs: Some(l) }, Body { rhs: Some(r) }) => eq_expr(l, r),
807        (TypeConst { rhs: Some(..) }, TypeConst { rhs: None })
808        | (TypeConst { rhs: None }, TypeConst { rhs: Some(..) })
809        | (Body { rhs: None }, Body { rhs: Some(..) })
810        | (Body { rhs: Some(..) }, Body { rhs: None })
811        | (TypeConst { .. }, Body { .. })
812        | (Body { .. }, TypeConst { .. }) => false,
813    }
814}
815
816pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
817    use UseTreeKind::*;
818    match (l, r) {
819        (Glob(_), Glob(_)) => true,
820        (Simple(l), Simple(r)) => both(l.as_ref(), r.as_ref(), |l, r| eq_id(*l, *r)),
821        (Nested { items: l, .. }, Nested { items: r, .. }) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
822        _ => false,
823    }
824}
825
826pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
827    matches!(
828        (l, r),
829        (Defaultness::Implicit, Defaultness::Implicit)
830            | (Defaultness::Default(_), Defaultness::Default(_))
831            | (Defaultness::Final(_), Defaultness::Final(_))
832    )
833}
834
835pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
836    use VisibilityKind::*;
837    match (&l.kind, &r.kind) {
838        (Public, Public) | (Inherited, Inherited) => true,
839        (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
840        _ => false,
841    }
842}
843
844pub fn eq_impl_restriction(l: &ImplRestriction, r: &ImplRestriction) -> bool {
845    eq_restriction_kind(&l.kind, &r.kind)
846}
847
848fn eq_restriction_kind(l: &RestrictionKind, r: &RestrictionKind) -> bool {
849    match (l, r) {
850        (RestrictionKind::Unrestricted, RestrictionKind::Unrestricted) => true,
851        (
852            RestrictionKind::Restricted {
853                path: l_path,
854                shorthand: l_short,
855                id: _,
856            },
857            RestrictionKind::Restricted {
858                path: r_path,
859                shorthand: r_short,
860                id: _,
861            },
862        ) => l_short == r_short && eq_path(l_path, r_path),
863        _ => false,
864    }
865}
866
867pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
868    eq_fn_ret_ty(&l.output, &r.output)
869        && over(&l.inputs, &r.inputs, |l, r| {
870            l.is_placeholder == r.is_placeholder
871                && eq_pat(&l.pat, &r.pat)
872                && eq_ty(&l.ty, &r.ty)
873                && over(&l.attrs, &r.attrs, eq_attr)
874        })
875}
876
877pub fn eq_closure_binder(l: &ClosureBinder, r: &ClosureBinder) -> bool {
878    match (l, r) {
879        (ClosureBinder::NotPresent, ClosureBinder::NotPresent) => true,
880        (ClosureBinder::For { generic_params: lp, .. }, ClosureBinder::For { generic_params: rp, .. }) => {
881            lp.len() == rp.len() && std::iter::zip(lp.iter(), rp.iter()).all(|(l, r)| eq_generic_param(l, r))
882        },
883        _ => false,
884    }
885}
886
887pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
888    match (l, r) {
889        (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
890        (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
891        _ => false,
892    }
893}
894
895pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
896    use TyKind::*;
897    match (&l.kind, &r.kind) {
898        (Paren(l), _) => eq_ty(l, r),
899        (_, Paren(r)) => eq_ty(l, r),
900        (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err(_), Err(_)) | (CVarArgs, CVarArgs) => {
901            true
902        },
903        (Slice(l), Slice(r)) => eq_ty(l, r),
904        (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
905        (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
906        (Ref(ll, l), Ref(rl, r)) => {
907            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)
908        },
909        (PinnedRef(ll, l), PinnedRef(rl, r)) => {
910            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)
911        },
912        (FnPtr(l), FnPtr(r)) => {
913            l.safety == r.safety
914                && eq_ext(&l.ext, &r.ext)
915                && over(&l.generic_params, &r.generic_params, eq_generic_param)
916                && eq_fn_decl(&l.decl, &r.decl)
917        },
918        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
919        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
920        (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
921        (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
922        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
923        _ => false,
924    }
925}
926
927pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
928    use Extern::*;
929    match (l, r) {
930        (None, None) | (Implicit(_), Implicit(_)) => true,
931        (Explicit(l, _), Explicit(r, _)) => eq_str_lit(l, r),
932        _ => false,
933    }
934}
935
936pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
937    l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
938}
939
940pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
941    l.modifiers == r.modifiers
942        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
943        && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
944            eq_generic_param(l, r)
945        })
946}
947
948pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
949    use GenericParamKind::*;
950    l.is_placeholder == r.is_placeholder
951        && eq_id(l.ident, r.ident)
952        && over(&l.bounds, &r.bounds, eq_generic_bound)
953        && match (&l.kind, &r.kind) {
954            (Lifetime, Lifetime) => true,
955            (Type { default: l }, Type { default: r }) => both(l.as_ref(), r.as_ref(), |l, r| eq_ty(l, r)),
956            (
957                Const {
958                    ty: lt,
959                    default: ld,
960                    span: _,
961                },
962                Const {
963                    ty: rt,
964                    default: rd,
965                    span: _,
966                },
967            ) => eq_ty(lt, rt) && both(ld.as_ref(), rd.as_ref(), eq_anon_const),
968            _ => false,
969        }
970        && over(&l.attrs, &r.attrs, eq_attr)
971}
972
973pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
974    use GenericBound::*;
975    match (l, r) {
976        (Trait(ptr1), Trait(ptr2)) => eq_poly_ref_trait(ptr1, ptr2),
977        (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
978        _ => false,
979    }
980}
981
982pub fn eq_precise_capture(l: &PreciseCapturingArg, r: &PreciseCapturingArg) -> bool {
983    match (l, r) {
984        (PreciseCapturingArg::Lifetime(l), PreciseCapturingArg::Lifetime(r)) => l.ident == r.ident,
985        (PreciseCapturingArg::Arg(l, _), PreciseCapturingArg::Arg(r, _)) => l.segments[0].ident == r.segments[0].ident,
986        _ => false,
987    }
988}
989
990fn eq_term(l: &Term, r: &Term) -> bool {
991    match (l, r) {
992        (Term::Ty(l), Term::Ty(r)) => eq_ty(l, r),
993        (Term::Const(l), Term::Const(r)) => eq_anon_const(l, r),
994        _ => false,
995    }
996}
997
998pub fn eq_assoc_item_constraint(l: &AssocItemConstraint, r: &AssocItemConstraint) -> bool {
999    use AssocItemConstraintKind::*;
1000    eq_id(l.ident, r.ident)
1001        && match (&l.kind, &r.kind) {
1002            (Equality { term: l }, Equality { term: r }) => eq_term(l, r),
1003            (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
1004            _ => false,
1005        }
1006}
1007
1008pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
1009    eq_path(&l.path, &r.path) && eq_delim_args(&l.args, &r.args)
1010}
1011
1012pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
1013    use AttrKind::*;
1014    l.style == r.style
1015        && match (&l.kind, &r.kind) {
1016            (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
1017            (Normal(l), Normal(r)) => {
1018                eq_path(&l.item.path, &r.item.path) && eq_attr_item_kind(&l.item.args, &r.item.args)
1019            },
1020            _ => false,
1021        }
1022}
1023
1024pub fn eq_attr_item_kind(l: &AttrItemKind, r: &AttrItemKind) -> bool {
1025    match (l, r) {
1026        (AttrItemKind::Unparsed(l), AttrItemKind::Unparsed(r)) => eq_attr_args(l, r),
1027        (AttrItemKind::Parsed(_l), AttrItemKind::Parsed(_r)) => todo!(),
1028        _ => false,
1029    }
1030}
1031
1032pub fn eq_attr_args(l: &AttrArgs, r: &AttrArgs) -> bool {
1033    use AttrArgs::*;
1034    match (l, r) {
1035        (Empty, Empty) => true,
1036        (Delimited(la), Delimited(ra)) => eq_delim_args(la, ra),
1037        (Eq { eq_span: _, expr: le }, Eq { eq_span: _, expr: re }) => eq_expr(le, re),
1038        _ => false,
1039    }
1040}
1041
1042pub fn eq_delim_args(l: &DelimArgs, r: &DelimArgs) -> bool {
1043    l.delim == r.delim
1044        && l.tokens.len() == r.tokens.len()
1045        && l.tokens.iter().zip(r.tokens.iter()).all(|(a, b)| a.eq_unspanned(b))
1046}