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                define_opaque: _,
340            }),
341            Static(box StaticItem {
342                ty: rt,
343                mutability: rm,
344                expr: re,
345                safety: rs,
346                define_opaque: _,
347            }),
348        ) => lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref()),
349        (
350            Const(box ConstItem {
351                defaultness: ld,
352                generics: lg,
353                ty: lt,
354                expr: le,
355                define_opaque: _,
356            }),
357            Const(box ConstItem {
358                defaultness: rd,
359                generics: rg,
360                ty: rt,
361                expr: re,
362                define_opaque: _,
363            }),
364        ) => eq_defaultness(*ld, *rd) && eq_generics(lg, rg) && eq_ty(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref()),
365        (
366            Fn(box ast::Fn {
367                defaultness: ld,
368                sig: lf,
369                generics: lg,
370                contract: lc,
371                body: lb,
372                define_opaque: _,
373            }),
374            Fn(box ast::Fn {
375                defaultness: rd,
376                sig: rf,
377                generics: rg,
378                contract: rc,
379                body: rb,
380                define_opaque: _,
381            }),
382        ) => {
383            eq_defaultness(*ld, *rd)
384                && eq_fn_sig(lf, rf)
385                && eq_generics(lg, rg)
386                && eq_opt_fn_contract(lc, rc)
387                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
388        },
389        (Mod(lu, lmk), Mod(ru, rmk)) => {
390            lu == ru
391                && match (lmk, rmk) {
392                    (ModKind::Loaded(litems, linline, _, _), ModKind::Loaded(ritems, rinline, _, _)) => {
393                        linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
394                    },
395                    (ModKind::Unloaded, ModKind::Unloaded) => true,
396                    _ => false,
397                }
398        },
399        (ForeignMod(l), ForeignMod(r)) => {
400            both(l.abi.as_ref(), r.abi.as_ref(), eq_str_lit)
401                && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
402        },
403        (
404            TyAlias(box ast::TyAlias {
405                defaultness: ld,
406                generics: lg,
407                bounds: lb,
408                ty: lt,
409                ..
410            }),
411            TyAlias(box ast::TyAlias {
412                defaultness: rd,
413                generics: rg,
414                bounds: rb,
415                ty: rt,
416                ..
417            }),
418        ) => {
419            eq_defaultness(*ld, *rd)
420                && eq_generics(lg, rg)
421                && over(lb, rb, eq_generic_bound)
422                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
423        },
424        (Enum(le, lg), Enum(re, rg)) => over(&le.variants, &re.variants, eq_variant) && eq_generics(lg, rg),
425        (Struct(lv, lg), Struct(rv, rg)) | (Union(lv, lg), Union(rv, rg)) => {
426            eq_variant_data(lv, rv) && eq_generics(lg, rg)
427        },
428        (
429            Trait(box ast::Trait {
430                is_auto: la,
431                safety: lu,
432                generics: lg,
433                bounds: lb,
434                items: li,
435            }),
436            Trait(box ast::Trait {
437                is_auto: ra,
438                safety: ru,
439                generics: rg,
440                bounds: rb,
441                items: ri,
442            }),
443        ) => {
444            la == ra
445                && matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
446                && eq_generics(lg, rg)
447                && over(lb, rb, eq_generic_bound)
448                && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
449        },
450        (TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, eq_generic_bound),
451        (
452            Impl(box ast::Impl {
453                safety: lu,
454                polarity: lp,
455                defaultness: ld,
456                constness: lc,
457                generics: lg,
458                of_trait: lot,
459                self_ty: lst,
460                items: li,
461            }),
462            Impl(box ast::Impl {
463                safety: ru,
464                polarity: rp,
465                defaultness: rd,
466                constness: rc,
467                generics: rg,
468                of_trait: rot,
469                self_ty: rst,
470                items: ri,
471            }),
472        ) => {
473            matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
474                && matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive)
475                && eq_defaultness(*ld, *rd)
476                && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
477                && eq_generics(lg, rg)
478                && both(lot.as_ref(), rot.as_ref(), |l, r| eq_path(&l.path, &r.path))
479                && eq_ty(lst, rst)
480                && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
481        },
482        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
483        (MacroDef(l), MacroDef(r)) => l.macro_rules == r.macro_rules && eq_delim_args(&l.body, &r.body),
484        _ => false,
485    }
486}
487
488pub fn eq_foreign_item_kind(l: &ForeignItemKind, r: &ForeignItemKind) -> bool {
489    use ForeignItemKind::*;
490    match (l, r) {
491        (
492            Static(box StaticItem {
493                ty: lt,
494                mutability: lm,
495                expr: le,
496                safety: ls,
497                define_opaque: _,
498            }),
499            Static(box StaticItem {
500                ty: rt,
501                mutability: rm,
502                expr: re,
503                safety: rs,
504                define_opaque: _,
505            }),
506        ) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref()) && ls == rs,
507        (
508            Fn(box ast::Fn {
509                defaultness: ld,
510                sig: lf,
511                generics: lg,
512                contract: lc,
513                body: lb,
514                define_opaque: _,
515            }),
516            Fn(box ast::Fn {
517                defaultness: rd,
518                sig: rf,
519                generics: rg,
520                contract: rc,
521                body: rb,
522                define_opaque: _,
523            }),
524        ) => {
525            eq_defaultness(*ld, *rd)
526                && eq_fn_sig(lf, rf)
527                && eq_generics(lg, rg)
528                && eq_opt_fn_contract(lc, rc)
529                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
530        },
531        (
532            TyAlias(box ast::TyAlias {
533                defaultness: ld,
534                generics: lg,
535                bounds: lb,
536                ty: lt,
537                ..
538            }),
539            TyAlias(box ast::TyAlias {
540                defaultness: rd,
541                generics: rg,
542                bounds: rb,
543                ty: rt,
544                ..
545            }),
546        ) => {
547            eq_defaultness(*ld, *rd)
548                && eq_generics(lg, rg)
549                && over(lb, rb, eq_generic_bound)
550                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
551        },
552        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
553        _ => false,
554    }
555}
556
557pub fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
558    use AssocItemKind::*;
559    match (l, r) {
560        (
561            Const(box ConstItem {
562                defaultness: ld,
563                generics: lg,
564                ty: lt,
565                expr: le,
566                define_opaque: _,
567            }),
568            Const(box ConstItem {
569                defaultness: rd,
570                generics: rg,
571                ty: rt,
572                expr: re,
573                define_opaque: _,
574            }),
575        ) => eq_defaultness(*ld, *rd) && eq_generics(lg, rg) && eq_ty(lt, rt) && eq_expr_opt(le.as_ref(), re.as_ref()),
576        (
577            Fn(box ast::Fn {
578                defaultness: ld,
579                sig: lf,
580                generics: lg,
581                contract: lc,
582                body: lb,
583                define_opaque: _,
584            }),
585            Fn(box ast::Fn {
586                defaultness: rd,
587                sig: rf,
588                generics: rg,
589                contract: rc,
590                body: rb,
591                define_opaque: _,
592            }),
593        ) => {
594            eq_defaultness(*ld, *rd)
595                && eq_fn_sig(lf, rf)
596                && eq_generics(lg, rg)
597                && eq_opt_fn_contract(lc, rc)
598                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
599        },
600        (
601            Type(box TyAlias {
602                defaultness: ld,
603                generics: lg,
604                bounds: lb,
605                ty: lt,
606                ..
607            }),
608            Type(box TyAlias {
609                defaultness: rd,
610                generics: rg,
611                bounds: rb,
612                ty: rt,
613                ..
614            }),
615        ) => {
616            eq_defaultness(*ld, *rd)
617                && eq_generics(lg, rg)
618                && over(lb, rb, eq_generic_bound)
619                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
620        },
621        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
622        _ => false,
623    }
624}
625
626pub fn eq_variant(l: &Variant, r: &Variant) -> bool {
627    l.is_placeholder == r.is_placeholder
628        && over(&l.attrs, &r.attrs, eq_attr)
629        && eq_vis(&l.vis, &r.vis)
630        && eq_id(l.ident, r.ident)
631        && eq_variant_data(&l.data, &r.data)
632        && both(l.disr_expr.as_ref(), r.disr_expr.as_ref(), |l, r| {
633            eq_expr(&l.value, &r.value)
634        })
635}
636
637pub fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
638    use VariantData::*;
639    match (l, r) {
640        (Unit(_), Unit(_)) => true,
641        (Struct { fields: l, .. }, Struct { fields: r, .. }) | (Tuple(l, _), Tuple(r, _)) => {
642            over(l, r, eq_struct_field)
643        },
644        _ => false,
645    }
646}
647
648pub fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
649    l.is_placeholder == r.is_placeholder
650        && over(&l.attrs, &r.attrs, eq_attr)
651        && eq_vis(&l.vis, &r.vis)
652        && both(l.ident.as_ref(), r.ident.as_ref(), |l, r| eq_id(*l, *r))
653        && eq_ty(&l.ty, &r.ty)
654}
655
656pub fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
657    eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
658}
659
660fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) -> bool {
661    matches!(
662        (l, r),
663        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
664            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
665            | (
666                Some(CoroutineKind::AsyncGen { .. }),
667                Some(CoroutineKind::AsyncGen { .. })
668            )
669            | (None, None)
670    )
671}
672
673pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
674    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
675        && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
676        && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
677        && eq_ext(&l.ext, &r.ext)
678}
679
680#[expect(clippy::ref_option, reason = "This is the type how it is stored in the AST")]
681pub fn eq_opt_fn_contract(l: &Option<P<FnContract>>, r: &Option<P<FnContract>>) -> bool {
682    match (l, r) {
683        (Some(l), Some(r)) => {
684            eq_expr_opt(l.requires.as_ref(), r.requires.as_ref()) && eq_expr_opt(l.ensures.as_ref(), r.ensures.as_ref())
685        },
686        (None, None) => true,
687        (Some(_), None) | (None, Some(_)) => false,
688    }
689}
690
691pub fn eq_generics(l: &Generics, r: &Generics) -> bool {
692    over(&l.params, &r.params, eq_generic_param)
693        && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
694            eq_where_predicate(l, r)
695        })
696}
697
698pub fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
699    use WherePredicateKind::*;
700    over(&l.attrs, &r.attrs, eq_attr)
701        && match (&l.kind, &r.kind) {
702            (BoundPredicate(l), BoundPredicate(r)) => {
703                over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
704                    eq_generic_param(l, r)
705                }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
706                    && over(&l.bounds, &r.bounds, eq_generic_bound)
707            },
708            (RegionPredicate(l), RegionPredicate(r)) => {
709                eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
710            },
711            (EqPredicate(l), EqPredicate(r)) => eq_ty(&l.lhs_ty, &r.lhs_ty) && eq_ty(&l.rhs_ty, &r.rhs_ty),
712            _ => false,
713        }
714}
715
716pub fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
717    eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
718}
719
720pub fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
721    eq_expr(&l.value, &r.value)
722}
723
724pub fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
725    use UseTreeKind::*;
726    match (l, r) {
727        (Glob, Glob) => true,
728        (Simple(l), Simple(r)) => both(l.as_ref(), r.as_ref(), |l, r| eq_id(*l, *r)),
729        (Nested { items: l, .. }, Nested { items: r, .. }) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
730        _ => false,
731    }
732}
733
734pub fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
735    matches!(
736        (l, r),
737        (Defaultness::Final, Defaultness::Final) | (Defaultness::Default(_), Defaultness::Default(_))
738    )
739}
740
741pub fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
742    use VisibilityKind::*;
743    match (&l.kind, &r.kind) {
744        (Public, Public) | (Inherited, Inherited) => true,
745        (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
746        _ => false,
747    }
748}
749
750pub fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
751    eq_fn_ret_ty(&l.output, &r.output)
752        && over(&l.inputs, &r.inputs, |l, r| {
753            l.is_placeholder == r.is_placeholder
754                && eq_pat(&l.pat, &r.pat)
755                && eq_ty(&l.ty, &r.ty)
756                && over(&l.attrs, &r.attrs, eq_attr)
757        })
758}
759
760pub fn eq_closure_binder(l: &ClosureBinder, r: &ClosureBinder) -> bool {
761    match (l, r) {
762        (ClosureBinder::NotPresent, ClosureBinder::NotPresent) => true,
763        (ClosureBinder::For { generic_params: lp, .. }, ClosureBinder::For { generic_params: rp, .. }) => {
764            lp.len() == rp.len() && std::iter::zip(lp.iter(), rp.iter()).all(|(l, r)| eq_generic_param(l, r))
765        },
766        _ => false,
767    }
768}
769
770pub fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
771    match (l, r) {
772        (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
773        (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
774        _ => false,
775    }
776}
777
778pub fn eq_ty(l: &Ty, r: &Ty) -> bool {
779    use TyKind::*;
780    match (&l.kind, &r.kind) {
781        (Paren(l), _) => eq_ty(l, r),
782        (_, Paren(r)) => eq_ty(l, r),
783        (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err(_), Err(_)) | (CVarArgs, CVarArgs) => {
784            true
785        },
786        (Slice(l), Slice(r)) => eq_ty(l, r),
787        (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
788        (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
789        (Ref(ll, l), Ref(rl, r)) => {
790            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)
791        },
792        (PinnedRef(ll, l), PinnedRef(rl, r)) => {
793            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)
794        },
795        (BareFn(l), BareFn(r)) => {
796            l.safety == r.safety
797                && eq_ext(&l.ext, &r.ext)
798                && over(&l.generic_params, &r.generic_params, eq_generic_param)
799                && eq_fn_decl(&l.decl, &r.decl)
800        },
801        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
802        (Path(lq, lp), Path(rq, rp)) => both(lq.as_ref(), rq.as_ref(), eq_qself) && eq_path(lp, rp),
803        (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
804        (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
805        (Typeof(l), Typeof(r)) => eq_expr(&l.value, &r.value),
806        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
807        _ => false,
808    }
809}
810
811pub fn eq_ext(l: &Extern, r: &Extern) -> bool {
812    use Extern::*;
813    match (l, r) {
814        (None, None) | (Implicit(_), Implicit(_)) => true,
815        (Explicit(l, _), Explicit(r, _)) => eq_str_lit(l, r),
816        _ => false,
817    }
818}
819
820pub fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
821    l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
822}
823
824pub fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
825    l.modifiers == r.modifiers
826        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
827        && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
828            eq_generic_param(l, r)
829        })
830}
831
832pub fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
833    use GenericParamKind::*;
834    l.is_placeholder == r.is_placeholder
835        && eq_id(l.ident, r.ident)
836        && over(&l.bounds, &r.bounds, eq_generic_bound)
837        && match (&l.kind, &r.kind) {
838            (Lifetime, Lifetime) => true,
839            (Type { default: l }, Type { default: r }) => both(l.as_ref(), r.as_ref(), |l, r| eq_ty(l, r)),
840            (
841                Const {
842                    ty: lt,
843                    kw_span: _,
844                    default: ld,
845                },
846                Const {
847                    ty: rt,
848                    kw_span: _,
849                    default: rd,
850                },
851            ) => eq_ty(lt, rt) && both(ld.as_ref(), rd.as_ref(), eq_anon_const),
852            _ => false,
853        }
854        && over(&l.attrs, &r.attrs, eq_attr)
855}
856
857pub fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
858    use GenericBound::*;
859    match (l, r) {
860        (Trait(ptr1), Trait(ptr2)) => eq_poly_ref_trait(ptr1, ptr2),
861        (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
862        _ => false,
863    }
864}
865
866pub fn eq_precise_capture(l: &PreciseCapturingArg, r: &PreciseCapturingArg) -> bool {
867    match (l, r) {
868        (PreciseCapturingArg::Lifetime(l), PreciseCapturingArg::Lifetime(r)) => l.ident == r.ident,
869        (PreciseCapturingArg::Arg(l, _), PreciseCapturingArg::Arg(r, _)) => l.segments[0].ident == r.segments[0].ident,
870        _ => false,
871    }
872}
873
874fn eq_term(l: &Term, r: &Term) -> bool {
875    match (l, r) {
876        (Term::Ty(l), Term::Ty(r)) => eq_ty(l, r),
877        (Term::Const(l), Term::Const(r)) => eq_anon_const(l, r),
878        _ => false,
879    }
880}
881
882pub fn eq_assoc_item_constraint(l: &AssocItemConstraint, r: &AssocItemConstraint) -> bool {
883    use AssocItemConstraintKind::*;
884    eq_id(l.ident, r.ident)
885        && match (&l.kind, &r.kind) {
886            (Equality { term: l }, Equality { term: r }) => eq_term(l, r),
887            (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
888            _ => false,
889        }
890}
891
892pub fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
893    eq_path(&l.path, &r.path) && eq_delim_args(&l.args, &r.args)
894}
895
896pub fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
897    use AttrKind::*;
898    l.style == r.style
899        && match (&l.kind, &r.kind) {
900            (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
901            (Normal(l), Normal(r)) => eq_path(&l.item.path, &r.item.path) && eq_attr_args(&l.item.args, &r.item.args),
902            _ => false,
903        }
904}
905
906pub fn eq_attr_args(l: &AttrArgs, r: &AttrArgs) -> bool {
907    use AttrArgs::*;
908    match (l, r) {
909        (Empty, Empty) => true,
910        (Delimited(la), Delimited(ra)) => eq_delim_args(la, ra),
911        (Eq { eq_span: _, expr: le }, Eq { eq_span: _, expr: re }) => eq_expr(le, re),
912        _ => false,
913    }
914}
915
916pub fn eq_delim_args(l: &DelimArgs, r: &DelimArgs) -> bool {
917    l.delim == r.delim && l.tokens.eq_unspanned(&r.tokens)
918}