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