Skip to main content

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::attr::data_structures::CfgEntry;
9use rustc_ast::{self as ast, HasAttrs, *};
10use rustc_span::sym;
11use rustc_span::symbol::Ident;
12use std::mem;
13
14pub mod ident_iter;
15pub use ident_iter::IdentIter;
16
17pub fn is_useless_with_eq_exprs(kind: BinOpKind) -> bool {
18    use BinOpKind::*;
19    matches!(
20        kind,
21        Sub | Div | Eq | Lt | Le | Gt | Ge | Ne | And | Or | BitXor | BitAnd | BitOr
22    )
23}
24
25/// Checks if each element in the first slice is contained within the latter as per `eq_fn`.
26pub fn unordered_over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
27    left.len() == right.len() && left.iter().all(|l| right.iter().any(|r| eq_fn(l, r)))
28}
29
30pub fn eq_id(l: Ident, r: Ident) -> bool {
31    l.name == r.name
32}
33
34pub fn eq_pat(l: &Pat, r: &Pat) -> bool {
35    use PatKind::*;
36    match (&l.kind, &r.kind) {
37        (Missing, _) | (_, Missing) => unreachable!(),
38        (Paren(l), _) => eq_pat(l, r),
39        (_, Paren(r)) => eq_pat(l, r),
40        (Wild, Wild) | (Rest, Rest) => true,
41        (Expr(l), Expr(r)) => eq_expr(l, r),
42        (Ident(b1, i1, s1), Ident(b2, i2, s2)) => {
43            b1 == b2 && eq_id(*i1, *i2) && both(s1.as_deref(), s2.as_deref(), eq_pat)
44        },
45        (Range(lf, lt, le), Range(rf, rt, re)) => {
46            eq_expr_opt(lf.as_deref(), rf.as_deref())
47                && eq_expr_opt(lt.as_deref(), rt.as_deref())
48                && eq_range_end(le.node, re.node)
49        },
50        (Box(l), Box(r)) => eq_pat(l, r),
51        (Ref(l, l_pin, l_mut), Ref(r, r_pin, r_mut)) => l_pin == r_pin && l_mut == r_mut && eq_pat(l, r),
52        (Tuple(l), Tuple(r)) | (Slice(l), Slice(r)) => over(l, r, eq_pat),
53        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
54        (TupleStruct(lqself, lp, lfs), TupleStruct(rqself, rp, rfs)) => {
55            eq_maybe_qself(lqself.as_deref(), rqself.as_deref()) && eq_path(lp, rp) && over(lfs, rfs, eq_pat)
56        },
57        (Struct(lqself, lp, lfs, lr), Struct(rqself, rp, rfs, rr)) => {
58            lr == rr
59                && eq_maybe_qself(lqself.as_deref(), rqself.as_deref())
60                && eq_path(lp, rp)
61                && unordered_over(lfs, rfs, eq_field_pat)
62        },
63        (Or(ls), Or(rs)) => unordered_over(ls, rs, eq_pat),
64        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
65        _ => false,
66    }
67}
68
69fn eq_range_end(l: RangeEnd, r: RangeEnd) -> bool {
70    match (l, r) {
71        (RangeEnd::Excluded, RangeEnd::Excluded) => true,
72        (RangeEnd::Included(l), RangeEnd::Included(r)) => {
73            matches!(l, RangeSyntax::DotDotEq) == matches!(r, RangeSyntax::DotDotEq)
74        },
75        _ => false,
76    }
77}
78
79pub fn eq_field_pat(l: &PatField, r: &PatField) -> bool {
80    l.is_placeholder == r.is_placeholder
81        && eq_id(l.ident, r.ident)
82        && eq_pat(&l.pat, &r.pat)
83        && over(&l.attrs, &r.attrs, eq_attr)
84}
85
86fn eq_qself(l: &QSelf, r: &QSelf) -> bool {
87    l.position == r.position && eq_ty(&l.ty, &r.ty)
88}
89
90pub fn eq_maybe_qself(l: Option<&QSelf>, r: Option<&QSelf>) -> bool {
91    match (l, r) {
92        (Some(l), Some(r)) => eq_qself(l, r),
93        (None, None) => true,
94        _ => false,
95    }
96}
97
98pub fn eq_path(l: &Path, r: &Path) -> bool {
99    over(&l.segments, &r.segments, eq_path_seg)
100}
101
102fn eq_path_seg(l: &PathSegment, r: &PathSegment) -> bool {
103    eq_id(l.ident, r.ident) && both(l.args.as_ref(), r.args.as_ref(), |l, r| eq_generic_args(l, r))
104}
105
106fn eq_generic_args(l: &GenericArgs, r: &GenericArgs) -> bool {
107    match (l, r) {
108        (AngleBracketed(l), AngleBracketed(r)) => over(&l.args, &r.args, eq_angle_arg),
109        (Parenthesized(l), Parenthesized(r)) => {
110            over(&l.inputs, &r.inputs, |l, r| eq_ty(l, r)) && eq_fn_ret_ty(&l.output, &r.output)
111        },
112        _ => false,
113    }
114}
115
116fn eq_angle_arg(l: &AngleBracketedArg, r: &AngleBracketedArg) -> bool {
117    match (l, r) {
118        (AngleBracketedArg::Arg(l), AngleBracketedArg::Arg(r)) => eq_generic_arg(l, r),
119        (AngleBracketedArg::Constraint(l), AngleBracketedArg::Constraint(r)) => eq_assoc_item_constraint(l, r),
120        _ => false,
121    }
122}
123
124fn eq_generic_arg(l: &GenericArg, r: &GenericArg) -> bool {
125    match (l, r) {
126        (GenericArg::Lifetime(l), GenericArg::Lifetime(r)) => eq_id(l.ident, r.ident),
127        (GenericArg::Type(l), GenericArg::Type(r)) => eq_ty(l, r),
128        (GenericArg::Const(l), GenericArg::Const(r)) => eq_expr(&l.value, &r.value),
129        _ => false,
130    }
131}
132
133fn eq_expr_opt(l: Option<&Expr>, r: Option<&Expr>) -> bool {
134    both(l, r, eq_expr)
135}
136
137fn eq_struct_rest(l: &StructRest, r: &StructRest) -> bool {
138    match (l, r) {
139        (StructRest::Base(lb), StructRest::Base(rb)) => eq_expr(lb, rb),
140        (StructRest::Rest(_), StructRest::Rest(_)) | (StructRest::None, StructRest::None) => true,
141        _ => false,
142    }
143}
144
145#[expect(clippy::too_many_lines, reason = "big match statement")]
146fn eq_expr(l: &Expr, r: &Expr) -> bool {
147    use ExprKind::*;
148    if !over(&l.attrs, &r.attrs, eq_attr) {
149        return false;
150    }
151    match (&l.kind, &r.kind) {
152        (Paren(l), _) => eq_expr(l, r),
153        (_, Paren(r)) => eq_expr(l, r),
154        (Err(_), Err(_)) => true,
155        (Dummy, _) | (_, Dummy) => unreachable!("comparing `ExprKind::Dummy`"),
156        (Try(l), Try(r)) | (Await(l, _), Await(r, _)) => eq_expr(l, r),
157        (Array(l), Array(r)) => over(l, r, |l, r| eq_expr(l, r)),
158        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)),
159        (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value),
160        (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)),
161        (
162            MethodCall(box ast::MethodCall {
163                seg: ls,
164                receiver: lr,
165                args: la,
166                ..
167            }),
168            MethodCall(box ast::MethodCall {
169                seg: rs,
170                receiver: rr,
171                args: ra,
172                ..
173            }),
174        ) => eq_path_seg(ls, rs) && eq_expr(lr, rr) && over(la, ra, |l, r| eq_expr(l, r)),
175        (Binary(lo, ll, lr), Binary(ro, rl, rr)) => lo.node == ro.node && eq_expr(ll, rl) && eq_expr(lr, rr),
176        (Unary(lo, l), Unary(ro, r)) => mem::discriminant(lo) == mem::discriminant(ro) && eq_expr(l, r),
177        (Lit(l), Lit(r)) => l == r,
178        (Cast(l, lt), Cast(r, rt)) | (Type(l, lt), Type(r, rt)) => eq_expr(l, r) && eq_ty(lt, rt),
179        (Let(lp, le, _, _), Let(rp, re, _, _)) => eq_pat(lp, rp) && eq_expr(le, re),
180        (If(lc, lt, le), If(rc, rt, re)) => {
181            eq_expr(lc, rc) && eq_block(lt, rt) && eq_expr_opt(le.as_deref(), re.as_deref())
182        },
183        (While(lc, lt, ll), While(rc, rt, rl)) => {
184            eq_label(ll.as_ref(), rl.as_ref()) && eq_expr(lc, rc) && eq_block(lt, rt)
185        },
186        (ForLoop(lf), ForLoop(rf)) => {
187            eq_label(lf.label.as_ref(), rf.label.as_ref())
188                && eq_pat(&lf.pat, &rf.pat)
189                && eq_expr(&lf.iter, &rf.iter)
190                && eq_block(&lf.body, &rf.body)
191                && lf.kind == rf.kind
192        }
193        (Loop(lt, ll, _), Loop(rt, rl, _)) => eq_label(ll.as_ref(), rl.as_ref()) && eq_block(lt, rt),
194        (Block(lb, ll), Block(rb, rl)) => eq_label(ll.as_ref(), rl.as_ref()) && eq_block(lb, rb),
195        (TryBlock(lb, lt), TryBlock(rb, rt)) => eq_block(lb, rb) && both(lt.as_deref(), rt.as_deref(), eq_ty),
196        (Yield(l), Yield(r)) => eq_expr_opt(l.expr().map(Box::as_ref), r.expr().map(Box::as_ref)) && l.same_kind(r),
197        (Ret(l), Ret(r)) => eq_expr_opt(l.as_deref(), r.as_deref()),
198        (Break(ll, le), Break(rl, re)) => {
199            eq_label(ll.as_ref(), rl.as_ref()) && eq_expr_opt(le.as_deref(), re.as_deref())
200        },
201        (Continue(ll), Continue(rl)) => eq_label(ll.as_ref(), rl.as_ref()),
202        (Assign(l1, l2, _), Assign(r1, r2, _)) | (Index(l1, l2, _), Index(r1, r2, _)) => {
203            eq_expr(l1, r1) && eq_expr(l2, r2)
204        },
205        (AssignOp(lo, lp, lv), AssignOp(ro, rp, rv)) => lo.node == ro.node && eq_expr(lp, rp) && eq_expr(lv, rv),
206        (Field(lp, lf), Field(rp, rf)) => eq_id(*lf, *rf) && eq_expr(lp, rp),
207        (Match(ls, la, lkind), Match(rs, ra, rkind)) => (lkind == rkind) && eq_expr(ls, rs) && over(la, ra, eq_arm),
208        (
209            Closure(box ast::Closure {
210                binder: lb,
211                capture_clause: lc,
212                coroutine_kind: la,
213                movability: lm,
214                fn_decl: lf,
215                body: le,
216                ..
217            }),
218            Closure(box ast::Closure {
219                binder: rb,
220                capture_clause: rc,
221                coroutine_kind: ra,
222                movability: rm,
223                fn_decl: rf,
224                body: re,
225                ..
226            }),
227        ) => {
228            eq_closure_binder(lb, rb)
229                && lc == rc
230                && eq_coroutine_kind(*la, *ra)
231                && lm == rm
232                && eq_fn_decl(lf, rf)
233                && eq_expr(le, re)
234        },
235        (Gen(lc, lb, lk, _), Gen(rc, rb, rk, _)) => lc == rc && eq_block(lb, rb) && lk == rk,
236        (Range(lf, lt, ll), Range(rf, rt, rl)) => {
237            ll == rl && eq_expr_opt(lf.as_deref(), rf.as_deref()) && eq_expr_opt(lt.as_deref(), rt.as_deref())
238        },
239        (AddrOf(lbk, lm, le), AddrOf(rbk, rm, re)) => lbk == rbk && lm == rm && eq_expr(le, re),
240        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
241        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
242        (Struct(lse), Struct(rse)) => {
243            eq_maybe_qself(lse.qself.as_deref(), rse.qself.as_deref())
244                && eq_path(&lse.path, &rse.path)
245                && eq_struct_rest(&lse.rest, &rse.rest)
246                && unordered_over(&lse.fields, &rse.fields, eq_field)
247        },
248        _ => false,
249    }
250}
251
252fn eq_coroutine_kind(a: Option<CoroutineKind>, b: Option<CoroutineKind>) -> bool {
253    matches!(
254        (a, b),
255        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
256            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
257            | (
258                Some(CoroutineKind::AsyncGen { .. }),
259                Some(CoroutineKind::AsyncGen { .. })
260            )
261            | (None, None)
262    )
263}
264
265fn eq_field(l: &ExprField, r: &ExprField) -> bool {
266    l.is_placeholder == r.is_placeholder
267        && eq_id(l.ident, r.ident)
268        && eq_expr(&l.expr, &r.expr)
269        && over(&l.attrs, &r.attrs, eq_attr)
270}
271
272fn eq_arm(l: &Arm, r: &Arm) -> bool {
273    l.is_placeholder == r.is_placeholder
274        && eq_pat(&l.pat, &r.pat)
275        && eq_expr_opt(l.body.as_deref(), r.body.as_deref())
276        && eq_expr_opt(l.guard.as_deref().map(|g| &g.cond), r.guard.as_deref().map(|g| &g.cond))
277        && over(&l.attrs, &r.attrs, eq_attr)
278}
279
280fn eq_label(l: Option<&Label>, r: Option<&Label>) -> bool {
281    both(l, r, |l, r| eq_id(l.ident, r.ident))
282}
283
284fn eq_block(l: &Block, r: &Block) -> bool {
285    l.rules == r.rules && over(&l.stmts, &r.stmts, eq_stmt)
286}
287
288fn eq_stmt(l: &Stmt, r: &Stmt) -> bool {
289    use StmtKind::*;
290    match (&l.kind, &r.kind) {
291        (Let(l), Let(r)) => {
292            eq_pat(&l.pat, &r.pat)
293                && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| eq_ty(l, r))
294                && eq_local_kind(&l.kind, &r.kind)
295                && over(&l.attrs, &r.attrs, eq_attr)
296        },
297        (Item(l), Item(r)) => eq_item(l, r, eq_item_kind),
298        (Expr(l), Expr(r)) | (Semi(l), Semi(r)) => eq_expr(l, r),
299        (Empty, Empty) => true,
300        (MacCall(l), MacCall(r)) => {
301            l.style == r.style && eq_mac_call(&l.mac, &r.mac) && over(&l.attrs, &r.attrs, eq_attr)
302        },
303        _ => false,
304    }
305}
306
307fn eq_local_kind(l: &LocalKind, r: &LocalKind) -> bool {
308    use LocalKind::*;
309    match (l, r) {
310        (Decl, Decl) => true,
311        (Init(l), Init(r)) => eq_expr(l, r),
312        (InitElse(li, le), InitElse(ri, re)) => eq_expr(li, ri) && eq_block(le, re),
313        _ => false,
314    }
315}
316
317fn eq_item<K>(l: &Item<K>, r: &Item<K>, mut eq_kind: impl FnMut(&K, &K) -> bool) -> bool {
318    over(&l.attrs, &r.attrs, eq_attr) && eq_vis(&l.vis, &r.vis) && eq_kind(&l.kind, &r.kind)
319}
320
321#[expect(clippy::too_many_lines, reason = "big match statement")]
322fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
323    use ItemKind::*;
324    match (l, r) {
325        (ExternCrate(ls, li), ExternCrate(rs, ri)) => ls == rs && eq_id(*li, *ri),
326        (Use(l), Use(r)) => eq_use_tree(l, r),
327        (
328            Static(box StaticItem {
329                ident: li,
330                ty: lt,
331                mutability: lm,
332                expr: le,
333                safety: ls,
334                define_opaque: _,
335                eii_impls: _,
336            }),
337            Static(box StaticItem {
338                ident: ri,
339                ty: rt,
340                mutability: rm,
341                expr: re,
342                safety: rs,
343                define_opaque: _,
344                eii_impls: _,
345            }),
346        ) => eq_id(*li, *ri) && lm == rm && ls == rs && eq_ty(lt, rt) && eq_expr_opt(le.as_deref(), re.as_deref()),
347        (
348            Const(box ConstItem {
349                defaultness: ld,
350                ident: li,
351                generics: lg,
352                ty: lt,
353                rhs_kind: lb,
354                define_opaque: _,
355            }),
356            Const(box ConstItem {
357                defaultness: rd,
358                ident: ri,
359                generics: rg,
360                ty: rt,
361                rhs_kind: rb,
362                define_opaque: _,
363            }),
364        ) => {
365            eq_defaultness(*ld, *rd)
366                && eq_id(*li, *ri)
367                && eq_generics(lg, rg)
368                && eq_ty(lt, rt)
369                && both(Some(lb), Some(rb), eq_const_item_rhs)
370        },
371        (
372            Fn(box ast::Fn {
373                defaultness: ld,
374                sig: lf,
375                ident: li,
376                generics: lg,
377                contract: lc,
378                body: lb,
379                define_opaque: _,
380                eii_impls: _,
381            }),
382            Fn(box ast::Fn {
383                defaultness: rd,
384                sig: rf,
385                ident: ri,
386                generics: rg,
387                contract: rc,
388                body: rb,
389                define_opaque: _,
390                eii_impls: _,
391            }),
392        ) => {
393            eq_defaultness(*ld, *rd)
394                && eq_fn_sig(lf, rf)
395                && eq_id(*li, *ri)
396                && eq_generics(lg, rg)
397                && eq_opt_fn_contract(lc, rc)
398                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
399        },
400        (Mod(ls, li, lmk), Mod(rs, ri, rmk)) => {
401            ls == rs
402                && eq_id(*li, *ri)
403                && match (lmk, rmk) {
404                    (ModKind::Loaded(litems, linline, _), ModKind::Loaded(ritems, rinline, _)) => {
405                        linline == rinline && over(litems, ritems, |l, r| eq_item(l, r, eq_item_kind))
406                    },
407                    (ModKind::Unloaded, ModKind::Unloaded) => true,
408                    _ => false,
409                }
410        },
411        (ForeignMod(l), ForeignMod(r)) => {
412            both(l.abi.as_ref(), r.abi.as_ref(), eq_str_lit)
413                && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
414        },
415        (
416            TyAlias(box ast::TyAlias {
417                defaultness: ld,
418                generics: lg,
419                bounds: lb,
420                ty: lt,
421                ..
422            }),
423            TyAlias(box ast::TyAlias {
424                defaultness: rd,
425                generics: rg,
426                bounds: rb,
427                ty: rt,
428                ..
429            }),
430        ) => {
431            eq_defaultness(*ld, *rd)
432                && eq_generics(lg, rg)
433                && over(lb, rb, eq_generic_bound)
434                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
435        },
436        (Enum(li, lg, le), Enum(ri, rg, re)) => {
437            eq_id(*li, *ri) && eq_generics(lg, rg) && over(&le.variants, &re.variants, eq_variant)
438        },
439        (Struct(li, lg, lv), Struct(ri, rg, rv)) | (Union(li, lg, lv), Union(ri, rg, rv)) => {
440            eq_id(*li, *ri) && eq_generics(lg, rg) && eq_variant_data(lv, rv)
441        },
442        (
443            Trait(box ast::Trait {
444                impl_restriction: liprt,
445                constness: lc,
446                is_auto: la,
447                safety: lu,
448                ident: li,
449                generics: lg,
450                bounds: lb,
451                items: lis,
452            }),
453            Trait(box ast::Trait {
454                impl_restriction: riprt,
455                constness: rc,
456                is_auto: ra,
457                safety: ru,
458                ident: ri,
459                generics: rg,
460                bounds: rb,
461                items: ris,
462            }),
463        ) => {
464            eq_impl_restriction(liprt, riprt)
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
527fn 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                eii_impls: _,
539            }),
540            Static(box StaticItem {
541                ident: ri,
542                ty: rt,
543                mutability: rm,
544                expr: re,
545                safety: rs,
546                define_opaque: _,
547                eii_impls: _,
548            }),
549        ) => eq_id(*li, *ri) && eq_ty(lt, rt) && lm == rm && eq_expr_opt(le.as_deref(), re.as_deref()) && ls == rs,
550        (
551            Fn(box ast::Fn {
552                defaultness: ld,
553                sig: lf,
554                ident: li,
555                generics: lg,
556                contract: lc,
557                body: lb,
558                define_opaque: _,
559                eii_impls: _,
560            }),
561            Fn(box ast::Fn {
562                defaultness: rd,
563                sig: rf,
564                ident: ri,
565                generics: rg,
566                contract: rc,
567                body: rb,
568                define_opaque: _,
569                eii_impls: _,
570            }),
571        ) => {
572            eq_defaultness(*ld, *rd)
573                && eq_fn_sig(lf, rf)
574                && eq_id(*li, *ri)
575                && eq_generics(lg, rg)
576                && eq_opt_fn_contract(lc, rc)
577                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
578        },
579        (
580            TyAlias(box ast::TyAlias {
581                defaultness: ld,
582                ident: li,
583                generics: lg,
584                after_where_clause: lw,
585                bounds: lb,
586                ty: lt,
587            }),
588            TyAlias(box ast::TyAlias {
589                defaultness: rd,
590                ident: ri,
591                generics: rg,
592                after_where_clause: rw,
593                bounds: rb,
594                ty: rt,
595            }),
596        ) => {
597            eq_defaultness(*ld, *rd)
598                && eq_id(*li, *ri)
599                && eq_generics(lg, rg)
600                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
601                && over(lb, rb, eq_generic_bound)
602                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
603        },
604        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
605        _ => false,
606    }
607}
608
609fn eq_assoc_item_kind(l: &AssocItemKind, r: &AssocItemKind) -> bool {
610    use AssocItemKind::*;
611    match (l, r) {
612        (
613            Const(box ConstItem {
614                defaultness: ld,
615                ident: li,
616                generics: lg,
617                ty: lt,
618                rhs_kind: lb,
619                define_opaque: _,
620            }),
621            Const(box ConstItem {
622                defaultness: rd,
623                ident: ri,
624                generics: rg,
625                ty: rt,
626                rhs_kind: rb,
627                define_opaque: _,
628            }),
629        ) => {
630            eq_defaultness(*ld, *rd)
631                && eq_id(*li, *ri)
632                && eq_generics(lg, rg)
633                && eq_ty(lt, rt)
634                && both(Some(lb), Some(rb), eq_const_item_rhs)
635        },
636        (
637            Fn(box ast::Fn {
638                defaultness: ld,
639                sig: lf,
640                ident: li,
641                generics: lg,
642                contract: lc,
643                body: lb,
644                define_opaque: _,
645                eii_impls: _,
646            }),
647            Fn(box ast::Fn {
648                defaultness: rd,
649                sig: rf,
650                ident: ri,
651                generics: rg,
652                contract: rc,
653                body: rb,
654                define_opaque: _,
655                eii_impls: _,
656            }),
657        ) => {
658            eq_defaultness(*ld, *rd)
659                && eq_fn_sig(lf, rf)
660                && eq_id(*li, *ri)
661                && eq_generics(lg, rg)
662                && eq_opt_fn_contract(lc, rc)
663                && both(lb.as_ref(), rb.as_ref(), |l, r| eq_block(l, r))
664        },
665        (
666            Type(box TyAlias {
667                defaultness: ld,
668                ident: li,
669                generics: lg,
670                after_where_clause: lw,
671                bounds: lb,
672                ty: lt,
673            }),
674            Type(box TyAlias {
675                defaultness: rd,
676                ident: ri,
677                generics: rg,
678                after_where_clause: rw,
679                bounds: rb,
680                ty: rt,
681            }),
682        ) => {
683            eq_defaultness(*ld, *rd)
684                && eq_id(*li, *ri)
685                && eq_generics(lg, rg)
686                && over(&lw.predicates, &rw.predicates, eq_where_predicate)
687                && over(lb, rb, eq_generic_bound)
688                && both(lt.as_ref(), rt.as_ref(), |l, r| eq_ty(l, r))
689        },
690        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
691        _ => false,
692    }
693}
694
695fn eq_variant(l: &Variant, r: &Variant) -> bool {
696    l.is_placeholder == r.is_placeholder
697        && over(&l.attrs, &r.attrs, eq_attr)
698        && eq_vis(&l.vis, &r.vis)
699        && eq_id(l.ident, r.ident)
700        && eq_variant_data(&l.data, &r.data)
701        && both(l.disr_expr.as_ref(), r.disr_expr.as_ref(), |l, r| {
702            eq_expr(&l.value, &r.value)
703        })
704}
705
706fn eq_variant_data(l: &VariantData, r: &VariantData) -> bool {
707    use VariantData::*;
708    match (l, r) {
709        (Unit(_), Unit(_)) => true,
710        (Struct { fields: l, .. }, Struct { fields: r, .. }) | (Tuple(l, _), Tuple(r, _)) => {
711            over(l, r, eq_struct_field)
712        },
713        _ => false,
714    }
715}
716
717fn eq_struct_field(l: &FieldDef, r: &FieldDef) -> bool {
718    l.is_placeholder == r.is_placeholder
719        && over(&l.attrs, &r.attrs, eq_attr)
720        && eq_vis(&l.vis, &r.vis)
721        && eq_mut_restriction(&l.mut_restriction, &r.mut_restriction)
722        && both(l.ident.as_ref(), r.ident.as_ref(), |l, r| eq_id(*l, *r))
723        && eq_ty(&l.ty, &r.ty)
724}
725
726fn eq_fn_sig(l: &FnSig, r: &FnSig) -> bool {
727    eq_fn_decl(&l.decl, &r.decl) && eq_fn_header(&l.header, &r.header)
728}
729
730fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) -> bool {
731    matches!(
732        (l, r),
733        (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. }))
734            | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. }))
735            | (
736                Some(CoroutineKind::AsyncGen { .. }),
737                Some(CoroutineKind::AsyncGen { .. })
738            )
739            | (None, None)
740    )
741}
742
743fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool {
744    matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default)
745        && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
746        && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
747        && eq_ext(&l.ext, &r.ext)
748}
749
750#[expect(clippy::ref_option, reason = "This is the type how it is stored in the AST")]
751fn eq_opt_fn_contract(l: &Option<Box<FnContract>>, r: &Option<Box<FnContract>>) -> bool {
752    match (l, r) {
753        (Some(l), Some(r)) => {
754            eq_expr_opt(l.requires.as_deref(), r.requires.as_deref())
755                && eq_expr_opt(l.ensures.as_deref(), r.ensures.as_deref())
756        },
757        (None, None) => true,
758        (Some(_), None) | (None, Some(_)) => false,
759    }
760}
761
762fn eq_generics(l: &Generics, r: &Generics) -> bool {
763    over(&l.params, &r.params, eq_generic_param)
764        && over(&l.where_clause.predicates, &r.where_clause.predicates, |l, r| {
765            eq_where_predicate(l, r)
766        })
767}
768
769fn eq_where_predicate(l: &WherePredicate, r: &WherePredicate) -> bool {
770    use WherePredicateKind::*;
771    over(&l.attrs, &r.attrs, eq_attr)
772        && match (&l.kind, &r.kind) {
773            (BoundPredicate(l), BoundPredicate(r)) => {
774                over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
775                    eq_generic_param(l, r)
776                }) && eq_ty(&l.bounded_ty, &r.bounded_ty)
777                    && over(&l.bounds, &r.bounds, eq_generic_bound)
778            },
779            (RegionPredicate(l), RegionPredicate(r)) => {
780                eq_id(l.lifetime.ident, r.lifetime.ident) && over(&l.bounds, &r.bounds, eq_generic_bound)
781            },
782            _ => false,
783        }
784}
785
786fn eq_use_tree(l: &UseTree, r: &UseTree) -> bool {
787    eq_path(&l.prefix, &r.prefix) && eq_use_tree_kind(&l.kind, &r.kind)
788}
789
790fn eq_anon_const(l: &AnonConst, r: &AnonConst) -> bool {
791    eq_expr(&l.value, &r.value)
792}
793
794fn eq_const_item_rhs(l: &ConstItemRhsKind, r: &ConstItemRhsKind) -> bool {
795    use ConstItemRhsKind::*;
796    match (l, r) {
797        (TypeConst { rhs: Some(l) }, TypeConst { rhs: Some(r) }) => eq_anon_const(l, r),
798        (TypeConst { rhs: None }, TypeConst { rhs: None }) | (Body { rhs: None }, Body { rhs: None }) => true,
799        (Body { rhs: Some(l) }, Body { rhs: Some(r) }) => eq_expr(l, r),
800        (TypeConst { rhs: Some(..) }, TypeConst { rhs: None })
801        | (TypeConst { rhs: None }, TypeConst { rhs: Some(..) })
802        | (Body { rhs: None }, Body { rhs: Some(..) })
803        | (Body { rhs: Some(..) }, Body { rhs: None })
804        | (TypeConst { .. }, Body { .. })
805        | (Body { .. }, TypeConst { .. }) => false,
806    }
807}
808
809fn eq_use_tree_kind(l: &UseTreeKind, r: &UseTreeKind) -> bool {
810    use UseTreeKind::*;
811    match (l, r) {
812        (Glob(_), Glob(_)) => true,
813        (Simple(l), Simple(r)) => both(l.as_ref(), r.as_ref(), |l, r| eq_id(*l, *r)),
814        (Nested { items: l, .. }, Nested { items: r, .. }) => over(l, r, |(l, _), (r, _)| eq_use_tree(l, r)),
815        _ => false,
816    }
817}
818
819fn eq_defaultness(l: Defaultness, r: Defaultness) -> bool {
820    matches!(
821        (l, r),
822        (Defaultness::Implicit, Defaultness::Implicit)
823            | (Defaultness::Default(_), Defaultness::Default(_))
824            | (Defaultness::Final(_), Defaultness::Final(_))
825    )
826}
827
828fn eq_vis(l: &Visibility, r: &Visibility) -> bool {
829    use VisibilityKind::*;
830    match (&l.kind, &r.kind) {
831        (Public, Public) | (Inherited, Inherited) => true,
832        (Restricted { path: l, .. }, Restricted { path: r, .. }) => eq_path(l, r),
833        _ => false,
834    }
835}
836
837fn eq_impl_restriction(l: &ImplRestriction, r: &ImplRestriction) -> bool {
838    eq_restriction_kind(&l.kind, &r.kind)
839}
840
841pub fn eq_mut_restriction(l: &MutRestriction, r: &MutRestriction) -> bool {
842    eq_restriction_kind(&l.kind, &r.kind)
843}
844
845fn eq_restriction_kind(l: &RestrictionKind, r: &RestrictionKind) -> bool {
846    match (l, r) {
847        (RestrictionKind::Unrestricted, RestrictionKind::Unrestricted) => true,
848        (
849            RestrictionKind::Restricted {
850                path: l_path,
851                shorthand: l_short,
852                id: _,
853            },
854            RestrictionKind::Restricted {
855                path: r_path,
856                shorthand: r_short,
857                id: _,
858            },
859        ) => l_short == r_short && eq_path(l_path, r_path),
860        _ => false,
861    }
862}
863
864fn eq_fn_decl(l: &FnDecl, r: &FnDecl) -> bool {
865    eq_fn_ret_ty(&l.output, &r.output)
866        && over(&l.inputs, &r.inputs, |l, r| {
867            l.is_placeholder == r.is_placeholder
868                && eq_pat(&l.pat, &r.pat)
869                && eq_ty(&l.ty, &r.ty)
870                && over(&l.attrs, &r.attrs, eq_attr)
871        })
872}
873
874fn eq_closure_binder(l: &ClosureBinder, r: &ClosureBinder) -> bool {
875    match (l, r) {
876        (ClosureBinder::NotPresent, ClosureBinder::NotPresent) => true,
877        (ClosureBinder::For { generic_params: lp, .. }, ClosureBinder::For { generic_params: rp, .. }) => {
878            lp.len() == rp.len() && std::iter::zip(lp.iter(), rp.iter()).all(|(l, r)| eq_generic_param(l, r))
879        },
880        _ => false,
881    }
882}
883
884fn eq_fn_ret_ty(l: &FnRetTy, r: &FnRetTy) -> bool {
885    match (l, r) {
886        (FnRetTy::Default(_), FnRetTy::Default(_)) => true,
887        (FnRetTy::Ty(l), FnRetTy::Ty(r)) => eq_ty(l, r),
888        _ => false,
889    }
890}
891
892fn eq_ty(l: &Ty, r: &Ty) -> bool {
893    use TyKind::*;
894    match (&l.kind, &r.kind) {
895        (Paren(l), _) => eq_ty(l, r),
896        (_, Paren(r)) => eq_ty(l, r),
897        (Never, Never) | (Infer, Infer) | (ImplicitSelf, ImplicitSelf) | (Err(_), Err(_)) | (CVarArgs, CVarArgs) => {
898            true
899        },
900        (Slice(l), Slice(r)) => eq_ty(l, r),
901        (Array(le, ls), Array(re, rs)) => eq_ty(le, re) && eq_expr(&ls.value, &rs.value),
902        (Ptr(l), Ptr(r)) => l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty),
903        (Ref(ll, l), Ref(rl, r)) => {
904            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)
905        },
906        (PinnedRef(ll, l), PinnedRef(rl, r)) => {
907            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)
908        },
909        (FnPtr(l), FnPtr(r)) => {
910            l.safety == r.safety
911                && eq_ext(&l.ext, &r.ext)
912                && over(&l.generic_params, &r.generic_params, eq_generic_param)
913                && eq_fn_decl(&l.decl, &r.decl)
914        },
915        (Tup(l), Tup(r)) => over(l, r, |l, r| eq_ty(l, r)),
916        (Path(lq, lp), Path(rq, rp)) => both(lq.as_deref(), rq.as_deref(), eq_qself) && eq_path(lp, rp),
917        (TraitObject(lg, ls), TraitObject(rg, rs)) => ls == rs && over(lg, rg, eq_generic_bound),
918        (ImplTrait(_, lg), ImplTrait(_, rg)) => over(lg, rg, eq_generic_bound),
919        (MacCall(l), MacCall(r)) => eq_mac_call(l, r),
920        _ => false,
921    }
922}
923
924fn eq_ext(l: &Extern, r: &Extern) -> bool {
925    use Extern::*;
926    match (l, r) {
927        (None, None) | (Implicit(_), Implicit(_)) => true,
928        (Explicit(l, _), Explicit(r, _)) => eq_str_lit(l, r),
929        _ => false,
930    }
931}
932
933fn eq_str_lit(l: &StrLit, r: &StrLit) -> bool {
934    l.style == r.style && l.symbol == r.symbol && l.suffix == r.suffix
935}
936
937fn eq_poly_ref_trait(l: &PolyTraitRef, r: &PolyTraitRef) -> bool {
938    l.modifiers == r.modifiers
939        && eq_path(&l.trait_ref.path, &r.trait_ref.path)
940        && over(&l.bound_generic_params, &r.bound_generic_params, |l, r| {
941            eq_generic_param(l, r)
942        })
943}
944
945fn eq_generic_param(l: &GenericParam, r: &GenericParam) -> bool {
946    use GenericParamKind::*;
947    l.is_placeholder == r.is_placeholder
948        && eq_id(l.ident, r.ident)
949        && over(&l.bounds, &r.bounds, eq_generic_bound)
950        && match (&l.kind, &r.kind) {
951            (Lifetime, Lifetime) => true,
952            (Type { default: l }, Type { default: r }) => both(l.as_ref(), r.as_ref(), |l, r| eq_ty(l, r)),
953            (
954                Const {
955                    ty: lt,
956                    default: ld,
957                    span: _,
958                },
959                Const {
960                    ty: rt,
961                    default: rd,
962                    span: _,
963                },
964            ) => eq_ty(lt, rt) && both(ld.as_ref(), rd.as_ref(), eq_anon_const),
965            _ => false,
966        }
967        && over(&l.attrs, &r.attrs, eq_attr)
968}
969
970fn eq_generic_bound(l: &GenericBound, r: &GenericBound) -> bool {
971    use GenericBound::*;
972    match (l, r) {
973        (Trait(ptr1), Trait(ptr2)) => eq_poly_ref_trait(ptr1, ptr2),
974        (Outlives(l), Outlives(r)) => eq_id(l.ident, r.ident),
975        _ => false,
976    }
977}
978
979fn eq_term(l: &Term, r: &Term) -> bool {
980    match (l, r) {
981        (Term::Ty(l), Term::Ty(r)) => eq_ty(l, r),
982        (Term::Const(l), Term::Const(r)) => eq_anon_const(l, r),
983        _ => false,
984    }
985}
986
987fn eq_assoc_item_constraint(l: &AssocItemConstraint, r: &AssocItemConstraint) -> bool {
988    use AssocItemConstraintKind::*;
989    eq_id(l.ident, r.ident)
990        && match (&l.kind, &r.kind) {
991            (Equality { term: l }, Equality { term: r }) => eq_term(l, r),
992            (Bound { bounds: l }, Bound { bounds: r }) => over(l, r, eq_generic_bound),
993            _ => false,
994        }
995}
996
997fn eq_mac_call(l: &MacCall, r: &MacCall) -> bool {
998    eq_path(&l.path, &r.path) && eq_delim_args(&l.args, &r.args)
999}
1000
1001fn eq_attr(l: &Attribute, r: &Attribute) -> bool {
1002    use AttrKind::*;
1003    l.style == r.style
1004        && match (&l.kind, &r.kind) {
1005            (DocComment(l1, l2), DocComment(r1, r2)) => l1 == r1 && l2 == r2,
1006            (Normal(l), Normal(r)) => {
1007                eq_path(&l.item.path, &r.item.path) && eq_attr_args(&l.item.args, &r.item.args)
1008            },
1009            (Synthetic(..), _) | (_, Synthetic(..)) => unreachable!(),
1010            _ => false,
1011        }
1012}
1013
1014fn eq_attr_args(l: &AttrArgs, r: &AttrArgs) -> bool {
1015    use AttrArgs::*;
1016    match (l, r) {
1017        (Empty, Empty) => true,
1018        (Delimited(la), Delimited(ra)) => eq_delim_args(la, ra),
1019        (Eq { eq_span: _, expr: le }, Eq { eq_span: _, expr: re }) => eq_expr(le, re),
1020        _ => false,
1021    }
1022}
1023
1024fn eq_delim_args(l: &DelimArgs, r: &DelimArgs) -> bool {
1025    l.delim == r.delim
1026        && l.tokens.len() == r.tokens.len()
1027        && l.tokens.iter().zip(r.tokens.iter()).all(|(a, b)| a.eq_unspanned(b))
1028}
1029
1030/// Checks whether `item` is gated on `#[cfg(test)]`.
1031pub fn is_cfg_test(item: &impl HasAttrs) -> bool {
1032    item.attrs().iter().any(|attr| {
1033        if attr.has_name(sym::cfg)
1034            && let Some(item_list) = attr.meta_item_list()
1035            && item_list.iter().any(|item| item.has_name(sym::test))
1036        {
1037            true
1038        } else if let AttrKind::Synthetic(synthetic) = &attr.kind
1039            && let SyntheticAttr::CfgTrace(cfg) = &**synthetic
1040        {
1041            requires_test_cfg(cfg)
1042        } else {
1043            false
1044        }
1045    })
1046}
1047
1048fn requires_test_cfg(cfg: &CfgEntry) -> bool {
1049    match cfg {
1050        CfgEntry::NameValue { name: sym::test, .. } => true,
1051        CfgEntry::All(subs, _) => subs.iter().any(requires_test_cfg),
1052        _ => false,
1053    }
1054}