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