Skip to main content

clippy_utils/
hir_utils.rs

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