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