clippy_utils/
hir_utils.rs

1use crate::consts::ConstEvalCtxt;
2use crate::macros::macro_backtrace;
3use crate::source::{SpanRange, SpanRangeExt, walk_span_to_context};
4use crate::tokenize_with_text;
5use rustc_ast::ast;
6use rustc_ast::ast::InlineAsmTemplatePiece;
7use rustc_data_structures::fx::{FxHasher, FxIndexMap};
8use rustc_hir::MatchSource::TryDesugar;
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::{
12    AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, ByRef, Closure, ConstArg, ConstArgKind, ConstItemRhs,
13    Expr, ExprField, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericArgs, GenericBound, GenericBounds,
14    GenericParam, GenericParamKind, GenericParamSource, Generics, HirId, HirIdMap, InlineAsmOperand, ItemId, ItemKind,
15    LetExpr, Lifetime, LifetimeKind, LifetimeParamKind, Node, ParamName, Pat, PatExpr, PatExprKind, PatField, PatKind,
16    Path, PathSegment, PreciseCapturingArgKind, PrimTy, QPath, Stmt, StmtKind, StructTailExpr, TraitBoundModifiers, Ty,
17    TyKind, TyPat, TyPatKind, UseKind, WherePredicate, WherePredicateKind,
18};
19use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize};
20use rustc_lint::LateContext;
21use rustc_middle::ty::TypeckResults;
22use rustc_span::{BytePos, ExpnKind, MacroKind, Symbol, SyntaxContext, sym};
23use std::hash::{Hash, Hasher};
24use std::ops::Range;
25use std::slice;
26
27/// Callback that is called when two expressions are not equal in the sense of `SpanlessEq`, but
28/// other conditions would make them equal.
29type SpanlessEqCallback<'a> = dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a;
30
31/// Determines how paths are hashed and compared for equality.
32#[derive(Copy, Clone, Debug, Default)]
33pub enum PathCheck {
34    /// Paths must match exactly and are hashed by their exact HIR tree.
35    ///
36    /// Thus, `std::iter::Iterator` and `Iterator` are not considered equal even though they refer
37    /// to the same item.
38    #[default]
39    Exact,
40    /// Paths are compared and hashed based on their resolution.
41    ///
42    /// They can appear different in the HIR tree but are still considered equal
43    /// and have equal hashes as long as they refer to the same item.
44    ///
45    /// Note that this is currently only partially implemented specifically for paths that are
46    /// resolved before type-checking, i.e. the final segment must have a non-error resolution.
47    /// If a path with an error resolution is encountered, it falls back to the default exact
48    /// matching behavior.
49    Resolution,
50}
51
52/// Type used to check whether two ast are the same. This is different from the
53/// operator `==` on ast types as this operator would compare true equality with
54/// ID and span.
55///
56/// Note that some expressions kinds are not considered but could be added.
57pub struct SpanlessEq<'a, 'tcx> {
58    /// Context used to evaluate constant expressions.
59    cx: &'a LateContext<'tcx>,
60    maybe_typeck_results: Option<(&'tcx TypeckResults<'tcx>, &'tcx TypeckResults<'tcx>)>,
61    allow_side_effects: bool,
62    expr_fallback: Option<Box<SpanlessEqCallback<'a>>>,
63    path_check: PathCheck,
64}
65
66impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
67    pub fn new(cx: &'a LateContext<'tcx>) -> Self {
68        Self {
69            cx,
70            maybe_typeck_results: cx.maybe_typeck_results().map(|x| (x, x)),
71            allow_side_effects: true,
72            expr_fallback: None,
73            path_check: PathCheck::default(),
74        }
75    }
76
77    /// Consider expressions containing potential side effects as not equal.
78    #[must_use]
79    pub fn deny_side_effects(self) -> Self {
80        Self {
81            allow_side_effects: false,
82            ..self
83        }
84    }
85
86    /// Check paths by their resolution instead of exact equality. See [`PathCheck`] for more
87    /// details.
88    #[must_use]
89    pub fn paths_by_resolution(self) -> Self {
90        Self {
91            path_check: PathCheck::Resolution,
92            ..self
93        }
94    }
95
96    #[must_use]
97    pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
98        Self {
99            expr_fallback: Some(Box::new(expr_fallback)),
100            ..self
101        }
102    }
103
104    /// Use this method to wrap comparisons that may involve inter-expression context.
105    /// See `self.locals`.
106    pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
107        HirEqInterExpr {
108            inner: self,
109            left_ctxt: SyntaxContext::root(),
110            right_ctxt: SyntaxContext::root(),
111            locals: HirIdMap::default(),
112            local_items: FxIndexMap::default(),
113        }
114    }
115
116    pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
117        self.inter_expr().eq_block(left, right)
118    }
119
120    pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
121        self.inter_expr().eq_expr(left, right)
122    }
123
124    pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
125        self.inter_expr().eq_path(left, right)
126    }
127
128    pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
129        self.inter_expr().eq_path_segment(left, right)
130    }
131
132    pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
133        self.inter_expr().eq_path_segments(left, right)
134    }
135
136    pub fn eq_modifiers(left: TraitBoundModifiers, right: TraitBoundModifiers) -> bool {
137        std::mem::discriminant(&left.constness) == std::mem::discriminant(&right.constness)
138            && std::mem::discriminant(&left.polarity) == std::mem::discriminant(&right.polarity)
139    }
140}
141
142pub struct HirEqInterExpr<'a, 'b, 'tcx> {
143    inner: &'a mut SpanlessEq<'b, 'tcx>,
144    left_ctxt: SyntaxContext,
145    right_ctxt: SyntaxContext,
146
147    // When binding are declared, the binding ID in the left expression is mapped to the one on the
148    // right. For example, when comparing `{ let x = 1; x + 2 }` and `{ let y = 1; y + 2 }`,
149    // these blocks are considered equal since `x` is mapped to `y`.
150    pub locals: HirIdMap<HirId>,
151    pub local_items: FxIndexMap<DefId, DefId>,
152}
153
154impl HirEqInterExpr<'_, '_, '_> {
155    pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
156        match (&left.kind, &right.kind) {
157            (StmtKind::Let(l), StmtKind::Let(r)) => {
158                // This additional check ensures that the type of the locals are equivalent even if the init
159                // expression or type have some inferred parts.
160                if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
161                    let l_ty = typeck_lhs.pat_ty(l.pat);
162                    let r_ty = typeck_rhs.pat_ty(r.pat);
163                    if l_ty != r_ty {
164                        return false;
165                    }
166                }
167
168                // eq_pat adds the HirIds to the locals map. We therefore call it last to make sure that
169                // these only get added if the init and type is equal.
170                both(l.init.as_ref(), r.init.as_ref(), |l, r| self.eq_expr(l, r))
171                    && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
172                    && both(l.els.as_ref(), r.els.as_ref(), |l, r| self.eq_block(l, r))
173                    && self.eq_pat(l.pat, r.pat)
174            },
175            (StmtKind::Expr(l), StmtKind::Expr(r)) | (StmtKind::Semi(l), StmtKind::Semi(r)) => self.eq_expr(l, r),
176            (StmtKind::Item(l), StmtKind::Item(r)) => self.eq_item(*l, *r),
177            _ => false,
178        }
179    }
180
181    pub fn eq_item(&mut self, l: ItemId, r: ItemId) -> bool {
182        let left = self.inner.cx.tcx.hir_item(l);
183        let right = self.inner.cx.tcx.hir_item(r);
184        let eq = match (left.kind, right.kind) {
185            (
186                ItemKind::Const(l_ident, l_generics, l_ty, ConstItemRhs::Body(l_body)),
187                ItemKind::Const(r_ident, r_generics, r_ty, ConstItemRhs::Body(r_body)),
188            ) => {
189                l_ident.name == r_ident.name
190                    && self.eq_generics(l_generics, r_generics)
191                    && self.eq_ty(l_ty, r_ty)
192                    && self.eq_body(l_body, r_body)
193            },
194            (ItemKind::Static(l_mut, l_ident, l_ty, l_body), ItemKind::Static(r_mut, r_ident, r_ty, r_body)) => {
195                l_mut == r_mut && l_ident.name == r_ident.name && self.eq_ty(l_ty, r_ty) && self.eq_body(l_body, r_body)
196            },
197            (
198                ItemKind::Fn {
199                    sig: l_sig,
200                    ident: l_ident,
201                    generics: l_generics,
202                    body: l_body,
203                    has_body: l_has_body,
204                },
205                ItemKind::Fn {
206                    sig: r_sig,
207                    ident: r_ident,
208                    generics: r_generics,
209                    body: r_body,
210                    has_body: r_has_body,
211                },
212            ) => {
213                l_ident.name == r_ident.name
214                    && (l_has_body == r_has_body)
215                    && self.eq_fn_sig(&l_sig, &r_sig)
216                    && self.eq_generics(l_generics, r_generics)
217                    && self.eq_body(l_body, r_body)
218            },
219            (ItemKind::TyAlias(l_ident, l_generics, l_ty), ItemKind::TyAlias(r_ident, r_generics, r_ty)) => {
220                l_ident.name == r_ident.name && self.eq_generics(l_generics, r_generics) && self.eq_ty(l_ty, r_ty)
221            },
222            (ItemKind::Use(l_path, l_kind), ItemKind::Use(r_path, r_kind)) => {
223                self.eq_path_segments(l_path.segments, r_path.segments)
224                    && match (l_kind, r_kind) {
225                        (UseKind::Single(l_ident), UseKind::Single(r_ident)) => l_ident.name == r_ident.name,
226                        (UseKind::Glob, UseKind::Glob) | (UseKind::ListStem, UseKind::ListStem) => true,
227                        _ => false,
228                    }
229            },
230            (ItemKind::Mod(l_ident, l_mod), ItemKind::Mod(r_ident, r_mod)) => {
231                l_ident.name == r_ident.name && over(l_mod.item_ids, r_mod.item_ids, |l, r| self.eq_item(*l, *r))
232            },
233            _ => false,
234        };
235        if eq {
236            self.local_items.insert(l.owner_id.to_def_id(), r.owner_id.to_def_id());
237        }
238        eq
239    }
240
241    fn eq_fn_sig(&mut self, left: &FnSig<'_>, right: &FnSig<'_>) -> bool {
242        left.header.safety == right.header.safety
243            && left.header.constness == right.header.constness
244            && left.header.asyncness == right.header.asyncness
245            && left.header.abi == right.header.abi
246            && self.eq_fn_decl(left.decl, right.decl)
247    }
248
249    fn eq_fn_decl(&mut self, left: &FnDecl<'_>, right: &FnDecl<'_>) -> bool {
250        over(left.inputs, right.inputs, |l, r| self.eq_ty(l, r))
251            && (match (left.output, right.output) {
252                (FnRetTy::DefaultReturn(_), FnRetTy::DefaultReturn(_)) => true,
253                (FnRetTy::Return(l_ty), FnRetTy::Return(r_ty)) => self.eq_ty(l_ty, r_ty),
254                _ => false,
255            })
256            && left.c_variadic == right.c_variadic
257            && left.implicit_self == right.implicit_self
258            && left.lifetime_elision_allowed == right.lifetime_elision_allowed
259    }
260
261    fn eq_generics(&mut self, left: &Generics<'_>, right: &Generics<'_>) -> bool {
262        self.eq_generics_param(left.params, right.params)
263            && self.eq_generics_predicate(left.predicates, right.predicates)
264    }
265
266    fn eq_generics_predicate(&mut self, left: &[WherePredicate<'_>], right: &[WherePredicate<'_>]) -> bool {
267        over(left, right, |l, r| match (l.kind, r.kind) {
268            (WherePredicateKind::BoundPredicate(l_bound), WherePredicateKind::BoundPredicate(r_bound)) => {
269                l_bound.origin == r_bound.origin
270                    && self.eq_ty(l_bound.bounded_ty, r_bound.bounded_ty)
271                    && self.eq_generics_param(l_bound.bound_generic_params, r_bound.bound_generic_params)
272                    && self.eq_generics_bound(l_bound.bounds, r_bound.bounds)
273            },
274            (WherePredicateKind::RegionPredicate(l_region), WherePredicateKind::RegionPredicate(r_region)) => {
275                Self::eq_lifetime(l_region.lifetime, r_region.lifetime)
276                    && self.eq_generics_bound(l_region.bounds, r_region.bounds)
277            },
278            (WherePredicateKind::EqPredicate(l_eq), WherePredicateKind::EqPredicate(r_eq)) => {
279                self.eq_ty(l_eq.lhs_ty, r_eq.lhs_ty)
280            },
281            _ => false,
282        })
283    }
284
285    fn eq_generics_bound(&mut self, left: GenericBounds<'_>, right: GenericBounds<'_>) -> bool {
286        over(left, right, |l, r| match (l, r) {
287            (GenericBound::Trait(l_trait), GenericBound::Trait(r_trait)) => {
288                l_trait.modifiers == r_trait.modifiers
289                    && self.eq_path(l_trait.trait_ref.path, r_trait.trait_ref.path)
290                    && self.eq_generics_param(l_trait.bound_generic_params, r_trait.bound_generic_params)
291            },
292            (GenericBound::Outlives(l_lifetime), GenericBound::Outlives(r_lifetime)) => {
293                Self::eq_lifetime(l_lifetime, r_lifetime)
294            },
295            (GenericBound::Use(l_capture, _), GenericBound::Use(r_capture, _)) => {
296                over(l_capture, r_capture, |l, r| match (l, r) {
297                    (PreciseCapturingArgKind::Lifetime(l_lifetime), PreciseCapturingArgKind::Lifetime(r_lifetime)) => {
298                        Self::eq_lifetime(l_lifetime, r_lifetime)
299                    },
300                    (PreciseCapturingArgKind::Param(l_param), PreciseCapturingArgKind::Param(r_param)) => {
301                        l_param.ident == r_param.ident && l_param.res == r_param.res
302                    },
303                    _ => false,
304                })
305            },
306            _ => false,
307        })
308    }
309
310    fn eq_generics_param(&mut self, left: &[GenericParam<'_>], right: &[GenericParam<'_>]) -> bool {
311        over(left, right, |l, r| {
312            (match (l.name, r.name) {
313                (ParamName::Plain(l_ident), ParamName::Plain(r_ident))
314                | (ParamName::Error(l_ident), ParamName::Error(r_ident)) => l_ident.name == r_ident.name,
315                (ParamName::Fresh, ParamName::Fresh) => true,
316                _ => false,
317            }) && l.pure_wrt_drop == r.pure_wrt_drop
318                && self.eq_generics_param_kind(&l.kind, &r.kind)
319                && (matches!(
320                    (l.source, r.source),
321                    (GenericParamSource::Generics, GenericParamSource::Generics)
322                        | (GenericParamSource::Binder, GenericParamSource::Binder)
323                ))
324        })
325    }
326
327    fn eq_generics_param_kind(&mut self, left: &GenericParamKind<'_>, right: &GenericParamKind<'_>) -> bool {
328        match (left, right) {
329            (GenericParamKind::Lifetime { kind: l_kind }, GenericParamKind::Lifetime { kind: r_kind }) => {
330                match (l_kind, r_kind) {
331                    (LifetimeParamKind::Explicit, LifetimeParamKind::Explicit)
332                    | (LifetimeParamKind::Error, LifetimeParamKind::Error) => true,
333                    (LifetimeParamKind::Elided(l_lifetime_kind), LifetimeParamKind::Elided(r_lifetime_kind)) => {
334                        l_lifetime_kind == r_lifetime_kind
335                    },
336                    _ => false,
337                }
338            },
339            (
340                GenericParamKind::Type {
341                    default: l_default,
342                    synthetic: l_synthetic,
343                },
344                GenericParamKind::Type {
345                    default: r_default,
346                    synthetic: r_synthetic,
347                },
348            ) => both(*l_default, *r_default, |l, r| self.eq_ty(l, r)) && l_synthetic == r_synthetic,
349            (
350                GenericParamKind::Const {
351                    ty: l_ty,
352                    default: l_default,
353                },
354                GenericParamKind::Const {
355                    ty: r_ty,
356                    default: r_default,
357                },
358            ) => self.eq_ty(l_ty, r_ty) && both(*l_default, *r_default, |l, r| self.eq_const_arg(l, r)),
359            _ => false,
360        }
361    }
362
363    /// Checks whether two blocks are the same.
364    fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
365        use TokenKind::{Semi, Whitespace};
366        if left.stmts.len() != right.stmts.len() {
367            return false;
368        }
369        let lspan = left.span.data();
370        let rspan = right.span.data();
371        if lspan.ctxt != SyntaxContext::root() && rspan.ctxt != SyntaxContext::root() {
372            // Don't try to check in between statements inside macros.
373            return over(left.stmts, right.stmts, |left, right| self.eq_stmt(left, right))
374                && both(left.expr.as_ref(), right.expr.as_ref(), |left, right| {
375                    self.eq_expr(left, right)
376                });
377        }
378        if lspan.ctxt != rspan.ctxt {
379            return false;
380        }
381
382        let mut lstart = lspan.lo;
383        let mut rstart = rspan.lo;
384
385        for (left, right) in left.stmts.iter().zip(right.stmts) {
386            if !self.eq_stmt(left, right) {
387                return false;
388            }
389
390            // Try to detect any `cfg`ed statements or empty macro expansions.
391            let Some(lstmt_span) = walk_span_to_context(left.span, lspan.ctxt) else {
392                return false;
393            };
394            let Some(rstmt_span) = walk_span_to_context(right.span, rspan.ctxt) else {
395                return false;
396            };
397            let lstmt_span = lstmt_span.data();
398            let rstmt_span = rstmt_span.data();
399
400            if lstmt_span.lo < lstart && rstmt_span.lo < rstart {
401                // Can happen when macros expand to multiple statements, or rearrange statements.
402                // Nothing in between the statements to check in this case.
403                continue;
404            }
405            if lstmt_span.lo < lstart || rstmt_span.lo < rstart {
406                // Only one of the blocks had a weird macro.
407                return false;
408            }
409            if !eq_span_tokens(self.inner.cx, lstart..lstmt_span.lo, rstart..rstmt_span.lo, |t| {
410                !matches!(t, Whitespace | Semi)
411            }) {
412                return false;
413            }
414
415            lstart = lstmt_span.hi;
416            rstart = rstmt_span.hi;
417        }
418
419        let (lend, rend) = match (left.expr, right.expr) {
420            (Some(left), Some(right)) => {
421                if !self.eq_expr(left, right) {
422                    return false;
423                }
424                let Some(lexpr_span) = walk_span_to_context(left.span, lspan.ctxt) else {
425                    return false;
426                };
427                let Some(rexpr_span) = walk_span_to_context(right.span, rspan.ctxt) else {
428                    return false;
429                };
430                (lexpr_span.lo(), rexpr_span.lo())
431            },
432            (None, None) => (lspan.hi, rspan.hi),
433            (Some(_), None) | (None, Some(_)) => return false,
434        };
435
436        if lend < lstart && rend < rstart {
437            // Can happen when macros rearrange the input.
438            // Nothing in between the statements to check in this case.
439            return true;
440        } else if lend < lstart || rend < rstart {
441            // Only one of the blocks had a weird macro
442            return false;
443        }
444        eq_span_tokens(self.inner.cx, lstart..lend, rstart..rend, |t| {
445            !matches!(t, Whitespace | Semi)
446        })
447    }
448
449    fn should_ignore(&self, expr: &Expr<'_>) -> bool {
450        macro_backtrace(expr.span).last().is_some_and(|macro_call| {
451            matches!(
452                self.inner.cx.tcx.get_diagnostic_name(macro_call.def_id),
453                Some(sym::todo_macro | sym::unimplemented_macro)
454            )
455        })
456    }
457
458    pub fn eq_body(&mut self, left: BodyId, right: BodyId) -> bool {
459        // swap out TypeckResults when hashing a body
460        let old_maybe_typeck_results = self.inner.maybe_typeck_results.replace((
461            self.inner.cx.tcx.typeck_body(left),
462            self.inner.cx.tcx.typeck_body(right),
463        ));
464        let res = self.eq_expr(
465            self.inner.cx.tcx.hir_body(left).value,
466            self.inner.cx.tcx.hir_body(right).value,
467        );
468        self.inner.maybe_typeck_results = old_maybe_typeck_results;
469        res
470    }
471
472    #[expect(clippy::too_many_lines)]
473    pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
474        if !self.check_ctxt(left.span.ctxt(), right.span.ctxt()) {
475            return false;
476        }
477
478        if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results
479            && typeck_lhs.expr_ty(left) == typeck_rhs.expr_ty(right)
480            && let (Some(l), Some(r)) = (
481                ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_lhs)
482                    .eval_local(left, self.left_ctxt),
483                ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_rhs)
484                    .eval_local(right, self.right_ctxt),
485            )
486            && l == r
487        {
488            return true;
489        }
490
491        let is_eq = match (
492            reduce_exprkind(self.inner.cx, &left.kind),
493            reduce_exprkind(self.inner.cx, &right.kind),
494        ) {
495            (ExprKind::AddrOf(lb, l_mut, le), ExprKind::AddrOf(rb, r_mut, re)) => {
496                lb == rb && l_mut == r_mut && self.eq_expr(le, re)
497            },
498            (ExprKind::Array(l), ExprKind::Array(r)) => self.eq_exprs(l, r),
499            (ExprKind::Assign(ll, lr, _), ExprKind::Assign(rl, rr, _)) => {
500                self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
501            },
502            (ExprKind::AssignOp(lo, ll, lr), ExprKind::AssignOp(ro, rl, rr)) => {
503                self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
504            },
505            (ExprKind::Block(l, _), ExprKind::Block(r, _)) => self.eq_block(l, r),
506            (ExprKind::Binary(l_op, ll, lr), ExprKind::Binary(r_op, rl, rr)) => {
507                l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
508                    || swap_binop(l_op.node, ll, lr).is_some_and(|(l_op, ll, lr)| {
509                        l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
510                    })
511            },
512            (ExprKind::Break(li, le), ExprKind::Break(ri, re)) => {
513                both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
514                    && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
515            },
516            (ExprKind::Call(l_fun, l_args), ExprKind::Call(r_fun, r_args)) => {
517                self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
518            },
519            (ExprKind::Cast(lx, lt), ExprKind::Cast(rx, rt)) => {
520                self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
521            },
522            (ExprKind::Closure(_l), ExprKind::Closure(_r)) => false,
523            (ExprKind::ConstBlock(lb), ExprKind::ConstBlock(rb)) => self.eq_body(lb.body, rb.body),
524            (ExprKind::Continue(li), ExprKind::Continue(ri)) => {
525                both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
526            },
527            (ExprKind::DropTemps(le), ExprKind::DropTemps(re)) => self.eq_expr(le, re),
528            (ExprKind::Field(l_f_exp, l_f_ident), ExprKind::Field(r_f_exp, r_f_ident)) => {
529                l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
530            },
531            (ExprKind::Index(la, li, _), ExprKind::Index(ra, ri, _)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
532            (ExprKind::If(lc, lt, le), ExprKind::If(rc, rt, re)) => {
533                self.eq_expr(lc, rc) && self.eq_expr(lt, rt)
534                    && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
535            },
536            (ExprKind::Let(l), ExprKind::Let(r)) => {
537                self.eq_pat(l.pat, r.pat)
538                    && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
539                    && self.eq_expr(l.init, r.init)
540            },
541            (ExprKind::Lit(l), ExprKind::Lit(r)) => l.node == r.node,
542            (ExprKind::Loop(lb, ll, lls, _), ExprKind::Loop(rb, rl, rls, _)) => {
543                lls == rls && self.eq_block(lb, rb)
544                    && both(ll.as_ref(), rl.as_ref(), |l, r| l.ident.name == r.ident.name)
545            },
546            (ExprKind::Match(le, la, ls), ExprKind::Match(re, ra, rs)) => {
547                (ls == rs || (matches!((ls, rs), (TryDesugar(_), TryDesugar(_)))))
548                    && self.eq_expr(le, re)
549                    && over(la, ra, |l, r| {
550                        self.eq_pat(l.pat, r.pat)
551                            && both(l.guard.as_ref(), r.guard.as_ref(), |l, r| self.eq_expr(l, r))
552                            && self.eq_expr(l.body, r.body)
553                    })
554            },
555            (
556                ExprKind::MethodCall(l_path, l_receiver, l_args, _),
557                ExprKind::MethodCall(r_path, r_receiver, r_args, _),
558            ) => {
559                self.inner.allow_side_effects
560                    && self.eq_path_segment(l_path, r_path)
561                    && self.eq_expr(l_receiver, r_receiver)
562                    && self.eq_exprs(l_args, r_args)
563            },
564            (ExprKind::UnsafeBinderCast(lkind, le, None), ExprKind::UnsafeBinderCast(rkind, re, None)) =>
565                lkind == rkind && self.eq_expr(le, re),
566            (ExprKind::UnsafeBinderCast(lkind, le, Some(lt)), ExprKind::UnsafeBinderCast(rkind, re, Some(rt))) =>
567                lkind == rkind && self.eq_expr(le, re) && self.eq_ty(lt, rt),
568            (ExprKind::OffsetOf(l_container, l_fields), ExprKind::OffsetOf(r_container, r_fields)) => {
569                self.eq_ty(l_container, r_container) && over(l_fields, r_fields, |l, r| l.name == r.name)
570            },
571            (ExprKind::Path(l), ExprKind::Path(r)) => self.eq_qpath(l, r),
572            (ExprKind::Repeat(le, ll), ExprKind::Repeat(re, rl)) => {
573                self.eq_expr(le, re) && self.eq_const_arg(ll, rl)
574            },
575            (ExprKind::Ret(l), ExprKind::Ret(r)) => both(l.as_ref(), r.as_ref(), |l, r| self.eq_expr(l, r)),
576            (ExprKind::Struct(l_path, lf, lo), ExprKind::Struct(r_path, rf, ro)) => {
577                self.eq_qpath(l_path, r_path)
578                    && match (lo, ro) {
579                        (StructTailExpr::Base(l),StructTailExpr::Base(r)) => self.eq_expr(l, r),
580                        (StructTailExpr::None, StructTailExpr::None) |
581                        (StructTailExpr::DefaultFields(_), StructTailExpr::DefaultFields(_)) => true,
582                        _ => false,
583                    }
584                    && over(lf, rf, |l, r| self.eq_expr_field(l, r))
585            },
586            (ExprKind::Tup(l_tup), ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
587            (ExprKind::Use(l_expr, _), ExprKind::Use(r_expr, _)) => self.eq_expr(l_expr, r_expr),
588            (ExprKind::Type(le, lt), ExprKind::Type(re, rt)) => self.eq_expr(le, re) && self.eq_ty(lt, rt),
589            (ExprKind::Unary(l_op, le), ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
590            (ExprKind::Yield(le, _), ExprKind::Yield(re, _)) => return self.eq_expr(le, re),
591            (
592                // Else branches for branches above, grouped as per `match_same_arms`.
593                | ExprKind::AddrOf(..)
594                | ExprKind::Array(..)
595                | ExprKind::Assign(..)
596                | ExprKind::AssignOp(..)
597                | ExprKind::Binary(..)
598                | ExprKind::Become(..)
599                | ExprKind::Block(..)
600                | ExprKind::Break(..)
601                | ExprKind::Call(..)
602                | ExprKind::Cast(..)
603                | ExprKind::ConstBlock(..)
604                | ExprKind::Continue(..)
605                | ExprKind::DropTemps(..)
606                | ExprKind::Field(..)
607                | ExprKind::Index(..)
608                | ExprKind::If(..)
609                | ExprKind::Let(..)
610                | ExprKind::Lit(..)
611                | ExprKind::Loop(..)
612                | ExprKind::Match(..)
613                | ExprKind::MethodCall(..)
614                | ExprKind::OffsetOf(..)
615                | ExprKind::Path(..)
616                | ExprKind::Repeat(..)
617                | ExprKind::Ret(..)
618                | ExprKind::Struct(..)
619                | ExprKind::Tup(..)
620                | ExprKind::Use(..)
621                | ExprKind::Type(..)
622                | ExprKind::Unary(..)
623                | ExprKind::Yield(..)
624                | ExprKind::UnsafeBinderCast(..)
625
626                // --- Special cases that do not have a positive branch.
627
628                // `Err` represents an invalid expression, so let's never assume that
629                // an invalid expressions is equal to anything.
630                | ExprKind::Err(..)
631
632                // For the time being, we always consider that two closures are unequal.
633                // This behavior may change in the future.
634                | ExprKind::Closure(..)
635                // For the time being, we always consider that two instances of InlineAsm are different.
636                // This behavior may change in the future.
637                | ExprKind::InlineAsm(_)
638                , _
639            ) => false,
640        };
641        (is_eq && (!self.should_ignore(left) || !self.should_ignore(right)))
642            || self.inner.expr_fallback.as_mut().is_some_and(|f| f(left, right))
643    }
644
645    fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
646        over(left, right, |l, r| self.eq_expr(l, r))
647    }
648
649    fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
650        left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
651    }
652
653    fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
654        match (left, right) {
655            (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_const_arg(l.as_unambig_ct(), r.as_unambig_ct()),
656            (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
657            (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty.as_unambig_ty(), r_ty.as_unambig_ty()),
658            (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
659            _ => false,
660        }
661    }
662
663    fn eq_const_arg(&mut self, left: &ConstArg<'_>, right: &ConstArg<'_>) -> bool {
664        if !self.check_ctxt(left.span.ctxt(), right.span.ctxt()) {
665            return false;
666        }
667
668        match (&left.kind, &right.kind) {
669            (ConstArgKind::Tup(l_t), ConstArgKind::Tup(r_t)) => {
670                l_t.len() == r_t.len() && l_t.iter().zip(*r_t).all(|(l_c, r_c)| self.eq_const_arg(*l_c, *r_c))
671            },
672            (ConstArgKind::Path(l_p), ConstArgKind::Path(r_p)) => self.eq_qpath(l_p, r_p),
673            (ConstArgKind::Anon(l_an), ConstArgKind::Anon(r_an)) => self.eq_body(l_an.body, r_an.body),
674            (ConstArgKind::Infer(..), ConstArgKind::Infer(..)) => true,
675            (ConstArgKind::Struct(path_a, inits_a), ConstArgKind::Struct(path_b, inits_b)) => {
676                self.eq_qpath(path_a, path_b)
677                    && inits_a
678                        .iter()
679                        .zip(*inits_b)
680                        .all(|(init_a, init_b)| self.eq_const_arg(init_a.expr, init_b.expr))
681            },
682            (ConstArgKind::TupleCall(path_a, args_a), ConstArgKind::TupleCall(path_b, args_b)) => {
683                self.eq_qpath(path_a, path_b)
684                    && args_a
685                        .iter()
686                        .zip(*args_b)
687                        .all(|(arg_a, arg_b)| self.eq_const_arg(arg_a, arg_b))
688            },
689            (ConstArgKind::Literal(kind_l), ConstArgKind::Literal(kind_r)) => kind_l == kind_r,
690            (ConstArgKind::Array(l_arr), ConstArgKind::Array(r_arr)) => {
691                l_arr.elems.len() == r_arr.elems.len()
692                && l_arr.elems.iter().zip(r_arr.elems.iter())
693                    .all(|(l_elem, r_elem)| self.eq_const_arg(l_elem, r_elem))
694            }
695            // Use explicit match for now since ConstArg is undergoing flux.
696            (
697                ConstArgKind::Path(..)
698                | ConstArgKind::Tup(..)
699                | ConstArgKind::Anon(..)
700                | ConstArgKind::TupleCall(..)
701                | ConstArgKind::Infer(..)
702                | ConstArgKind::Struct(..)
703                | ConstArgKind::Literal(..)
704                | ConstArgKind::Array(..)
705                | ConstArgKind::Error(..),
706                _,
707            ) => false,
708        }
709    }
710
711    fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
712        left.kind == right.kind
713    }
714
715    fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
716        let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
717        li.name == ri.name && self.eq_pat(lp, rp)
718    }
719
720    fn eq_pat_expr(&mut self, left: &PatExpr<'_>, right: &PatExpr<'_>) -> bool {
721        match (&left.kind, &right.kind) {
722            (
723                PatExprKind::Lit {
724                    lit: left,
725                    negated: left_neg,
726                },
727                PatExprKind::Lit {
728                    lit: right,
729                    negated: right_neg,
730                },
731            ) => left_neg == right_neg && left.node == right.node,
732            (PatExprKind::Path(left), PatExprKind::Path(right)) => self.eq_qpath(left, right),
733            (PatExprKind::Lit { .. } | PatExprKind::Path(..), _) => false,
734        }
735    }
736
737    /// Checks whether two patterns are the same.
738    fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
739        match (&left.kind, &right.kind) {
740            (PatKind::Box(l), PatKind::Box(r)) => self.eq_pat(l, r),
741            (PatKind::Struct(lp, la, ..), PatKind::Struct(rp, ra, ..)) => {
742                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
743            },
744            (PatKind::TupleStruct(lp, la, ls), PatKind::TupleStruct(rp, ra, rs)) => {
745                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
746            },
747            (PatKind::Binding(lb, li, _, lp), PatKind::Binding(rb, ri, _, rp)) => {
748                let eq = lb == rb && both(lp.as_ref(), rp.as_ref(), |l, r| self.eq_pat(l, r));
749                if eq {
750                    self.locals.insert(*li, *ri);
751                }
752                eq
753            },
754            (PatKind::Expr(l), PatKind::Expr(r)) => self.eq_pat_expr(l, r),
755            (PatKind::Tuple(l, ls), PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
756            (PatKind::Range(ls, le, li), PatKind::Range(rs, re, ri)) => {
757                both(ls.as_ref(), rs.as_ref(), |a, b| self.eq_pat_expr(a, b))
758                    && both(le.as_ref(), re.as_ref(), |a, b| self.eq_pat_expr(a, b))
759                    && (li == ri)
760            },
761            (PatKind::Ref(le, lp, lm), PatKind::Ref(re, rp, rm)) => lp == rp && lm == rm && self.eq_pat(le, re),
762            (PatKind::Slice(ls, li, le), PatKind::Slice(rs, ri, re)) => {
763                over(ls, rs, |l, r| self.eq_pat(l, r))
764                    && over(le, re, |l, r| self.eq_pat(l, r))
765                    && both(li.as_ref(), ri.as_ref(), |l, r| self.eq_pat(l, r))
766            },
767            (PatKind::Wild, PatKind::Wild) => true,
768            _ => false,
769        }
770    }
771
772    fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
773        match (left, right) {
774            (QPath::Resolved(lty, lpath), QPath::Resolved(rty, rpath)) => {
775                both(lty.as_ref(), rty.as_ref(), |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
776            },
777            (QPath::TypeRelative(lty, lseg), QPath::TypeRelative(rty, rseg)) => {
778                self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
779            },
780            _ => false,
781        }
782    }
783
784    pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
785        match (left.res, right.res) {
786            (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
787            (Res::Local(_), _) | (_, Res::Local(_)) => false,
788            (Res::Def(l_kind, l), Res::Def(r_kind, r))
789                if l_kind == r_kind
790                    && let DefKind::Const
791                    | DefKind::Static { .. }
792                    | DefKind::Fn
793                    | DefKind::TyAlias
794                    | DefKind::Use
795                    | DefKind::Mod = l_kind =>
796            {
797                (l == r || self.local_items.get(&l) == Some(&r)) && self.eq_path_segments(left.segments, right.segments)
798            },
799            _ => self.eq_path_segments(left.segments, right.segments),
800        }
801    }
802
803    fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
804        if left.parenthesized == right.parenthesized {
805            over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
806                && over(left.constraints, right.constraints, |l, r| self.eq_assoc_eq_constraint(l, r))
807        } else {
808            false
809        }
810    }
811
812    pub fn eq_path_segments<'tcx>(
813        &mut self,
814        mut left: &'tcx [PathSegment<'tcx>],
815        mut right: &'tcx [PathSegment<'tcx>],
816    ) -> bool {
817        if let PathCheck::Resolution = self.inner.path_check
818            && let Some(left_seg) = generic_path_segments(left)
819            && let Some(right_seg) = generic_path_segments(right)
820        {
821            // If we compare by resolution, then only check the last segments that could possibly have generic
822            // arguments
823            left = left_seg;
824            right = right_seg;
825        }
826
827        over(left, right, |l, r| self.eq_path_segment(l, r))
828    }
829
830    pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
831        if !self.eq_path_parameters(left.args(), right.args()) {
832            return false;
833        }
834
835        if let PathCheck::Resolution = self.inner.path_check
836            && left.res != Res::Err
837            && right.res != Res::Err
838        {
839            left.res == right.res
840        } else {
841            // The == of idents doesn't work with different contexts,
842            // we have to be explicit about hygiene
843            left.ident.name == right.ident.name
844        }
845    }
846
847    pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
848        match (&left.kind, &right.kind) {
849            (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
850            (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
851            (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
852            (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
853                l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
854            },
855            (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
856            (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
857            (TyKind::Infer(()), TyKind::Infer(())) => true,
858            _ => false,
859        }
860    }
861
862    /// Checks whether two constraints designate the same equality constraint (same name, and same
863    /// type or const).
864    fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
865        // TODO: this could be extended to check for identical associated item bound constraints
866        left.ident.name == right.ident.name
867            && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
868                || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
869    }
870
871    fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> bool {
872        if self.left_ctxt == left && self.right_ctxt == right {
873            return true;
874        } else if self.left_ctxt == left || self.right_ctxt == right {
875            // Only one context has changed. This can only happen if the two nodes are written differently.
876            return false;
877        } else if left != SyntaxContext::root() {
878            let mut left_data = left.outer_expn_data();
879            let mut right_data = right.outer_expn_data();
880            loop {
881                use TokenKind::{BlockComment, LineComment, Whitespace};
882                if left_data.macro_def_id != right_data.macro_def_id
883                    || (matches!(
884                        left_data.kind,
885                        ExpnKind::Macro(MacroKind::Bang, name)
886                        if name == sym::cfg || name == sym::option_env
887                    ) && !eq_span_tokens(self.inner.cx, left_data.call_site, right_data.call_site, |t| {
888                        !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. })
889                    }))
890                {
891                    // Either a different chain of macro calls, or different arguments to the `cfg` macro.
892                    return false;
893                }
894                let left_ctxt = left_data.call_site.ctxt();
895                let right_ctxt = right_data.call_site.ctxt();
896                if left_ctxt == SyntaxContext::root() && right_ctxt == SyntaxContext::root() {
897                    break;
898                }
899                if left_ctxt == SyntaxContext::root() || right_ctxt == SyntaxContext::root() {
900                    // Different lengths for the expansion stack. This can only happen if nodes are written differently,
901                    // or shouldn't be compared to start with.
902                    return false;
903                }
904                left_data = left_ctxt.outer_expn_data();
905                right_data = right_ctxt.outer_expn_data();
906            }
907        }
908        self.left_ctxt = left;
909        self.right_ctxt = right;
910        true
911    }
912}
913
914/// Some simple reductions like `{ return }` => `return`
915fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
916    if let ExprKind::Block(block, _) = kind {
917        match (block.stmts, block.expr) {
918            // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
919            // block with an empty span.
920            ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
921            // `{}` => `()`
922            ([], None)
923                if block.span.check_source_text(cx, |src| {
924                    tokenize(src, FrontmatterAllowed::No)
925                        .map(|t| t.kind)
926                        .filter(|t| {
927                            !matches!(
928                                t,
929                                TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
930                            )
931                        })
932                        .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
933                }) =>
934            {
935                &ExprKind::Tup(&[])
936            },
937            ([], Some(expr)) => match expr.kind {
938                // `{ return .. }` => `return ..`
939                ExprKind::Ret(..) => &expr.kind,
940                _ => kind,
941            },
942            ([stmt], None) => match stmt.kind {
943                StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
944                    // `{ return ..; }` => `return ..`
945                    ExprKind::Ret(..) => &expr.kind,
946                    _ => kind,
947                },
948                _ => kind,
949            },
950            _ => kind,
951        }
952    } else {
953        kind
954    }
955}
956
957fn swap_binop<'a>(
958    binop: BinOpKind,
959    lhs: &'a Expr<'a>,
960    rhs: &'a Expr<'a>,
961) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
962    match binop {
963        BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
964            Some((binop, rhs, lhs))
965        },
966        BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
967        BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
968        BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
969        BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
970        BinOpKind::Mul // Not always commutative, e.g. with matrices. See issue #5698
971        | BinOpKind::Shl
972        | BinOpKind::Shr
973        | BinOpKind::Rem
974        | BinOpKind::Sub
975        | BinOpKind::Div
976        | BinOpKind::And
977        | BinOpKind::Or => None,
978    }
979}
980
981/// Checks if the two `Option`s are both `None` or some equal values as per
982/// `eq_fn`.
983pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
984    l.as_ref()
985        .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
986}
987
988/// Checks if the two `Option`s are both `Some` and pass the predicate function.
989pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
990    l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
991}
992
993/// Checks if two slices are equal as per `eq_fn`.
994pub fn over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
995    left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
996}
997
998/// Counts how many elements of the slices are equal as per `eq_fn`.
999pub fn count_eq<X: Sized>(
1000    left: &mut dyn Iterator<Item = X>,
1001    right: &mut dyn Iterator<Item = X>,
1002    mut eq_fn: impl FnMut(&X, &X) -> bool,
1003) -> usize {
1004    left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
1005}
1006
1007/// Checks if two expressions evaluate to the same value, and don't contain any side effects.
1008pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
1009    SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
1010}
1011
1012/// Returns the segments of a path that might have generic parameters.
1013/// Usually just the last segment for free items, except for when the path resolves to an associated
1014/// item, in which case it is the last two
1015fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
1016    match segments.last()?.res {
1017        Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => {
1018            // <Ty as module::Trait<T>>::assoc::<U>
1019            //        ^^^^^^^^^^^^^^^^   ^^^^^^^^^^ segments: [module, Trait<T>, assoc<U>]
1020            Some(&segments[segments.len().checked_sub(2)?..])
1021        },
1022        Res::Err => None,
1023        _ => Some(slice::from_ref(segments.last()?)),
1024    }
1025}
1026
1027/// Type used to hash an ast element. This is different from the `Hash` trait
1028/// on ast types as this
1029/// trait would consider IDs and spans.
1030///
1031/// All expressions kind are hashed, but some might have a weaker hash.
1032pub struct SpanlessHash<'a, 'tcx> {
1033    /// Context used to evaluate constant expressions.
1034    cx: &'a LateContext<'tcx>,
1035    maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
1036    s: FxHasher,
1037    path_check: PathCheck,
1038}
1039
1040impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
1041    pub fn new(cx: &'a LateContext<'tcx>) -> Self {
1042        Self {
1043            cx,
1044            maybe_typeck_results: cx.maybe_typeck_results(),
1045            s: FxHasher::default(),
1046            path_check: PathCheck::default(),
1047        }
1048    }
1049
1050    /// Check paths by their resolution instead of exact equality. See [`PathCheck`] for more
1051    /// details.
1052    #[must_use]
1053    pub fn paths_by_resolution(self) -> Self {
1054        Self {
1055            path_check: PathCheck::Resolution,
1056            ..self
1057        }
1058    }
1059
1060    pub fn finish(self) -> u64 {
1061        self.s.finish()
1062    }
1063
1064    pub fn hash_block(&mut self, b: &Block<'_>) {
1065        for s in b.stmts {
1066            self.hash_stmt(s);
1067        }
1068
1069        if let Some(e) = b.expr {
1070            self.hash_expr(e);
1071        }
1072
1073        std::mem::discriminant(&b.rules).hash(&mut self.s);
1074    }
1075
1076    #[expect(clippy::too_many_lines)]
1077    pub fn hash_expr(&mut self, e: &Expr<'_>) {
1078        let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
1079            ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_local(e, e.span.ctxt())
1080        });
1081
1082        // const hashing may result in the same hash as some unrelated node, so add a sort of
1083        // discriminant depending on which path we're choosing next
1084        simple_const.hash(&mut self.s);
1085        if simple_const.is_some() {
1086            return;
1087        }
1088
1089        std::mem::discriminant(&e.kind).hash(&mut self.s);
1090
1091        match &e.kind {
1092            ExprKind::AddrOf(kind, m, e) => {
1093                std::mem::discriminant(kind).hash(&mut self.s);
1094                m.hash(&mut self.s);
1095                self.hash_expr(e);
1096            },
1097            ExprKind::Continue(i) => {
1098                if let Some(i) = i.label {
1099                    self.hash_name(i.ident.name);
1100                }
1101            },
1102            ExprKind::Array(v) => {
1103                self.hash_exprs(v);
1104            },
1105            ExprKind::Assign(l, r, _) => {
1106                self.hash_expr(l);
1107                self.hash_expr(r);
1108            },
1109            ExprKind::AssignOp(o, l, r) => {
1110                std::mem::discriminant(&o.node).hash(&mut self.s);
1111                self.hash_expr(l);
1112                self.hash_expr(r);
1113            },
1114            ExprKind::Become(f) => {
1115                self.hash_expr(f);
1116            },
1117            ExprKind::Block(b, _) => {
1118                self.hash_block(b);
1119            },
1120            ExprKind::Binary(op, l, r) => {
1121                std::mem::discriminant(&op.node).hash(&mut self.s);
1122                self.hash_expr(l);
1123                self.hash_expr(r);
1124            },
1125            ExprKind::Break(i, j) => {
1126                if let Some(i) = i.label {
1127                    self.hash_name(i.ident.name);
1128                }
1129                if let Some(j) = j {
1130                    self.hash_expr(j);
1131                }
1132            },
1133            ExprKind::Call(fun, args) => {
1134                self.hash_expr(fun);
1135                self.hash_exprs(args);
1136            },
1137            ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
1138                self.hash_expr(e);
1139                self.hash_ty(ty);
1140            },
1141            ExprKind::Closure(Closure {
1142                capture_clause, body, ..
1143            }) => {
1144                std::mem::discriminant(capture_clause).hash(&mut self.s);
1145                // closures inherit TypeckResults
1146                self.hash_expr(self.cx.tcx.hir_body(*body).value);
1147            },
1148            ExprKind::ConstBlock(l_id) => {
1149                self.hash_body(l_id.body);
1150            },
1151            ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
1152                self.hash_expr(e);
1153            },
1154            ExprKind::Field(e, f) => {
1155                self.hash_expr(e);
1156                self.hash_name(f.name);
1157            },
1158            ExprKind::Index(a, i, _) => {
1159                self.hash_expr(a);
1160                self.hash_expr(i);
1161            },
1162            ExprKind::InlineAsm(asm) => {
1163                for piece in asm.template {
1164                    match piece {
1165                        InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
1166                        InlineAsmTemplatePiece::Placeholder {
1167                            operand_idx,
1168                            modifier,
1169                            span: _,
1170                        } => {
1171                            operand_idx.hash(&mut self.s);
1172                            modifier.hash(&mut self.s);
1173                        },
1174                    }
1175                }
1176                asm.options.hash(&mut self.s);
1177                for (op, _op_sp) in asm.operands {
1178                    match op {
1179                        InlineAsmOperand::In { reg, expr } => {
1180                            reg.hash(&mut self.s);
1181                            self.hash_expr(expr);
1182                        },
1183                        InlineAsmOperand::Out { reg, late, expr } => {
1184                            reg.hash(&mut self.s);
1185                            late.hash(&mut self.s);
1186                            if let Some(expr) = expr {
1187                                self.hash_expr(expr);
1188                            }
1189                        },
1190                        InlineAsmOperand::InOut { reg, late, expr } => {
1191                            reg.hash(&mut self.s);
1192                            late.hash(&mut self.s);
1193                            self.hash_expr(expr);
1194                        },
1195                        InlineAsmOperand::SplitInOut {
1196                            reg,
1197                            late,
1198                            in_expr,
1199                            out_expr,
1200                        } => {
1201                            reg.hash(&mut self.s);
1202                            late.hash(&mut self.s);
1203                            self.hash_expr(in_expr);
1204                            if let Some(out_expr) = out_expr {
1205                                self.hash_expr(out_expr);
1206                            }
1207                        },
1208                        InlineAsmOperand::SymFn { expr } => {
1209                            self.hash_expr(expr);
1210                        },
1211                        InlineAsmOperand::Const { anon_const } => {
1212                            self.hash_body(anon_const.body);
1213                        },
1214                        InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
1215                        InlineAsmOperand::Label { block } => self.hash_block(block),
1216                    }
1217                }
1218            },
1219            ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
1220                self.hash_expr(init);
1221                if let Some(ty) = ty {
1222                    self.hash_ty(ty);
1223                }
1224                self.hash_pat(pat);
1225            },
1226            ExprKind::Lit(l) => {
1227                l.node.hash(&mut self.s);
1228            },
1229            ExprKind::Loop(b, i, ..) => {
1230                self.hash_block(b);
1231                if let Some(i) = i {
1232                    self.hash_name(i.ident.name);
1233                }
1234            },
1235            ExprKind::If(cond, then, else_opt) => {
1236                self.hash_expr(cond);
1237                self.hash_expr(then);
1238                if let Some(e) = else_opt {
1239                    self.hash_expr(e);
1240                }
1241            },
1242            ExprKind::Match(scrutinee, arms, _) => {
1243                self.hash_expr(scrutinee);
1244
1245                for arm in *arms {
1246                    self.hash_pat(arm.pat);
1247                    if let Some(e) = arm.guard {
1248                        self.hash_expr(e);
1249                    }
1250                    self.hash_expr(arm.body);
1251                }
1252            },
1253            ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1254                self.hash_name(path.ident.name);
1255                self.hash_expr(receiver);
1256                self.hash_exprs(args);
1257            },
1258            ExprKind::OffsetOf(container, fields) => {
1259                self.hash_ty(container);
1260                for field in *fields {
1261                    self.hash_name(field.name);
1262                }
1263            },
1264            ExprKind::Path(qpath) => {
1265                self.hash_qpath(qpath);
1266            },
1267            ExprKind::Repeat(e, len) => {
1268                self.hash_expr(e);
1269                self.hash_const_arg(len);
1270            },
1271            ExprKind::Ret(e) => {
1272                if let Some(e) = e {
1273                    self.hash_expr(e);
1274                }
1275            },
1276            ExprKind::Struct(path, fields, expr) => {
1277                self.hash_qpath(path);
1278
1279                for f in *fields {
1280                    self.hash_name(f.ident.name);
1281                    self.hash_expr(f.expr);
1282                }
1283
1284                if let StructTailExpr::Base(e) = expr {
1285                    self.hash_expr(e);
1286                }
1287            },
1288            ExprKind::Tup(tup) => {
1289                self.hash_exprs(tup);
1290            },
1291            ExprKind::Use(expr, _) => {
1292                self.hash_expr(expr);
1293            },
1294            ExprKind::Unary(l_op, le) => {
1295                std::mem::discriminant(l_op).hash(&mut self.s);
1296                self.hash_expr(le);
1297            },
1298            ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1299                std::mem::discriminant(kind).hash(&mut self.s);
1300                self.hash_expr(expr);
1301                if let Some(ty) = ty {
1302                    self.hash_ty(ty);
1303                }
1304            },
1305            ExprKind::Err(_) => {},
1306        }
1307    }
1308
1309    pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1310        for e in e {
1311            self.hash_expr(e);
1312        }
1313    }
1314
1315    pub fn hash_name(&mut self, n: Symbol) {
1316        n.hash(&mut self.s);
1317    }
1318
1319    pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1320        match p {
1321            QPath::Resolved(_, path) => {
1322                self.hash_path(path);
1323            },
1324            QPath::TypeRelative(_, path) => {
1325                self.hash_name(path.ident.name);
1326            },
1327        }
1328        // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
1329    }
1330
1331    pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1332        std::mem::discriminant(&lit.kind).hash(&mut self.s);
1333        match &lit.kind {
1334            PatExprKind::Lit { lit, negated } => {
1335                lit.node.hash(&mut self.s);
1336                negated.hash(&mut self.s);
1337            },
1338            PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1339        }
1340    }
1341
1342    pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1343        std::mem::discriminant(&pat.kind).hash(&mut self.s);
1344        match pat.kind {
1345            TyPatKind::Range(s, e) => {
1346                self.hash_const_arg(s);
1347                self.hash_const_arg(e);
1348            },
1349            TyPatKind::Or(variants) => {
1350                for variant in variants {
1351                    self.hash_ty_pat(variant);
1352                }
1353            },
1354            TyPatKind::NotNull | TyPatKind::Err(_) => {},
1355        }
1356    }
1357
1358    pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1359        std::mem::discriminant(&pat.kind).hash(&mut self.s);
1360        match &pat.kind {
1361            PatKind::Missing => unreachable!(),
1362            PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1363                std::mem::discriminant(by_ref).hash(&mut self.s);
1364                if let ByRef::Yes(pi, mu) = by_ref {
1365                    std::mem::discriminant(pi).hash(&mut self.s);
1366                    std::mem::discriminant(mu).hash(&mut self.s);
1367                }
1368                std::mem::discriminant(mutability).hash(&mut self.s);
1369                if let Some(pat) = pat {
1370                    self.hash_pat(pat);
1371                }
1372            },
1373            PatKind::Box(pat) | PatKind::Deref(pat) => self.hash_pat(pat),
1374            PatKind::Expr(expr) => self.hash_pat_expr(expr),
1375            PatKind::Or(pats) => {
1376                for pat in *pats {
1377                    self.hash_pat(pat);
1378                }
1379            },
1380            PatKind::Range(s, e, i) => {
1381                if let Some(s) = s {
1382                    self.hash_pat_expr(s);
1383                }
1384                if let Some(e) = e {
1385                    self.hash_pat_expr(e);
1386                }
1387                std::mem::discriminant(i).hash(&mut self.s);
1388            },
1389            PatKind::Ref(pat, pi, mu) => {
1390                self.hash_pat(pat);
1391                std::mem::discriminant(pi).hash(&mut self.s);
1392                std::mem::discriminant(mu).hash(&mut self.s);
1393            },
1394            PatKind::Guard(pat, guard) => {
1395                self.hash_pat(pat);
1396                self.hash_expr(guard);
1397            },
1398            PatKind::Slice(l, m, r) => {
1399                for pat in *l {
1400                    self.hash_pat(pat);
1401                }
1402                if let Some(pat) = m {
1403                    self.hash_pat(pat);
1404                }
1405                for pat in *r {
1406                    self.hash_pat(pat);
1407                }
1408            },
1409            PatKind::Struct(qpath, fields, e) => {
1410                self.hash_qpath(qpath);
1411                for f in *fields {
1412                    self.hash_name(f.ident.name);
1413                    self.hash_pat(f.pat);
1414                }
1415                e.hash(&mut self.s);
1416            },
1417            PatKind::Tuple(pats, e) => {
1418                for pat in *pats {
1419                    self.hash_pat(pat);
1420                }
1421                e.hash(&mut self.s);
1422            },
1423            PatKind::TupleStruct(qpath, pats, e) => {
1424                self.hash_qpath(qpath);
1425                for pat in *pats {
1426                    self.hash_pat(pat);
1427                }
1428                e.hash(&mut self.s);
1429            },
1430            PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1431        }
1432    }
1433
1434    pub fn hash_path(&mut self, path: &Path<'_>) {
1435        match path.res {
1436            // constant hash since equality is dependant on inter-expression context
1437            // e.g. The expressions `if let Some(x) = foo() {}` and `if let Some(y) = foo() {}` are considered equal
1438            // even though the binding names are different and they have different `HirId`s.
1439            Res::Local(_) => 1_usize.hash(&mut self.s),
1440            _ => {
1441                if let PathCheck::Resolution = self.path_check
1442                    && let [.., last] = path.segments
1443                    && let Some(segments) = generic_path_segments(path.segments)
1444                {
1445                    for seg in segments {
1446                        self.hash_generic_args(seg.args().args);
1447                    }
1448                    last.res.hash(&mut self.s);
1449                } else {
1450                    for seg in path.segments {
1451                        self.hash_name(seg.ident.name);
1452                        self.hash_generic_args(seg.args().args);
1453                    }
1454                }
1455            },
1456        }
1457    }
1458
1459    pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1460        let TraitBoundModifiers { constness, polarity } = modifiers;
1461        std::mem::discriminant(&polarity).hash(&mut self.s);
1462        std::mem::discriminant(&constness).hash(&mut self.s);
1463    }
1464
1465    pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1466        std::mem::discriminant(&b.kind).hash(&mut self.s);
1467
1468        match &b.kind {
1469            StmtKind::Let(local) => {
1470                self.hash_pat(local.pat);
1471                if let Some(init) = local.init {
1472                    self.hash_expr(init);
1473                }
1474                if let Some(els) = local.els {
1475                    self.hash_block(els);
1476                }
1477            },
1478            StmtKind::Item(..) => {},
1479            StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1480                self.hash_expr(expr);
1481            },
1482        }
1483    }
1484
1485    pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1486        lifetime.ident.name.hash(&mut self.s);
1487        std::mem::discriminant(&lifetime.kind).hash(&mut self.s);
1488        if let LifetimeKind::Param(param_id) = lifetime.kind {
1489            param_id.hash(&mut self.s);
1490        }
1491    }
1492
1493    pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1494        std::mem::discriminant(&ty.kind).hash(&mut self.s);
1495        self.hash_tykind(&ty.kind);
1496    }
1497
1498    pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1499        match ty {
1500            TyKind::Slice(ty) => {
1501                self.hash_ty(ty);
1502            },
1503            TyKind::Array(ty, len) => {
1504                self.hash_ty(ty);
1505                self.hash_const_arg(len);
1506            },
1507            TyKind::Pat(ty, pat) => {
1508                self.hash_ty(ty);
1509                self.hash_ty_pat(pat);
1510            },
1511            TyKind::Ptr(mut_ty) => {
1512                self.hash_ty(mut_ty.ty);
1513                mut_ty.mutbl.hash(&mut self.s);
1514            },
1515            TyKind::Ref(lifetime, mut_ty) => {
1516                self.hash_lifetime(lifetime);
1517                self.hash_ty(mut_ty.ty);
1518                mut_ty.mutbl.hash(&mut self.s);
1519            },
1520            TyKind::FnPtr(fn_ptr) => {
1521                fn_ptr.safety.hash(&mut self.s);
1522                fn_ptr.abi.hash(&mut self.s);
1523                for arg in fn_ptr.decl.inputs {
1524                    self.hash_ty(arg);
1525                }
1526                std::mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1527                match fn_ptr.decl.output {
1528                    FnRetTy::DefaultReturn(_) => {},
1529                    FnRetTy::Return(ty) => {
1530                        self.hash_ty(ty);
1531                    },
1532                }
1533                fn_ptr.decl.c_variadic.hash(&mut self.s);
1534            },
1535            TyKind::Tup(ty_list) => {
1536                for ty in *ty_list {
1537                    self.hash_ty(ty);
1538                }
1539            },
1540            TyKind::Path(qpath) => self.hash_qpath(qpath),
1541            TyKind::TraitObject(_, lifetime) => {
1542                self.hash_lifetime(lifetime);
1543            },
1544            TyKind::UnsafeBinder(binder) => {
1545                self.hash_ty(binder.inner_ty);
1546            },
1547            TyKind::Err(_)
1548            | TyKind::Infer(())
1549            | TyKind::Never
1550            | TyKind::InferDelegation(..)
1551            | TyKind::OpaqueDef(_)
1552            | TyKind::TraitAscription(_) => {},
1553        }
1554    }
1555
1556    pub fn hash_body(&mut self, body_id: BodyId) {
1557        // swap out TypeckResults when hashing a body
1558        let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1559        self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1560        self.maybe_typeck_results = old_maybe_typeck_results;
1561    }
1562
1563    fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1564        match &const_arg.kind {
1565            ConstArgKind::Tup(tup) => {
1566                for arg in *tup {
1567                    self.hash_const_arg(*arg);
1568                }
1569            },
1570            ConstArgKind::Path(path) => self.hash_qpath(path),
1571            ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1572            ConstArgKind::Struct(path, inits) => {
1573                self.hash_qpath(path);
1574                for init in *inits {
1575                    self.hash_const_arg(init.expr);
1576                }
1577            },
1578            ConstArgKind::TupleCall(path, args) => {
1579                self.hash_qpath(path);
1580                for arg in *args {
1581                    self.hash_const_arg(arg);
1582                }
1583            },
1584            ConstArgKind::Array(array_expr) => {
1585                for elem in array_expr.elems {
1586                    self.hash_const_arg(elem);
1587                }
1588            },
1589            ConstArgKind::Infer(..) | ConstArgKind::Error(..) => {},
1590            ConstArgKind::Literal(lit) => lit.hash(&mut self.s),
1591        }
1592    }
1593
1594    fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1595        for arg in arg_list {
1596            match arg {
1597                GenericArg::Lifetime(l) => self.hash_lifetime(l),
1598                GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1599                GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1600                GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1601            }
1602        }
1603    }
1604}
1605
1606pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1607    let mut h = SpanlessHash::new(cx);
1608    h.hash_stmt(s);
1609    h.finish()
1610}
1611
1612pub fn is_bool(ty: &Ty<'_>) -> bool {
1613    if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1614        matches!(path.res, Res::PrimTy(PrimTy::Bool))
1615    } else {
1616        false
1617    }
1618}
1619
1620pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1621    let mut h = SpanlessHash::new(cx);
1622    h.hash_expr(e);
1623    h.finish()
1624}
1625
1626fn eq_span_tokens(
1627    cx: &LateContext<'_>,
1628    left: impl SpanRange,
1629    right: impl SpanRange,
1630    pred: impl Fn(TokenKind) -> bool,
1631) -> bool {
1632    fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1633        if let Some(lsrc) = left.get_source_range(cx)
1634            && let Some(lsrc) = lsrc.as_str()
1635            && let Some(rsrc) = right.get_source_range(cx)
1636            && let Some(rsrc) = rsrc.as_str()
1637        {
1638            let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1639            let map = |(_, source, _)| source;
1640
1641            let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1642            let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1643            ltok.eq(rtok)
1644        } else {
1645            // Unable to access the source. Conservatively assume the blocks aren't equal.
1646            false
1647        }
1648    }
1649    f(cx, left.into_range(), right.into_range(), pred)
1650}
1651
1652/// Returns true if the expression contains ambiguous literals (unsuffixed float or int literals)
1653/// that could be interpreted as either f32/f64 or i32/i64 depending on context.
1654pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1655    match expr.kind {
1656        ExprKind::Path(ref qpath) => {
1657            if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1658                && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1659                && local.ty.is_none()
1660                && let Some(init) = local.init
1661            {
1662                return has_ambiguous_literal_in_expr(cx, init);
1663            }
1664            false
1665        },
1666        ExprKind::Lit(lit) => matches!(
1667            lit.node,
1668            ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1669        ),
1670
1671        ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1672
1673        ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1674            has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1675        },
1676
1677        ExprKind::Unary(_, e)
1678        | ExprKind::Cast(e, _)
1679        | ExprKind::Type(e, _)
1680        | ExprKind::DropTemps(e)
1681        | ExprKind::AddrOf(_, _, e)
1682        | ExprKind::Field(e, _)
1683        | ExprKind::Index(e, _, _)
1684        | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1685
1686        ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1687            has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1688        },
1689
1690        ExprKind::Closure(Closure { body, .. }) => {
1691            let body = cx.tcx.hir_body(*body);
1692            let closure_expr = crate::peel_blocks(body.value);
1693            has_ambiguous_literal_in_expr(cx, closure_expr)
1694        },
1695
1696        ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1697
1698        ExprKind::If(cond, then_expr, else_expr) => {
1699            has_ambiguous_literal_in_expr(cx, cond)
1700                || has_ambiguous_literal_in_expr(cx, then_expr)
1701                || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1702        },
1703
1704        ExprKind::Match(scrutinee, arms, _) => {
1705            has_ambiguous_literal_in_expr(cx, scrutinee)
1706                || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1707        },
1708
1709        ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1710
1711        ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1712            opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1713        },
1714
1715        _ => false,
1716    }
1717}