Skip to main content

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::{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, Hasher};
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.maybe_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::Box(l), PatKind::Box(r)) => self.eq_pat(l, r),
792            (PatKind::Struct(lp, la, ..), PatKind::Struct(rp, ra, ..)) => {
793                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
794            },
795            (PatKind::TupleStruct(lp, la, ls), PatKind::TupleStruct(rp, ra, rs)) => {
796                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
797            },
798            (PatKind::Binding(lb, li, _, lp), PatKind::Binding(rb, ri, _, rp)) => {
799                let eq = lb == rb && both(lp.as_ref(), rp.as_ref(), |l, r| self.eq_pat(l, r));
800                if eq {
801                    self.locals.insert(*li, *ri);
802                }
803                eq
804            },
805            (PatKind::Expr(l), PatKind::Expr(r)) => self.eq_pat_expr(l, r),
806            (PatKind::Tuple(l, ls), PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
807            (PatKind::Range(ls, le, li), PatKind::Range(rs, re, ri)) => {
808                both(ls.as_ref(), rs.as_ref(), |a, b| self.eq_pat_expr(a, b))
809                    && both(le.as_ref(), re.as_ref(), |a, b| self.eq_pat_expr(a, b))
810                    && (li == ri)
811            },
812            (PatKind::Ref(le, lp, lm), PatKind::Ref(re, rp, rm)) => lp == rp && lm == rm && self.eq_pat(le, re),
813            (PatKind::Slice(ls, li, le), PatKind::Slice(rs, ri, re)) => {
814                over(ls, rs, |l, r| self.eq_pat(l, r))
815                    && over(le, re, |l, r| self.eq_pat(l, r))
816                    && both(li.as_ref(), ri.as_ref(), |l, r| self.eq_pat(l, r))
817            },
818            (PatKind::Wild, PatKind::Wild) => true,
819            _ => false,
820        }
821    }
822
823    fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
824        match (left, right) {
825            (QPath::Resolved(lty, lpath), QPath::Resolved(rty, rpath)) => {
826                both(lty.as_ref(), rty.as_ref(), |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
827            },
828            (QPath::TypeRelative(lty, lseg), QPath::TypeRelative(rty, rseg)) => {
829                self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
830            },
831            _ => false,
832        }
833    }
834
835    pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
836        match (left.res, right.res) {
837            (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
838            (Res::Local(_), _) | (_, Res::Local(_)) => false,
839            (Res::Def(l_kind, l), Res::Def(r_kind, r))
840                if l_kind == r_kind
841                    && let DefKind::Const { .. }
842                    | DefKind::Static { .. }
843                    | DefKind::Fn
844                    | DefKind::TyAlias
845                    | DefKind::Use
846                    | DefKind::Mod = l_kind =>
847            {
848                (l == r || self.local_items.get(&l) == Some(&r)) && self.eq_path_segments(left.segments, right.segments)
849            },
850            _ => self.eq_path_segments(left.segments, right.segments),
851        }
852    }
853
854    fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
855        if left.parenthesized == right.parenthesized {
856            over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
857                && over(left.constraints, right.constraints, |l, r| self.eq_assoc_eq_constraint(l, r))
858        } else {
859            false
860        }
861    }
862
863    pub fn eq_path_segments<'tcx>(
864        &mut self,
865        mut left: &'tcx [PathSegment<'tcx>],
866        mut right: &'tcx [PathSegment<'tcx>],
867    ) -> bool {
868        if let PathCheck::Resolution = self.inner.path_check
869            && let Some(left_seg) = generic_path_segments(left)
870            && let Some(right_seg) = generic_path_segments(right)
871        {
872            // If we compare by resolution, then only check the last segments that could possibly have generic
873            // arguments
874            left = left_seg;
875            right = right_seg;
876        }
877
878        over(left, right, |l, r| self.eq_path_segment(l, r))
879    }
880
881    pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
882        if !self.eq_path_parameters(left.args(), right.args()) {
883            return false;
884        }
885
886        if let PathCheck::Resolution = self.inner.path_check
887            && left.res != Res::Err
888            && right.res != Res::Err
889        {
890            left.res == right.res
891        } else {
892            // The == of idents doesn't work with different contexts,
893            // we have to be explicit about hygiene
894            left.ident.name == right.ident.name
895        }
896    }
897
898    pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
899        match (&left.kind, &right.kind) {
900            (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
901            (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
902            (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
903            (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
904                l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
905            },
906            (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
907            (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
908            (TyKind::Infer(()), TyKind::Infer(())) => true,
909            _ => false,
910        }
911    }
912
913    /// Checks whether two constraints designate the same equality constraint (same name, and same
914    /// type or const).
915    fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
916        // TODO: this could be extended to check for identical associated item bound constraints
917        left.ident.name == right.ident.name
918            && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
919                || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
920    }
921
922    /// Checks whether either operand is within a macro context, and if so, whether the macro calls
923    /// are equal.
924    fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> Option<bool> {
925        let prev_left = mem::replace(&mut self.prev_left_ctxt, left);
926        let prev_right = mem::replace(&mut self.prev_right_ctxt, right);
927
928        if left == self.eval_ctxt && right == self.eval_ctxt {
929            None
930        } else if left == prev_left && right == prev_right {
931            // Same as the previous context, no need to recheck anything
932            Some(true)
933        } else if left == prev_left
934            || right == prev_right
935            || left == self.eval_ctxt
936            || right == self.eval_ctxt
937            || left.is_root()
938            || right.is_root()
939        {
940            // Either only one context changed, or at least one context is a parent of the
941            // evaluation context.
942            // Unfortunately we can't get a span of a metavariable so we have to treat the
943            // second case as unequal.
944            Some(false)
945        } else {
946            // Walk each context in lockstep up to the evaluation context checking that each
947            // expansion has the same kind.
948            let mut left_data = left.outer_expn_data();
949            let mut right_data = right.outer_expn_data();
950            loop {
951                use TokenKind::{BlockComment, LineComment, Whitespace};
952                if left_data.macro_def_id != right_data.macro_def_id || left_data.kind != right_data.kind {
953                    return Some(false);
954                }
955                let left = left_data.call_site.ctxt();
956                let right = right_data.call_site.ctxt();
957                if left == self.eval_ctxt && right == self.eval_ctxt {
958                    // Finally if the outermost expansion is a macro call, check if the
959                    // tokens are the same.
960                    if let ExpnKind::Macro(MacroKind::Bang, _) = left_data.kind {
961                        return Some(eq_span_tokens(
962                            self.inner.cx,
963                            left_data.call_site,
964                            right_data.call_site,
965                            |t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. }),
966                        ));
967                    }
968                    return Some(true);
969                }
970                if left == prev_left && right == prev_right {
971                    return Some(true);
972                }
973                if left == prev_left
974                    || right == prev_right
975                    || left == self.eval_ctxt
976                    || right == self.eval_ctxt
977                    || left.is_root()
978                    || right.is_root()
979                {
980                    // Either there's a different number of expansions, or at least one context is
981                    // a parent of the evaluation context.
982                    return Some(false);
983                }
984                left_data = left.outer_expn_data();
985                right_data = right.outer_expn_data();
986            }
987        }
988    }
989
990    fn swap_binop<'a>(
991        &self,
992        binop: BinOpKind,
993        lhs: &'a Expr<'a>,
994        rhs: &'a Expr<'a>,
995    ) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
996        match binop {
997            // `==` and `!=`, are commutative
998            BinOpKind::Eq | BinOpKind::Ne => Some((binop, rhs, lhs)),
999            // Comparisons can be reversed
1000            BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
1001            BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
1002            BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
1003            BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
1004            // Non-commutative operators
1005            BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Rem | BinOpKind::Sub | BinOpKind::Div => None,
1006            // We know that those operators are commutative for primitive types,
1007            // and we don't assume anything for other types
1008            BinOpKind::Mul
1009            | BinOpKind::Add
1010            | BinOpKind::And
1011            | BinOpKind::Or
1012            | BinOpKind::BitAnd
1013            | BinOpKind::BitXor
1014            | BinOpKind::BitOr => self.inner.maybe_typeck_results.and_then(|(typeck_lhs, _)| {
1015                typeck_lhs
1016                    .expr_ty_adjusted(lhs)
1017                    .peel_refs()
1018                    .is_primitive()
1019                    .then_some((binop, rhs, lhs))
1020            }),
1021        }
1022    }
1023}
1024
1025/// Some simple reductions like `{ return }` => `return`
1026fn reduce_exprkind<'hir>(
1027    cx: &LateContext<'_>,
1028    eval_ctxt: SyntaxContext,
1029    kind: &'hir ExprKind<'hir>,
1030) -> &'hir ExprKind<'hir> {
1031    if let ExprKind::Block(block, _) = kind {
1032        match (block.stmts, block.expr) {
1033            // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
1034            // block with an empty span.
1035            ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
1036            // `{}` => `()`
1037            ([], None)
1038                if block.span.ctxt() != eval_ctxt
1039                    || block.span.check_source_text(cx, |src| {
1040                        tokenize(src, FrontmatterAllowed::No)
1041                            .map(|t| t.kind)
1042                            .filter(|t| {
1043                                !matches!(
1044                                    t,
1045                                    TokenKind::LineComment { .. }
1046                                        | TokenKind::BlockComment { .. }
1047                                        | TokenKind::Whitespace
1048                                )
1049                            })
1050                            .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
1051                    }) =>
1052            {
1053                &ExprKind::Tup(&[])
1054            },
1055            ([], Some(expr)) => match expr.kind {
1056                // `{ return .. }` => `return ..`
1057                ExprKind::Ret(..) => &expr.kind,
1058                _ => kind,
1059            },
1060            ([stmt], None) => match stmt.kind {
1061                StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
1062                    // `{ return ..; }` => `return ..`
1063                    ExprKind::Ret(..) => &expr.kind,
1064                    _ => kind,
1065                },
1066                _ => kind,
1067            },
1068            _ => kind,
1069        }
1070    } else {
1071        kind
1072    }
1073}
1074
1075/// Checks if the two `Option`s are both `None` or some equal values as per
1076/// `eq_fn`.
1077pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
1078    l.as_ref()
1079        .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
1080}
1081
1082/// Checks if the two `Option`s are both `Some` and pass the predicate function.
1083pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
1084    l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
1085}
1086
1087/// Checks if two slices are equal as per `eq_fn`.
1088pub fn over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
1089    left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
1090}
1091
1092/// Counts how many elements of the slices are equal as per `eq_fn`.
1093pub fn count_eq<X: Sized>(
1094    left: &mut dyn Iterator<Item = X>,
1095    right: &mut dyn Iterator<Item = X>,
1096    mut eq_fn: impl FnMut(&X, &X) -> bool,
1097) -> usize {
1098    left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
1099}
1100
1101/// Checks if two expressions evaluate to the same value, and don't contain any side effects.
1102///
1103/// The context argument is the context used to view the two expressions. e.g. when comparing the
1104/// two arguments in `f(m!(1), m!(2))` the context of the call expression should be used. This is
1105/// needed to handle the case where two macros expand to the same thing, but the arguments are
1106/// different.
1107pub fn eq_expr_value(cx: &LateContext<'_>, ctxt: SyntaxContext, left: &Expr<'_>, right: &Expr<'_>) -> bool {
1108    SpanlessEq::new(cx).deny_side_effects().eq_expr(ctxt, left, right)
1109}
1110
1111/// Returns the segments of a path that might have generic parameters.
1112/// Usually just the last segment for free items, except for when the path resolves to an associated
1113/// item, in which case it is the last two
1114fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
1115    match segments.last()?.res {
1116        Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _) => {
1117            // <Ty as module::Trait<T>>::assoc::<U>
1118            //        ^^^^^^^^^^^^^^^^   ^^^^^^^^^^ segments: [module, Trait<T>, assoc<U>]
1119            Some(&segments[segments.len().checked_sub(2)?..])
1120        },
1121        Res::Err => None,
1122        _ => Some(slice::from_ref(segments.last()?)),
1123    }
1124}
1125
1126/// Type used to hash an ast element. This is different from the `Hash` trait
1127/// on ast types as this
1128/// trait would consider IDs and spans.
1129///
1130/// All expressions kind are hashed, but some might have a weaker hash.
1131pub struct SpanlessHash<'a, 'tcx> {
1132    /// Context used to evaluate constant expressions.
1133    cx: &'a LateContext<'tcx>,
1134    maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
1135    s: FxHasher,
1136    path_check: PathCheck,
1137}
1138
1139impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
1140    pub fn new(cx: &'a LateContext<'tcx>) -> Self {
1141        Self {
1142            cx,
1143            maybe_typeck_results: cx.maybe_typeck_results(),
1144            s: FxHasher::default(),
1145            path_check: PathCheck::default(),
1146        }
1147    }
1148
1149    /// Check paths by their resolution instead of exact equality. See [`PathCheck`] for more
1150    /// details.
1151    #[must_use]
1152    pub fn paths_by_resolution(self) -> Self {
1153        Self {
1154            path_check: PathCheck::Resolution,
1155            ..self
1156        }
1157    }
1158
1159    pub fn finish(self) -> u64 {
1160        self.s.finish()
1161    }
1162
1163    pub fn hash_block(&mut self, b: &Block<'_>) {
1164        for s in b.stmts {
1165            self.hash_stmt(s);
1166        }
1167
1168        if let Some(e) = b.expr {
1169            self.hash_expr(e);
1170        }
1171
1172        mem::discriminant(&b.rules).hash(&mut self.s);
1173    }
1174
1175    #[expect(clippy::too_many_lines)]
1176    pub fn hash_expr(&mut self, e: &Expr<'_>) {
1177        let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
1178            ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_local(e, e.span.ctxt())
1179        });
1180
1181        // const hashing may result in the same hash as some unrelated node, so add a sort of
1182        // discriminant depending on which path we're choosing next
1183        simple_const.hash(&mut self.s);
1184        if simple_const.is_some() {
1185            return;
1186        }
1187
1188        mem::discriminant(&e.kind).hash(&mut self.s);
1189
1190        match &e.kind {
1191            ExprKind::AddrOf(kind, m, e) => {
1192                mem::discriminant(kind).hash(&mut self.s);
1193                m.hash(&mut self.s);
1194                self.hash_expr(e);
1195            },
1196            ExprKind::Continue(i) => {
1197                if let Some(i) = i.label {
1198                    self.hash_name(i.ident.name);
1199                }
1200            },
1201            ExprKind::Array(v) => {
1202                self.hash_exprs(v);
1203            },
1204            ExprKind::Assign(l, r, _) => {
1205                self.hash_expr(l);
1206                self.hash_expr(r);
1207            },
1208            ExprKind::AssignOp(o, l, r) => {
1209                mem::discriminant(&o.node).hash(&mut self.s);
1210                self.hash_expr(l);
1211                self.hash_expr(r);
1212            },
1213            ExprKind::Become(f) => {
1214                self.hash_expr(f);
1215            },
1216            ExprKind::Block(b, _) => {
1217                self.hash_block(b);
1218            },
1219            ExprKind::Binary(op, l, r) => {
1220                mem::discriminant(&op.node).hash(&mut self.s);
1221                self.hash_expr(l);
1222                self.hash_expr(r);
1223            },
1224            ExprKind::Break(i, j) => {
1225                if let Some(i) = i.label {
1226                    self.hash_name(i.ident.name);
1227                }
1228                if let Some(j) = j {
1229                    self.hash_expr(j);
1230                }
1231            },
1232            ExprKind::Call(fun, args) => {
1233                self.hash_expr(fun);
1234                self.hash_exprs(args);
1235            },
1236            ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
1237                self.hash_expr(e);
1238                self.hash_ty(ty);
1239            },
1240            ExprKind::Closure(Closure {
1241                capture_clause, body, ..
1242            }) => {
1243                mem::discriminant(capture_clause).hash(&mut self.s);
1244                // closures inherit TypeckResults
1245                self.hash_expr(self.cx.tcx.hir_body(*body).value);
1246            },
1247            ExprKind::ConstBlock(l_id) => {
1248                self.hash_body(l_id.body);
1249            },
1250            ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
1251                self.hash_expr(e);
1252            },
1253            ExprKind::Field(e, f) => {
1254                self.hash_expr(e);
1255                self.hash_name(f.name);
1256            },
1257            ExprKind::Index(a, i, _) => {
1258                self.hash_expr(a);
1259                self.hash_expr(i);
1260            },
1261            ExprKind::InlineAsm(asm) => {
1262                for piece in asm.template {
1263                    match piece {
1264                        InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
1265                        InlineAsmTemplatePiece::Placeholder {
1266                            operand_idx,
1267                            modifier,
1268                            span: _,
1269                        } => {
1270                            operand_idx.hash(&mut self.s);
1271                            modifier.hash(&mut self.s);
1272                        },
1273                    }
1274                }
1275                asm.options.hash(&mut self.s);
1276                for (op, _op_sp) in asm.operands {
1277                    match op {
1278                        InlineAsmOperand::In { reg, expr } => {
1279                            reg.hash(&mut self.s);
1280                            self.hash_expr(expr);
1281                        },
1282                        InlineAsmOperand::Out { reg, late, expr } => {
1283                            reg.hash(&mut self.s);
1284                            late.hash(&mut self.s);
1285                            if let Some(expr) = expr {
1286                                self.hash_expr(expr);
1287                            }
1288                        },
1289                        InlineAsmOperand::InOut { reg, late, expr } => {
1290                            reg.hash(&mut self.s);
1291                            late.hash(&mut self.s);
1292                            self.hash_expr(expr);
1293                        },
1294                        InlineAsmOperand::SplitInOut {
1295                            reg,
1296                            late,
1297                            in_expr,
1298                            out_expr,
1299                        } => {
1300                            reg.hash(&mut self.s);
1301                            late.hash(&mut self.s);
1302                            self.hash_expr(in_expr);
1303                            if let Some(out_expr) = out_expr {
1304                                self.hash_expr(out_expr);
1305                            }
1306                        },
1307                        InlineAsmOperand::SymFn { expr } => {
1308                            self.hash_expr(expr);
1309                        },
1310                        InlineAsmOperand::Const { anon_const } => {
1311                            self.hash_body(anon_const.body);
1312                        },
1313                        InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
1314                        InlineAsmOperand::Label { block } => self.hash_block(block),
1315                    }
1316                }
1317            },
1318            ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
1319                self.hash_expr(init);
1320                if let Some(ty) = ty {
1321                    self.hash_ty(ty);
1322                }
1323                self.hash_pat(pat);
1324            },
1325            ExprKind::Lit(l) => {
1326                l.node.hash(&mut self.s);
1327            },
1328            ExprKind::Loop(b, i, ..) => {
1329                self.hash_block(b);
1330                if let Some(i) = i {
1331                    self.hash_name(i.ident.name);
1332                }
1333            },
1334            ExprKind::If(cond, then, else_opt) => {
1335                self.hash_expr(cond);
1336                self.hash_expr(then);
1337                if let Some(e) = else_opt {
1338                    self.hash_expr(e);
1339                }
1340            },
1341            ExprKind::Match(scrutinee, arms, _) => {
1342                self.hash_expr(scrutinee);
1343
1344                for arm in *arms {
1345                    self.hash_pat(arm.pat);
1346                    if let Some(e) = arm.guard {
1347                        self.hash_expr(e);
1348                    }
1349                    self.hash_expr(arm.body);
1350                }
1351            },
1352            ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1353                self.hash_name(path.ident.name);
1354                self.hash_expr(receiver);
1355                self.hash_exprs(args);
1356            },
1357            ExprKind::OffsetOf(container, fields) => {
1358                self.hash_ty(container);
1359                for field in *fields {
1360                    self.hash_name(field.name);
1361                }
1362            },
1363            ExprKind::Path(qpath) => {
1364                self.hash_qpath(qpath);
1365            },
1366            ExprKind::Repeat(e, len) => {
1367                self.hash_expr(e);
1368                self.hash_const_arg(len);
1369            },
1370            ExprKind::Ret(e) => {
1371                if let Some(e) = e {
1372                    self.hash_expr(e);
1373                }
1374            },
1375            ExprKind::Struct(path, fields, expr) => {
1376                self.hash_qpath(path);
1377
1378                for f in *fields {
1379                    self.hash_name(f.ident.name);
1380                    self.hash_expr(f.expr);
1381                }
1382
1383                if let StructTailExpr::Base(e) = expr {
1384                    self.hash_expr(e);
1385                }
1386            },
1387            ExprKind::Tup(tup) => {
1388                self.hash_exprs(tup);
1389            },
1390            ExprKind::Use(expr, _) => {
1391                self.hash_expr(expr);
1392            },
1393            ExprKind::Unary(l_op, le) => {
1394                mem::discriminant(l_op).hash(&mut self.s);
1395                self.hash_expr(le);
1396            },
1397            ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1398                mem::discriminant(kind).hash(&mut self.s);
1399                self.hash_expr(expr);
1400                if let Some(ty) = ty {
1401                    self.hash_ty(ty);
1402                }
1403            },
1404            ExprKind::Err(_) => {},
1405        }
1406    }
1407
1408    pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1409        for e in e {
1410            self.hash_expr(e);
1411        }
1412    }
1413
1414    pub fn hash_name(&mut self, n: Symbol) {
1415        n.hash(&mut self.s);
1416    }
1417
1418    pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1419        match p {
1420            QPath::Resolved(_, path) => {
1421                self.hash_path(path);
1422            },
1423            QPath::TypeRelative(_, path) => {
1424                self.hash_name(path.ident.name);
1425            },
1426        }
1427        // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
1428    }
1429
1430    pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1431        mem::discriminant(&lit.kind).hash(&mut self.s);
1432        match &lit.kind {
1433            PatExprKind::Lit { lit, negated } => {
1434                lit.node.hash(&mut self.s);
1435                negated.hash(&mut self.s);
1436            },
1437            PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1438        }
1439    }
1440
1441    pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1442        mem::discriminant(&pat.kind).hash(&mut self.s);
1443        match pat.kind {
1444            TyPatKind::Range(s, e) => {
1445                self.hash_const_arg(s);
1446                self.hash_const_arg(e);
1447            },
1448            TyPatKind::Or(variants) => {
1449                for variant in variants {
1450                    self.hash_ty_pat(variant);
1451                }
1452            },
1453            TyPatKind::NotNull | TyPatKind::Err(_) => {},
1454        }
1455    }
1456
1457    pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1458        mem::discriminant(&pat.kind).hash(&mut self.s);
1459        match &pat.kind {
1460            PatKind::Missing => unreachable!(),
1461            PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1462                mem::discriminant(by_ref).hash(&mut self.s);
1463                if let ByRef::Yes(pi, mu) = by_ref {
1464                    mem::discriminant(pi).hash(&mut self.s);
1465                    mem::discriminant(mu).hash(&mut self.s);
1466                }
1467                mem::discriminant(mutability).hash(&mut self.s);
1468                if let Some(pat) = pat {
1469                    self.hash_pat(pat);
1470                }
1471            },
1472            PatKind::Box(pat) | PatKind::Deref(pat) => self.hash_pat(pat),
1473            PatKind::Expr(expr) => self.hash_pat_expr(expr),
1474            PatKind::Or(pats) => {
1475                for pat in *pats {
1476                    self.hash_pat(pat);
1477                }
1478            },
1479            PatKind::Range(s, e, i) => {
1480                if let Some(s) = s {
1481                    self.hash_pat_expr(s);
1482                }
1483                if let Some(e) = e {
1484                    self.hash_pat_expr(e);
1485                }
1486                mem::discriminant(i).hash(&mut self.s);
1487            },
1488            PatKind::Ref(pat, pi, mu) => {
1489                self.hash_pat(pat);
1490                mem::discriminant(pi).hash(&mut self.s);
1491                mem::discriminant(mu).hash(&mut self.s);
1492            },
1493            PatKind::Guard(pat, guard) => {
1494                self.hash_pat(pat);
1495                self.hash_expr(guard);
1496            },
1497            PatKind::Slice(l, m, r) => {
1498                for pat in *l {
1499                    self.hash_pat(pat);
1500                }
1501                if let Some(pat) = m {
1502                    self.hash_pat(pat);
1503                }
1504                for pat in *r {
1505                    self.hash_pat(pat);
1506                }
1507            },
1508            PatKind::Struct(qpath, fields, e) => {
1509                self.hash_qpath(qpath);
1510                for f in *fields {
1511                    self.hash_name(f.ident.name);
1512                    self.hash_pat(f.pat);
1513                }
1514                e.hash(&mut self.s);
1515            },
1516            PatKind::Tuple(pats, e) => {
1517                for pat in *pats {
1518                    self.hash_pat(pat);
1519                }
1520                e.hash(&mut self.s);
1521            },
1522            PatKind::TupleStruct(qpath, pats, e) => {
1523                self.hash_qpath(qpath);
1524                for pat in *pats {
1525                    self.hash_pat(pat);
1526                }
1527                e.hash(&mut self.s);
1528            },
1529            PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1530        }
1531    }
1532
1533    pub fn hash_path(&mut self, path: &Path<'_>) {
1534        match path.res {
1535            // constant hash since equality is dependant on inter-expression context
1536            // e.g. The expressions `if let Some(x) = foo() {}` and `if let Some(y) = foo() {}` are considered equal
1537            // even though the binding names are different and they have different `HirId`s.
1538            Res::Local(_) => 1_usize.hash(&mut self.s),
1539            _ => {
1540                if let PathCheck::Resolution = self.path_check
1541                    && let [.., last] = path.segments
1542                    && let Some(segments) = generic_path_segments(path.segments)
1543                {
1544                    for seg in segments {
1545                        self.hash_generic_args(seg.args().args);
1546                    }
1547                    last.res.hash(&mut self.s);
1548                } else {
1549                    for seg in path.segments {
1550                        self.hash_name(seg.ident.name);
1551                        self.hash_generic_args(seg.args().args);
1552                    }
1553                }
1554            },
1555        }
1556    }
1557
1558    pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1559        let TraitBoundModifiers { constness, polarity } = modifiers;
1560        mem::discriminant(&polarity).hash(&mut self.s);
1561        mem::discriminant(&constness).hash(&mut self.s);
1562    }
1563
1564    pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1565        mem::discriminant(&b.kind).hash(&mut self.s);
1566
1567        match &b.kind {
1568            StmtKind::Let(local) => {
1569                self.hash_pat(local.pat);
1570                if let Some(init) = local.init {
1571                    self.hash_expr(init);
1572                }
1573                if let Some(els) = local.els {
1574                    self.hash_block(els);
1575                }
1576            },
1577            StmtKind::Item(..) => {},
1578            StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1579                self.hash_expr(expr);
1580            },
1581        }
1582    }
1583
1584    pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1585        lifetime.ident.name.hash(&mut self.s);
1586        mem::discriminant(&lifetime.kind).hash(&mut self.s);
1587        if let LifetimeKind::Param(param_id) = lifetime.kind {
1588            param_id.hash(&mut self.s);
1589        }
1590    }
1591
1592    pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1593        mem::discriminant(&ty.kind).hash(&mut self.s);
1594        self.hash_tykind(&ty.kind);
1595    }
1596
1597    pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1598        match ty {
1599            TyKind::Slice(ty) => {
1600                self.hash_ty(ty);
1601            },
1602            TyKind::Array(ty, len) => {
1603                self.hash_ty(ty);
1604                self.hash_const_arg(len);
1605            },
1606            TyKind::Pat(ty, pat) => {
1607                self.hash_ty(ty);
1608                self.hash_ty_pat(pat);
1609            },
1610            TyKind::FieldOf(base, TyFieldPath { variant, field }) => {
1611                self.hash_ty(base);
1612                if let Some(variant) = variant {
1613                    self.hash_name(variant.name);
1614                }
1615                self.hash_name(field.name);
1616            },
1617            TyKind::Ptr(mut_ty) => {
1618                self.hash_ty(mut_ty.ty);
1619                mut_ty.mutbl.hash(&mut self.s);
1620            },
1621            TyKind::Ref(lifetime, mut_ty) => {
1622                self.hash_lifetime(lifetime);
1623                self.hash_ty(mut_ty.ty);
1624                mut_ty.mutbl.hash(&mut self.s);
1625            },
1626            TyKind::FnPtr(fn_ptr) => {
1627                fn_ptr.safety.hash(&mut self.s);
1628                fn_ptr.abi.hash(&mut self.s);
1629                for arg in fn_ptr.decl.inputs {
1630                    self.hash_ty(arg);
1631                }
1632                mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1633                match fn_ptr.decl.output {
1634                    FnRetTy::DefaultReturn(_) => {},
1635                    FnRetTy::Return(ty) => {
1636                        self.hash_ty(ty);
1637                    },
1638                }
1639                fn_ptr.decl.c_variadic().hash(&mut self.s);
1640            },
1641            TyKind::Tup(ty_list) => {
1642                for ty in *ty_list {
1643                    self.hash_ty(ty);
1644                }
1645            },
1646            TyKind::Path(qpath) => self.hash_qpath(qpath),
1647            TyKind::TraitObject(_, lifetime) => {
1648                self.hash_lifetime(lifetime);
1649            },
1650            TyKind::UnsafeBinder(binder) => {
1651                self.hash_ty(binder.inner_ty);
1652            },
1653            TyKind::Err(_)
1654            | TyKind::Infer(())
1655            | TyKind::Never
1656            | TyKind::InferDelegation(..)
1657            | TyKind::OpaqueDef(_)
1658            | TyKind::TraitAscription(_) => {},
1659        }
1660    }
1661
1662    pub fn hash_body(&mut self, body_id: BodyId) {
1663        // swap out TypeckResults when hashing a body
1664        let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1665        self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1666        self.maybe_typeck_results = old_maybe_typeck_results;
1667    }
1668
1669    fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1670        match &const_arg.kind {
1671            ConstArgKind::Tup(tup) => {
1672                for arg in *tup {
1673                    self.hash_const_arg(arg);
1674                }
1675            },
1676            ConstArgKind::Path(path) => self.hash_qpath(path),
1677            ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1678            ConstArgKind::Struct(path, inits) => {
1679                self.hash_qpath(path);
1680                for init in *inits {
1681                    self.hash_const_arg(init.expr);
1682                }
1683            },
1684            ConstArgKind::TupleCall(path, args) => {
1685                self.hash_qpath(path);
1686                for arg in *args {
1687                    self.hash_const_arg(arg);
1688                }
1689            },
1690            ConstArgKind::Array(array_expr) => {
1691                for elem in array_expr.elems {
1692                    self.hash_const_arg(elem);
1693                }
1694            },
1695            ConstArgKind::Infer(..) | ConstArgKind::Error(..) => {},
1696            ConstArgKind::Literal { lit, negated } => {
1697                lit.hash(&mut self.s);
1698                negated.hash(&mut self.s);
1699            },
1700        }
1701    }
1702
1703    fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1704        for arg in arg_list {
1705            match arg {
1706                GenericArg::Lifetime(l) => self.hash_lifetime(l),
1707                GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1708                GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1709                GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1710            }
1711        }
1712    }
1713}
1714
1715pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1716    let mut h = SpanlessHash::new(cx);
1717    h.hash_stmt(s);
1718    h.finish()
1719}
1720
1721pub fn is_bool(ty: &Ty<'_>) -> bool {
1722    if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1723        matches!(path.res, Res::PrimTy(PrimTy::Bool))
1724    } else {
1725        false
1726    }
1727}
1728
1729pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1730    let mut h = SpanlessHash::new(cx);
1731    h.hash_expr(e);
1732    h.finish()
1733}
1734
1735fn eq_span_tokens(
1736    cx: &LateContext<'_>,
1737    left: impl SpanRange,
1738    right: impl SpanRange,
1739    pred: impl Fn(TokenKind) -> bool,
1740) -> bool {
1741    fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1742        if let Some(lsrc) = left.get_source_range(cx)
1743            && let Some(lsrc) = lsrc.as_str()
1744            && let Some(rsrc) = right.get_source_range(cx)
1745            && let Some(rsrc) = rsrc.as_str()
1746        {
1747            let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1748            let map = |(_, source, _)| source;
1749
1750            let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1751            let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1752            ltok.eq(rtok)
1753        } else {
1754            // Unable to access the source. Conservatively assume the blocks aren't equal.
1755            false
1756        }
1757    }
1758    f(cx, left.into_range(), right.into_range(), pred)
1759}
1760
1761/// Returns true if the expression contains ambiguous literals (unsuffixed float or int literals)
1762/// that could be interpreted as either f32/f64 or i32/i64 depending on context.
1763pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1764    match expr.kind {
1765        ExprKind::Path(ref qpath) => {
1766            if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1767                && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1768                && local.ty.is_none()
1769                && let Some(init) = local.init
1770            {
1771                return has_ambiguous_literal_in_expr(cx, init);
1772            }
1773            false
1774        },
1775        ExprKind::Lit(lit) => matches!(
1776            lit.node,
1777            ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1778        ),
1779
1780        ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1781
1782        ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1783            has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1784        },
1785
1786        ExprKind::Unary(_, e)
1787        | ExprKind::Cast(e, _)
1788        | ExprKind::Type(e, _)
1789        | ExprKind::DropTemps(e)
1790        | ExprKind::AddrOf(_, _, e)
1791        | ExprKind::Field(e, _)
1792        | ExprKind::Index(e, _, _)
1793        | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1794
1795        ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1796            has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1797        },
1798
1799        ExprKind::Closure(Closure { body, .. }) => {
1800            let body = cx.tcx.hir_body(*body);
1801            let closure_expr = crate::peel_blocks(body.value);
1802            has_ambiguous_literal_in_expr(cx, closure_expr)
1803        },
1804
1805        ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1806
1807        ExprKind::If(cond, then_expr, else_expr) => {
1808            has_ambiguous_literal_in_expr(cx, cond)
1809                || has_ambiguous_literal_in_expr(cx, then_expr)
1810                || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1811        },
1812
1813        ExprKind::Match(scrutinee, arms, _) => {
1814            has_ambiguous_literal_in_expr(cx, scrutinee)
1815                || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1816        },
1817
1818        ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1819
1820        ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1821            opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1822        },
1823
1824        _ => false,
1825    }
1826}