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