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