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