Skip to main content

clippy_utils/
hir_utils.rs

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