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