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(l), TryBlock(r)) => eq_block(l, r),
203        (Yield(l), Yield(r)) => eq_expr_opt(l.expr().map(Box::as_ref), r.expr().map(Box::as_ref)) && l.same_kind(r),
204        (Ret(l), Ret(r)) => eq_expr_opt(l.as_deref(), r.as_deref()),
205        (Break(ll, le), Break(rl, re)) => {
206            eq_label(ll.as_ref(), rl.as_ref()) && eq_expr_opt(le.as_deref(), re.as_deref())
207        },
208        (Continue(ll), Continue(rl)) => eq_label(ll.as_ref(), rl.as_ref()),
209        (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2, _), Index(r1, r2, _)) => {
210            eq_expr(l1, r1) && eq_expr(l2, r2)
211        },
212        (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
213        (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
214        (Match(ls, la, lkind), Match(rs, ra, rkind)) => (lkind == rkind) && eq_expr(ls, rs) && over(la, ra, eq_arm),
215        (
216            Closure(box ast::Closure {
217                binder: lb,
218                capture_clause: lc,
219                coroutine_kind: la,
220                movability: lm,
221                fn_decl: lf,
222                body: le,
223                ..
224            }),
225            Closure(box ast::Closure {
226                binder: rb,
227                capture_clause: rc,
228                coroutine_kind: ra,
229                movability: rm,
230                fn_decl: rf,
231                body: re,
232                ..
233            }),
234        ) => {
235            eq_closure_binder(lb, rb)
236                && lc == rc
237                && eq_coroutine_kind(*la, *ra)
238                && lm == rm
239                && eq_fn_decl(lf, rf)
240                && eq_expr(le, re)
241        },
242        (Gen(lc, lb, lk, _), Gen(rc, rb, rk, _)) => lc == rc && eq_block(lb, rb) && lk == rk,
243        (Range(lf, lt, ll), Range(rf, rt, rl)) => {
244            ll == rl && eq_expr_opt(lf.as_deref(), rf.as_deref()) && eq_expr_opt(lt.as_deref(), rt.as_deref())
245        },
246        (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
247        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
248        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
249        (Struct(lse), Struct(rse)) => {
250            eq_maybe_qself(lse.qself.as_deref(), rse.qself.as_deref())
251                && eq_path(&lse.path, &rse.path)
252                && eq_struct_rest(&lse.rest, &rse.rest)
253                && unordered_over(&lse.fields, &rse.fields, eq_field)
254        },
255        _ => false,
256    }
257}
258
259fn eq_coroutine_kind(a: Option<CoroutineKind>, b: Option<CoroutineKind>) -> bool {
260    matches!(
261        (a, b),
262        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
263            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
264            | (
265                Some(CoroutineKind::AsyncGen { .. }),
266                Some(CoroutineKind::AsyncGen { .. })
267            )
268            | (None, None)
269    )
270}
271
272pub fn eq_field(l: &ExprField, r: &ExprField) -> bool {
273    l.is_placeholder == r.is_placeholder
274        && eq_id(l.ident, r.ident)
275        && eq_expr(&l.expr, &r.expr)
276        && over(&l.attrs, &r.attrs, eq_attr)
277}
278
279pub fn eq_arm(l: &Arm, r: &Arm) -> bool {
280    l.is_placeholder == r.is_placeholder
281        && eq_pat(&l.pat, &r.pat)
282        && eq_expr_opt(l.body.as_deref(), r.body.as_deref())
283        && eq_expr_opt(l.guard.as_deref(), r.guard.as_deref())
284        && over(&l.attrs, &r.attrs, eq_attr)
285}
286
287pub fn eq_label(l: Option<&Label>, r: Option<&Label>) -> bool {
288    both(l, r, |l, r| eq_id(l.ident, r.ident))
289}
290
291pub fn eq_block(l: &Block, r: &Block) -> bool {
292    l.rules == r.rules && over(&l.stmts, &r.stmts, eq_stmt)
293}
294
295pub fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
296    use StmtKind::*;
297    match (&l.kind, &r.kind) {
298        (Let(l), Let(r)) => {
299            eq_pat(&l.pat, &r.pat)
300                && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| eq_ty(l, r))
301                && eq_local_kind(&l.kind, &r.kind)
302                && over(&l.attrs, &r.attrs, eq_attr)
303        },
304        (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
305        (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
306        (Empty, Empty) => true,
307        (MacCall(l), MacCall(r)) => {
308            l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, eq_attr)
309        },
310        _ => false,
311    }
312}
313
314pub fn eq_local_kind(l: &LocalKind, r: &LocalKind) -> bool {
315    use LocalKind::*;
316    match (l, r) {
317        (Decl, Decl) => true,
318        (Init(l), Init(r)) => eq_expr(l, r),
319        (InitElse(li, le), InitElse(ri, re)) => eq_expr(li, ri) && eq_block(le, re),
320        _ => false,
321    }
322}
323
324pub fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
325    over(&l.attrs, &r.attrs, eq_attr) && eq_vis(&l.vis, &r.vis) && eq_kind(&l.kind, &r.kind)
326}
327
328#[expect(clippy::too_many_lines, reason = "big match statement")]
329pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
330    use ItemKind::*;
331    match (l, r) {
332        (ExternCrate(ls, li), ExternCrate(rs, ri)) => ls == rs && eq_id(*li, *ri),
333        (Use(l), Use(r)) => eq_use_tree(l, r),
334        (
335            Static(box StaticItem {
336                ident: li,
337                ty: lt,
338                mutability: lm,
339                expr: le,
340                safety: ls,
341                define_opaque: _,
342            }),
343            Static(box StaticItem {
344                ident: ri,
345                ty: rt,
346                mutability: rm,
347                expr: re,
348                safety: rs,
349                define_opaque: _,
350            }),
351        ) => eq_id(*li, *ri) && lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_deref(), re.as_deref()),
352        (
353            Const(box ConstItem {
354                defaultness: ld,
355                ident: li,
356                generics: lg,
357                ty: lt,
358                rhs: lb,
359                define_opaque: _,
360            }),
361            Const(box ConstItem {
362                defaultness: rd,
363                ident: ri,
364                generics: rg,
365                ty: rt,
366                rhs: rb,
367                define_opaque: _,
368            }),
369        ) => {
370            eq_defaultness(*ld, *rd)
371                && eq_id(*li, *ri)
372                && eq_generics(lg, rg)
373                && eq_ty(lt, rt)
374                && both(lb.as_ref(), rb.as_ref(), eq_const_item_rhs)
375        },
376        (
377            Fn(box ast::Fn {
378                defaultness: ld,
379                sig: lf,
380                ident: li,
381                generics: lg,
382                contract: lc,
383                body: lb,
384                define_opaque: _,
385            }),
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        (
474            TraitAlias(box ast::TraitAlias {
475                ident: li,
476                generics: lg,
477                bounds: lb,
478                constness: lc,
479            }),
480            TraitAlias(box ast::TraitAlias {
481                ident: ri,
482                generics: rg,
483                bounds: rb,
484                constness: rc,
485            }),
486        ) => {
487            matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
488                && eq_id(*li, *ri)
489                && eq_generics(lg, rg)
490                && over(lb, rb, eq_generic_bound)
491        },
492        (
493            Impl(ast::Impl {
494                generics: lg,
495                of_trait: lot,
496                self_ty: lst,
497                items: li,
498                constness: lc,
499            }),
500            Impl(ast::Impl {
501                generics: rg,
502                of_trait: rot,
503                self_ty: rst,
504                items: ri,
505                constness: rc,
506            }),
507        ) => {
508            eq_generics(lg, rg)
509                && both(lot.as_deref(), rot.as_deref(), |l, r| {
510                    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
511                        && matches!(l.polarity, ImplPolarity::Positive) == matches!(r.polarity, ImplPolarity::Positive)
512                        && eq_defaultness(l.defaultness, r.defaultness)
513                        && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
514                        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
515                })
516                && eq_ty(lst, rst)
517                && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
518        },
519        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
520        (MacroDef(li, ld), MacroDef(ri, rd)) => {
521            eq_id(*li, *ri) && ld.macro_rules == rd.macro_rules && eq_delim_args(&ld.body, &rd.body)
522        },
523        _ => false,
524    }
525}
526
527pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
528    use ForeignItemKind::*;
529    match (l, r) {
530        (
531            Static(box StaticItem {
532                ident: li,
533                ty: lt,
534                mutability: lm,
535                expr: le,
536                safety: ls,
537                define_opaque: _,
538            }),
539            Static(box StaticItem {
540                ident: ri,
541                ty: rt,
542                mutability: rm,
543                expr: re,
544                safety: rs,
545                define_opaque: _,
546            }),
547        ) => eq_id(*li, *ri) && eq_ty(lt, rt) && lm == rm && eq_expr_opt(le.as_deref(), re.as_deref()) && ls == rs,
548        (
549            Fn(box ast::Fn {
550                defaultness: ld,
551                sig: lf,
552                ident: li,
553                generics: lg,
554                contract: lc,
555                body: lb,
556                define_opaque: _,
557            }),
558            Fn(box ast::Fn {
559                defaultness: rd,
560                sig: rf,
561                ident: ri,
562                generics: rg,
563                contract: rc,
564                body: rb,
565                define_opaque: _,
566            }),
567        ) => {
568            eq_defaultness(*ld, *rd)
569                && eq_fn_sig(lf, rf)
570                && eq_id(*li, *ri)
571                && eq_generics(lg, rg)
572                && eq_opt_fn_contract(lc, rc)
573                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
574        },
575        (
576            TyAlias(box ast::TyAlias {
577                defaultness: ld,
578                ident: li,
579                generics: lg,
580                after_where_clause: lw,
581                bounds: lb,
582                ty: lt,
583            }),
584            TyAlias(box ast::TyAlias {
585                defaultness: rd,
586                ident: ri,
587                generics: rg,
588                after_where_clause: rw,
589                bounds: rb,
590                ty: rt,
591            }),
592        ) => {
593            eq_defaultness(*ld, *rd)
594                && eq_id(*li, *ri)
595                && eq_generics(lg, rg)
596                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
597                && over(lb, rb, eq_generic_bound)
598                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
599        },
600        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
601        _ => false,
602    }
603}
604
605pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
606    use AssocItemKind::*;
607    match (l, r) {
608        (
609            Const(box ConstItem {
610                defaultness: ld,
611                ident: li,
612                generics: lg,
613                ty: lt,
614                rhs: lb,
615                define_opaque: _,
616            }),
617            Const(box ConstItem {
618                defaultness: rd,
619                ident: ri,
620                generics: rg,
621                ty: rt,
622                rhs: rb,
623                define_opaque: _,
624            }),
625        ) => {
626            eq_defaultness(*ld, *rd)
627                && eq_id(*li, *ri)
628                && eq_generics(lg, rg)
629                && eq_ty(lt, rt)
630                && both(lb.as_ref(), rb.as_ref(), eq_const_item_rhs)
631        },
632        (
633            Fn(box ast::Fn {
634                defaultness: ld,
635                sig: lf,
636                ident: li,
637                generics: lg,
638                contract: lc,
639                body: lb,
640                define_opaque: _,
641            }),
642            Fn(box ast::Fn {
643                defaultness: rd,
644                sig: rf,
645                ident: ri,
646                generics: rg,
647                contract: rc,
648                body: rb,
649                define_opaque: _,
650            }),
651        ) => {
652            eq_defaultness(*ld, *rd)
653                && eq_fn_sig(lf, rf)
654                && eq_id(*li, *ri)
655                && eq_generics(lg, rg)
656                && eq_opt_fn_contract(lc, rc)
657                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
658        },
659        (
660            Type(box TyAlias {
661                defaultness: ld,
662                ident: li,
663                generics: lg,
664                after_where_clause: lw,
665                bounds: lb,
666                ty: lt,
667            }),
668            Type(box TyAlias {
669                defaultness: rd,
670                ident: ri,
671                generics: rg,
672                after_where_clause: rw,
673                bounds: rb,
674                ty: rt,
675            }),
676        ) => {
677            eq_defaultness(*ld, *rd)
678                && eq_id(*li, *ri)
679                && eq_generics(lg, rg)
680                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
681                && over(lb, rb, eq_generic_bound)
682                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
683        },
684        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
685        _ => false,
686    }
687}
688
689pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
690    l.is_placeholder == r.is_placeholder
691        && over(&l.attrs, &r.attrs, eq_attr)
692        && eq_vis(&l.vis, &r.vis)
693        && eq_id(l.ident, r.ident)
694        && eq_variant_data(&l.data, &r.data)
695        && both(l.disr_expr.as_ref(), r.disr_expr.as_ref(), |l, r| {
696            eq_expr(&l.value, &r.value)
697        })
698}
699
700pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
701    use VariantData::*;
702    match (l, r) {
703        (Unit(_), Unit(_)) => true,
704        (Struct { fields: l, .. }, Struct { fields: r, .. }) | (Tuple(l, _), Tuple(r, _)) => {
705            over(l, r, eq_struct_field)
706        },
707        _ => false,
708    }
709}
710
711pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
712    l.is_placeholder == r.is_placeholder
713        && over(&l.attrs, &r.attrs, eq_attr)
714        && eq_vis(&l.vis, &r.vis)
715        && both(l.ident.as_ref(), r.ident.as_ref(), |l, r| eq_id(*l, *r))
716        && eq_ty(&l.ty, &r.ty)
717}
718
719pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
720    eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
721}
722
723fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) -> bool {
724    matches!(
725        (l, r),
726        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
727            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
728            | (
729                Some(CoroutineKind::AsyncGen { .. }),
730                Some(CoroutineKind::AsyncGen { .. })
731            )
732            | (None, None)
733    )
734}
735
736pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
737    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
738        && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
739        && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
740        && eq_ext(&l.ext, &r.ext)
741}
742
743#[expect(clippy::ref_option, reason = "This is the type how it is stored in the AST")]
744pub fn eq_opt_fn_contract(l: &Option<Box<FnContract>>, r: &Option<Box<FnContract>>) -> bool {
745    match (l, r) {
746        (Some(l), Some(r)) => {
747            eq_expr_opt(l.requires.as_deref(), r.requires.as_deref())
748                && eq_expr_opt(l.ensures.as_deref(), r.ensures.as_deref())
749        },
750        (None, None) => true,
751        (Some(_), None) | (None, Some(_)) => false,
752    }
753}
754
755pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
756    over(&l.params, &r.params, eq_generic_param)
757        && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
758            eq_where_predicate(l, r)
759        })
760}
761
762pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
763    use WherePredicateKind::*;
764    over(&l.attrs, &r.attrs, eq_attr)
765        && match (&l.kind, &r.kind) {
766            (BoundPredicate(l), BoundPredicate(r)) => {
767                over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
768                    eq_generic_param(l, r)
769                }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
770                    && over(&l.bounds, &r.bounds, eq_generic_bound)
771            },
772            (RegionPredicate(l), RegionPredicate(r)) => {
773                eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
774            },
775            (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
776            _ => false,
777        }
778}
779
780pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
781    eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
782}
783
784pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
785    eq_expr(&l.value, &r.value)
786}
787
788pub fn eq_const_item_rhs(l: &ConstItemRhs, r: &ConstItemRhs) -> bool {
789    use ConstItemRhs::*;
790    match (l, r) {
791        (TypeConst(l), TypeConst(r)) => eq_anon_const(l, r),
792        (Body(l), Body(r)) => eq_expr(l, r),
793        (TypeConst(..), Body(..)) | (Body(..), TypeConst(..)) => false,
794    }
795}
796
797pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
798    use UseTreeKind::*;
799    match (l, r) {
800        (Glob, Glob) => true,
801        (Simple(l), Simple(r)) => both(l.as_ref(), r.as_ref(), |l, r| eq_id(*l, *r)),
802        (Nested { items: l, .. }, Nested { items: r, .. }) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
803        _ => false,
804    }
805}
806
807pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
808    matches!(
809        (l, r),
810        (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_))
811    )
812}
813
814pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
815    use VisibilityKind::*;
816    match (&l.kind, &r.kind) {
817        (Public, Public) | (Inherited, Inherited) => true,
818        (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
819        _ => false,
820    }
821}
822
823pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
824    eq_fn_ret_ty(&l.output, &r.output)
825        && over(&l.inputs, &r.inputs, |l, r| {
826            l.is_placeholder == r.is_placeholder
827                && eq_pat(&l.pat, &r.pat)
828                && eq_ty(&l.ty, &r.ty)
829                && over(&l.attrs, &r.attrs, eq_attr)
830        })
831}
832
833pub fn eq_closure_binder(l: &ClosureBinder, r: &ClosureBinder) -> bool {
834    match (l, r) {
835        (ClosureBinder::NotPresent, ClosureBinder::NotPresent) => true,
836        (ClosureBinder::For { generic_params: lp, .. }, ClosureBinder::For { generic_params: rp, .. }) => {
837            lp.len() == rp.len() && std::iter::zip(lp.iter(), rp.iter()).all(|(l, r)| eq_generic_param(l, r))
838        },
839        _ => false,
840    }
841}
842
843pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
844    match (l, r) {
845        (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
846        (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
847        _ => false,
848    }
849}
850
851pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
852    use TyKind::*;
853    match (&l.kind, &r.kind) {
854        (Paren(l), _) => eq_ty(l, r),
855        (_, Paren(r)) => eq_ty(l, r),
856        (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err(_), Err(_)) | (CVarArgs, CVarArgs) => {
857            true
858        },
859        (Slice(l), Slice(r)) => eq_ty(l, r),
860        (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
861        (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
862        (Ref(ll, l), Ref(rl, r)) => {
863            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)
864        },
865        (PinnedRef(ll, l), PinnedRef(rl, r)) => {
866            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)
867        },
868        (FnPtr(l), FnPtr(r)) => {
869            l.safety == r.safety
870                && eq_ext(&l.ext, &r.ext)
871                && over(&l.generic_params, &r.generic_params, eq_generic_param)
872                && eq_fn_decl(&l.decl, &r.decl)
873        },
874        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
875        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
876        (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
877        (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
878        (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
879        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
880        _ => false,
881    }
882}
883
884pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
885    use Extern::*;
886    match (l, r) {
887        (None, None) | (Implicit(_), Implicit(_)) => true,
888        (Explicit(l, _), Explicit(r, _)) => eq_str_lit(l, r),
889        _ => false,
890    }
891}
892
893pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
894    l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
895}
896
897pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
898    l.modifiers == r.modifiers
899        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
900        && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
901            eq_generic_param(l, r)
902        })
903}
904
905pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
906    use GenericParamKind::*;
907    l.is_placeholder == r.is_placeholder
908        && eq_id(l.ident, r.ident)
909        && over(&l.bounds, &r.bounds, eq_generic_bound)
910        && match (&l.kind, &r.kind) {
911            (Lifetime, Lifetime) => true,
912            (Type { default: l }, Type { default: r }) => both(l.as_ref(), r.as_ref(), |l, r| eq_ty(l, r)),
913            (
914                Const {
915                    ty: lt,
916                    default: ld,
917                    span: _,
918                },
919                Const {
920                    ty: rt,
921                    default: rd,
922                    span: _,
923                },
924            ) => eq_ty(lt, rt) && both(ld.as_ref(), rd.as_ref(), eq_anon_const),
925            _ => false,
926        }
927        && over(&l.attrs, &r.attrs, eq_attr)
928}
929
930pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
931    use GenericBound::*;
932    match (l, r) {
933        (Trait(ptr1), Trait(ptr2)) => eq_poly_ref_trait(ptr1, ptr2),
934        (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
935        _ => false,
936    }
937}
938
939pub fn eq_precise_capture(l: &PreciseCapturingArg, r: &PreciseCapturingArg) -> bool {
940    match (l, r) {
941        (PreciseCapturingArg::Lifetime(l), PreciseCapturingArg::Lifetime(r)) => l.ident == r.ident,
942        (PreciseCapturingArg::Arg(l, _), PreciseCapturingArg::Arg(r, _)) => l.segments[0].ident == r.segments[0].ident,
943        _ => false,
944    }
945}
946
947fn eq_term(l: &Term, r: &Term) -> bool {
948    match (l, r) {
949        (Term::Ty(l), Term::Ty(r)) => eq_ty(l, r),
950        (Term::Const(l), Term::Const(r)) => eq_anon_const(l, r),
951        _ => false,
952    }
953}
954
955pub fn eq_assoc_item_constraint(l: &AssocItemConstraint, r: &AssocItemConstraint) -> bool {
956    use AssocItemConstraintKind::*;
957    eq_id(l.ident, r.ident)
958        && match (&l.kind, &r.kind) {
959            (Equality { term: l }, Equality { term: r }) => eq_term(l, r),
960            (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
961            _ => false,
962        }
963}
964
965pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
966    eq_path(&l.path, &r.path) && eq_delim_args(&l.args, &r.args)
967}
968
969pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
970    use AttrKind::*;
971    l.style == r.style
972        && match (&l.kind, &r.kind) {
973            (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
974            (Normal(l), Normal(r)) => eq_path(&l.item.path, &r.item.path) && eq_attr_args(&l.item.args, &r.item.args),
975            _ => false,
976        }
977}
978
979pub fn eq_attr_args(l: &AttrArgs, r: &AttrArgs) -> bool {
980    use AttrArgs::*;
981    match (l, r) {
982        (Empty, Empty) => true,
983        (Delimited(la), Delimited(ra)) => eq_delim_args(la, ra),
984        (Eq { eq_span: _, expr: le }, Eq { eq_span: _, expr: re }) => eq_expr(le, re),
985        _ => false,
986    }
987}
988
989pub fn eq_delim_args(l: &DelimArgs, r: &DelimArgs) -> bool {
990    l.delim == r.delim
991        && l.tokens.len() == r.tokens.len()
992        && l.tokens.iter().zip(r.tokens.iter()).all(|(a, b)| a.eq_unspanned(b))
993}