clippy_utils/
hir_utils.rs

1use crate::consts::ConstEvalCtxt;
2use crate::macros::macro_backtrace;
3use crate::source::{SpanRange, SpanRangeExt, walk_span_to_context};
4use crate::tokenize_with_text;
5use rustc_ast::ast;
6use rustc_ast::ast::InlineAsmTemplatePiece;
7use rustc_data_structures::fx::FxHasher;
8use rustc_hir::MatchSource::TryDesugar;
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::{
11    AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, ByRef, Closure, ConstArg, ConstArgKind, Expr,
12    ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime,
13    LifetimeKind, Node, Pat, PatExpr, PatExprKind, PatField, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind,
14    StructTailExpr, TraitBoundModifiers, Ty, TyKind, TyPat, TyPatKind,
15};
16use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize};
17use rustc_lint::LateContext;
18use rustc_middle::ty::TypeckResults;
19use rustc_span::{BytePos, ExpnKind, MacroKind, Symbol, SyntaxContext, sym};
20use std::hash::{Hash, Hasher};
21use std::ops::Range;
22use std::slice;
23
24/// Callback that is called when two expressions are not equal in the sense of `SpanlessEq`, but
25/// other conditions would make them equal.
26type SpanlessEqCallback<'a> = dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a;
27
28/// Determines how paths are hashed and compared for equality.
29#[derive(Copy, Clone, Debug, Default)]
30pub enum PathCheck {
31    /// Paths must match exactly and are hashed by their exact HIR tree.
32    ///
33    /// Thus, `std::iter::Iterator` and `Iterator` are not considered equal even though they refer
34    /// to the same item.
35    #[default]
36    Exact,
37    /// Paths are compared and hashed based on their resolution.
38    ///
39    /// They can appear different in the HIR tree but are still considered equal
40    /// and have equal hashes as long as they refer to the same item.
41    ///
42    /// Note that this is currently only partially implemented specifically for paths that are
43    /// resolved before type-checking, i.e. the final segment must have a non-error resolution.
44    /// If a path with an error resolution is encountered, it falls back to the default exact
45    /// matching behavior.
46    Resolution,
47}
48
49/// Type used to check whether two ast are the same. This is different from the
50/// operator `==` on ast types as this operator would compare true equality with
51/// ID and span.
52///
53/// Note that some expressions kinds are not considered but could be added.
54pub struct SpanlessEq<'a, 'tcx> {
55    /// Context used to evaluate constant expressions.
56    cx: &'a LateContext<'tcx>,
57    maybe_typeck_results: Option<(&'tcx TypeckResults<'tcx>, &'tcx TypeckResults<'tcx>)>,
58    allow_side_effects: bool,
59    expr_fallback: Option<Box<SpanlessEqCallback<'a>>>,
60    path_check: PathCheck,
61}
62
63impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
64    pub fn new(cx: &'a LateContext<'tcx>) -> Self {
65        Self {
66            cx,
67            maybe_typeck_results: cx.maybe_typeck_results().map(|x| (x, x)),
68            allow_side_effects: true,
69            expr_fallback: None,
70            path_check: PathCheck::default(),
71        }
72    }
73
74    /// Consider expressions containing potential side effects as not equal.
75    #[must_use]
76    pub fn deny_side_effects(self) -> Self {
77        Self {
78            allow_side_effects: false,
79            ..self
80        }
81    }
82
83    /// Check paths by their resolution instead of exact equality. See [`PathCheck`] for more
84    /// details.
85    #[must_use]
86    pub fn paths_by_resolution(self) -> Self {
87        Self {
88            path_check: PathCheck::Resolution,
89            ..self
90        }
91    }
92
93    #[must_use]
94    pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
95        Self {
96            expr_fallback: Some(Box::new(expr_fallback)),
97            ..self
98        }
99    }
100
101    /// Use this method to wrap comparisons that may involve inter-expression context.
102    /// See `self.locals`.
103    pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
104        HirEqInterExpr {
105            inner: self,
106            left_ctxt: SyntaxContext::root(),
107            right_ctxt: SyntaxContext::root(),
108            locals: HirIdMap::default(),
109        }
110    }
111
112    pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
113        self.inter_expr().eq_block(left, right)
114    }
115
116    pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
117        self.inter_expr().eq_expr(left, right)
118    }
119
120    pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
121        self.inter_expr().eq_path(left, right)
122    }
123
124    pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
125        self.inter_expr().eq_path_segment(left, right)
126    }
127
128    pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
129        self.inter_expr().eq_path_segments(left, right)
130    }
131
132    pub fn eq_modifiers(left: TraitBoundModifiers, right: TraitBoundModifiers) -> bool {
133        std::mem::discriminant(&left.constness) == std::mem::discriminant(&right.constness)
134            && std::mem::discriminant(&left.polarity) == std::mem::discriminant(&right.polarity)
135    }
136}
137
138pub struct HirEqInterExpr<'a, 'b, 'tcx> {
139    inner: &'a mut SpanlessEq<'b, 'tcx>,
140    left_ctxt: SyntaxContext,
141    right_ctxt: SyntaxContext,
142
143    // When binding are declared, the binding ID in the left expression is mapped to the one on the
144    // right. For example, when comparing `{ let x = 1; x + 2 }` and `{ let y = 1; y + 2 }`,
145    // these blocks are considered equal since `x` is mapped to `y`.
146    pub locals: HirIdMap<HirId>,
147}
148
149impl HirEqInterExpr<'_, '_, '_> {
150    pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
151        match (&left.kind, &right.kind) {
152            (StmtKind::Let(l), StmtKind::Let(r)) => {
153                // This additional check ensures that the type of the locals are equivalent even if the init
154                // expression or type have some inferred parts.
155                if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
156                    let l_ty = typeck_lhs.pat_ty(l.pat);
157                    let r_ty = typeck_rhs.pat_ty(r.pat);
158                    if l_ty != r_ty {
159                        return false;
160                    }
161                }
162
163                // eq_pat adds the HirIds to the locals map. We therefore call it last to make sure that
164                // these only get added if the init and type is equal.
165                both(l.init.as_ref(), r.init.as_ref(), |l, r| self.eq_expr(l, r))
166                    && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
167                    && both(l.els.as_ref(), r.els.as_ref(), |l, r| self.eq_block(l, r))
168                    && self.eq_pat(l.pat, r.pat)
169            },
170            (StmtKind::Expr(l), StmtKind::Expr(r)) | (StmtKind::Semi(l), StmtKind::Semi(r)) => self.eq_expr(l, r),
171            _ => false,
172        }
173    }
174
175    /// Checks whether two blocks are the same.
176    fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
177        use TokenKind::{Semi, Whitespace};
178        if left.stmts.len() != right.stmts.len() {
179            return false;
180        }
181        let lspan = left.span.data();
182        let rspan = right.span.data();
183        if lspan.ctxt != SyntaxContext::root() && rspan.ctxt != SyntaxContext::root() {
184            // Don't try to check in between statements inside macros.
185            return over(left.stmts, right.stmts, |left, right| self.eq_stmt(left, right))
186                && both(left.expr.as_ref(), right.expr.as_ref(), |left, right| {
187                    self.eq_expr(left, right)
188                });
189        }
190        if lspan.ctxt != rspan.ctxt {
191            return false;
192        }
193
194        let mut lstart = lspan.lo;
195        let mut rstart = rspan.lo;
196
197        for (left, right) in left.stmts.iter().zip(right.stmts) {
198            if !self.eq_stmt(left, right) {
199                return false;
200            }
201
202            // Try to detect any `cfg`ed statements or empty macro expansions.
203            let Some(lstmt_span) = walk_span_to_context(left.span, lspan.ctxt) else {
204                return false;
205            };
206            let Some(rstmt_span) = walk_span_to_context(right.span, rspan.ctxt) else {
207                return false;
208            };
209            let lstmt_span = lstmt_span.data();
210            let rstmt_span = rstmt_span.data();
211
212            if lstmt_span.lo < lstart && rstmt_span.lo < rstart {
213                // Can happen when macros expand to multiple statements, or rearrange statements.
214                // Nothing in between the statements to check in this case.
215                continue;
216            }
217            if lstmt_span.lo < lstart || rstmt_span.lo < rstart {
218                // Only one of the blocks had a weird macro.
219                return false;
220            }
221            if !eq_span_tokens(self.inner.cx, lstart..lstmt_span.lo, rstart..rstmt_span.lo, |t| {
222                !matches!(t, Whitespace | Semi)
223            }) {
224                return false;
225            }
226
227            lstart = lstmt_span.hi;
228            rstart = rstmt_span.hi;
229        }
230
231        let (lend, rend) = match (left.expr, right.expr) {
232            (Some(left), Some(right)) => {
233                if !self.eq_expr(left, right) {
234                    return false;
235                }
236                let Some(lexpr_span) = walk_span_to_context(left.span, lspan.ctxt) else {
237                    return false;
238                };
239                let Some(rexpr_span) = walk_span_to_context(right.span, rspan.ctxt) else {
240                    return false;
241                };
242                (lexpr_span.lo(), rexpr_span.lo())
243            },
244            (None, None) => (lspan.hi, rspan.hi),
245            (Some(_), None) | (None, Some(_)) => return false,
246        };
247
248        if lend < lstart && rend < rstart {
249            // Can happen when macros rearrange the input.
250            // Nothing in between the statements to check in this case.
251            return true;
252        } else if lend < lstart || rend < rstart {
253            // Only one of the blocks had a weird macro
254            return false;
255        }
256        eq_span_tokens(self.inner.cx, lstart..lend, rstart..rend, |t| {
257            !matches!(t, Whitespace | Semi)
258        })
259    }
260
261    fn should_ignore(&self, expr: &Expr<'_>) -> bool {
262        macro_backtrace(expr.span).last().is_some_and(|macro_call| {
263            matches!(
264                self.inner.cx.tcx.get_diagnostic_name(macro_call.def_id),
265                Some(sym::todo_macro | sym::unimplemented_macro)
266            )
267        })
268    }
269
270    pub fn eq_body(&mut self, left: BodyId, right: BodyId) -> bool {
271        // swap out TypeckResults when hashing a body
272        let old_maybe_typeck_results = self.inner.maybe_typeck_results.replace((
273            self.inner.cx.tcx.typeck_body(left),
274            self.inner.cx.tcx.typeck_body(right),
275        ));
276        let res = self.eq_expr(
277            self.inner.cx.tcx.hir_body(left).value,
278            self.inner.cx.tcx.hir_body(right).value,
279        );
280        self.inner.maybe_typeck_results = old_maybe_typeck_results;
281        res
282    }
283
284    #[expect(clippy::too_many_lines)]
285    pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
286        if !self.check_ctxt(left.span.ctxt(), right.span.ctxt()) {
287            return false;
288        }
289
290        if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results
291            && typeck_lhs.expr_ty(left) == typeck_rhs.expr_ty(right)
292            && let (Some(l), Some(r)) = (
293                ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_lhs)
294                    .eval_local(left, self.left_ctxt),
295                ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_rhs)
296                    .eval_local(right, self.right_ctxt),
297            )
298            && l == r
299        {
300            return true;
301        }
302
303        let is_eq = match (
304            reduce_exprkind(self.inner.cx, &left.kind),
305            reduce_exprkind(self.inner.cx, &right.kind),
306        ) {
307            (ExprKind::AddrOf(lb, l_mut, le), ExprKind::AddrOf(rb, r_mut, re)) => {
308                lb == rb && l_mut == r_mut && self.eq_expr(le, re)
309            },
310            (ExprKind::Array(l), ExprKind::Array(r)) => self.eq_exprs(l, r),
311            (ExprKind::Assign(ll, lr, _), ExprKind::Assign(rl, rr, _)) => {
312                self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
313            },
314            (ExprKind::AssignOp(lo, ll, lr), ExprKind::AssignOp(ro, rl, rr)) => {
315                self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
316            },
317            (ExprKind::Block(l, _), ExprKind::Block(r, _)) => self.eq_block(l, r),
318            (ExprKind::Binary(l_op, ll, lr), ExprKind::Binary(r_op, rl, rr)) => {
319                l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
320                    || swap_binop(l_op.node, ll, lr).is_some_and(|(l_op, ll, lr)| {
321                        l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
322                    })
323            },
324            (ExprKind::Break(li, le), ExprKind::Break(ri, re)) => {
325                both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
326                    && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
327            },
328            (ExprKind::Call(l_fun, l_args), ExprKind::Call(r_fun, r_args)) => {
329                self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
330            },
331            (ExprKind::Cast(lx, lt), ExprKind::Cast(rx, rt)) => {
332                self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
333            },
334            (ExprKind::Closure(_l), ExprKind::Closure(_r)) => false,
335            (ExprKind::ConstBlock(lb), ExprKind::ConstBlock(rb)) => self.eq_body(lb.body, rb.body),
336            (ExprKind::Continue(li), ExprKind::Continue(ri)) => {
337                both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
338            },
339            (ExprKind::DropTemps(le), ExprKind::DropTemps(re)) => self.eq_expr(le, re),
340            (ExprKind::Field(l_f_exp, l_f_ident), ExprKind::Field(r_f_exp, r_f_ident)) => {
341                l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
342            },
343            (ExprKind::Index(la, li, _), ExprKind::Index(ra, ri, _)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
344            (ExprKind::If(lc, lt, le), ExprKind::If(rc, rt, re)) => {
345                self.eq_expr(lc, rc) && self.eq_expr(lt, rt)
346                    && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
347            },
348            (ExprKind::Let(l), ExprKind::Let(r)) => {
349                self.eq_pat(l.pat, r.pat)
350                    && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
351                    && self.eq_expr(l.init, r.init)
352            },
353            (ExprKind::Lit(l), ExprKind::Lit(r)) => l.node == r.node,
354            (ExprKind::Loop(lb, ll, lls, _), ExprKind::Loop(rb, rl, rls, _)) => {
355                lls == rls && self.eq_block(lb, rb)
356                    && both(ll.as_ref(), rl.as_ref(), |l, r| l.ident.name == r.ident.name)
357            },
358            (ExprKind::Match(le, la, ls), ExprKind::Match(re, ra, rs)) => {
359                (ls == rs || (matches!((ls, rs), (TryDesugar(_), TryDesugar(_)))))
360                    && self.eq_expr(le, re)
361                    && over(la, ra, |l, r| {
362                        self.eq_pat(l.pat, r.pat)
363                            && both(l.guard.as_ref(), r.guard.as_ref(), |l, r| self.eq_expr(l, r))
364                            && self.eq_expr(l.body, r.body)
365                    })
366            },
367            (
368                ExprKind::MethodCall(l_path, l_receiver, l_args, _),
369                ExprKind::MethodCall(r_path, r_receiver, r_args, _),
370            ) => {
371                self.inner.allow_side_effects
372                    && self.eq_path_segment(l_path, r_path)
373                    && self.eq_expr(l_receiver, r_receiver)
374                    && self.eq_exprs(l_args, r_args)
375            },
376            (ExprKind::UnsafeBinderCast(lkind, le, None), ExprKind::UnsafeBinderCast(rkind, re, None)) =>
377                lkind == rkind && self.eq_expr(le, re),
378            (ExprKind::UnsafeBinderCast(lkind, le, Some(lt)), ExprKind::UnsafeBinderCast(rkind, re, Some(rt))) =>
379                lkind == rkind && self.eq_expr(le, re) && self.eq_ty(lt, rt),
380            (ExprKind::OffsetOf(l_container, l_fields), ExprKind::OffsetOf(r_container, r_fields)) => {
381                self.eq_ty(l_container, r_container) && over(l_fields, r_fields, |l, r| l.name == r.name)
382            },
383            (ExprKind::Path(l), ExprKind::Path(r)) => self.eq_qpath(l, r),
384            (ExprKind::Repeat(le, ll), ExprKind::Repeat(re, rl)) => {
385                self.eq_expr(le, re) && self.eq_const_arg(ll, rl)
386            },
387            (ExprKind::Ret(l), ExprKind::Ret(r)) => both(l.as_ref(), r.as_ref(), |l, r| self.eq_expr(l, r)),
388            (ExprKind::Struct(l_path, lf, lo), ExprKind::Struct(r_path, rf, ro)) => {
389                self.eq_qpath(l_path, r_path)
390                    && match (lo, ro) {
391                        (StructTailExpr::Base(l),StructTailExpr::Base(r)) => self.eq_expr(l, r),
392                        (StructTailExpr::None, StructTailExpr::None) |
393                        (StructTailExpr::DefaultFields(_), StructTailExpr::DefaultFields(_)) => true,
394                        _ => false,
395                    }
396                    && over(lf, rf, |l, r| self.eq_expr_field(l, r))
397            },
398            (ExprKind::Tup(l_tup), ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
399            (ExprKind::Use(l_expr, _), ExprKind::Use(r_expr, _)) => self.eq_expr(l_expr, r_expr),
400            (ExprKind::Type(le, lt), ExprKind::Type(re, rt)) => self.eq_expr(le, re) && self.eq_ty(lt, rt),
401            (ExprKind::Unary(l_op, le), ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
402            (ExprKind::Yield(le, _), ExprKind::Yield(re, _)) => return self.eq_expr(le, re),
403            (
404                // Else branches for branches above, grouped as per `match_same_arms`.
405                | ExprKind::AddrOf(..)
406                | ExprKind::Array(..)
407                | ExprKind::Assign(..)
408                | ExprKind::AssignOp(..)
409                | ExprKind::Binary(..)
410                | ExprKind::Become(..)
411                | ExprKind::Block(..)
412                | ExprKind::Break(..)
413                | ExprKind::Call(..)
414                | ExprKind::Cast(..)
415                | ExprKind::ConstBlock(..)
416                | ExprKind::Continue(..)
417                | ExprKind::DropTemps(..)
418                | ExprKind::Field(..)
419                | ExprKind::Index(..)
420                | ExprKind::If(..)
421                | ExprKind::Let(..)
422                | ExprKind::Lit(..)
423                | ExprKind::Loop(..)
424                | ExprKind::Match(..)
425                | ExprKind::MethodCall(..)
426                | ExprKind::OffsetOf(..)
427                | ExprKind::Path(..)
428                | ExprKind::Repeat(..)
429                | ExprKind::Ret(..)
430                | ExprKind::Struct(..)
431                | ExprKind::Tup(..)
432                | ExprKind::Use(..)
433                | ExprKind::Type(..)
434                | ExprKind::Unary(..)
435                | ExprKind::Yield(..)
436                | ExprKind::UnsafeBinderCast(..)
437
438                // --- Special cases that do not have a positive branch.
439
440                // `Err` represents an invalid expression, so let's never assume that
441                // an invalid expressions is equal to anything.
442                | ExprKind::Err(..)
443
444                // For the time being, we always consider that two closures are unequal.
445                // This behavior may change in the future.
446                | ExprKind::Closure(..)
447                // For the time being, we always consider that two instances of InlineAsm are different.
448                // This behavior may change in the future.
449                | ExprKind::InlineAsm(_)
450                , _
451            ) => false,
452        };
453        (is_eq && (!self.should_ignore(left) || !self.should_ignore(right)))
454            || self.inner.expr_fallback.as_mut().is_some_and(|f| f(left, right))
455    }
456
457    fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
458        over(left, right, |l, r| self.eq_expr(l, r))
459    }
460
461    fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
462        left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
463    }
464
465    fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
466        match (left, right) {
467            (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_const_arg(l.as_unambig_ct(), r.as_unambig_ct()),
468            (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
469            (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty.as_unambig_ty(), r_ty.as_unambig_ty()),
470            (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
471            _ => false,
472        }
473    }
474
475    fn eq_const_arg(&mut self, left: &ConstArg<'_>, right: &ConstArg<'_>) -> bool {
476        match (&left.kind, &right.kind) {
477            (ConstArgKind::Path(l_p), ConstArgKind::Path(r_p)) => self.eq_qpath(l_p, r_p),
478            (ConstArgKind::Anon(l_an), ConstArgKind::Anon(r_an)) => self.eq_body(l_an.body, r_an.body),
479            (ConstArgKind::Infer(..), ConstArgKind::Infer(..)) => true,
480            // Use explicit match for now since ConstArg is undergoing flux.
481            (ConstArgKind::Path(..), ConstArgKind::Anon(..))
482            | (ConstArgKind::Anon(..), ConstArgKind::Path(..))
483            | (ConstArgKind::Infer(..) | ConstArgKind::Error(..), _)
484            | (_, ConstArgKind::Infer(..) | ConstArgKind::Error(..)) => false,
485        }
486    }
487
488    fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
489        left.kind == right.kind
490    }
491
492    fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
493        let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
494        li.name == ri.name && self.eq_pat(lp, rp)
495    }
496
497    fn eq_pat_expr(&mut self, left: &PatExpr<'_>, right: &PatExpr<'_>) -> bool {
498        match (&left.kind, &right.kind) {
499            (
500                PatExprKind::Lit {
501                    lit: left,
502                    negated: left_neg,
503                },
504                PatExprKind::Lit {
505                    lit: right,
506                    negated: right_neg,
507                },
508            ) => left_neg == right_neg && left.node == right.node,
509            (PatExprKind::ConstBlock(left), PatExprKind::ConstBlock(right)) => self.eq_body(left.body, right.body),
510            (PatExprKind::Path(left), PatExprKind::Path(right)) => self.eq_qpath(left, right),
511            (PatExprKind::Lit { .. } | PatExprKind::ConstBlock(..) | PatExprKind::Path(..), _) => false,
512        }
513    }
514
515    /// Checks whether two patterns are the same.
516    fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
517        match (&left.kind, &right.kind) {
518            (PatKind::Box(l), PatKind::Box(r)) => self.eq_pat(l, r),
519            (PatKind::Struct(lp, la, ..), PatKind::Struct(rp, ra, ..)) => {
520                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
521            },
522            (PatKind::TupleStruct(lp, la, ls), PatKind::TupleStruct(rp, ra, rs)) => {
523                self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
524            },
525            (PatKind::Binding(lb, li, _, lp), PatKind::Binding(rb, ri, _, rp)) => {
526                let eq = lb == rb && both(lp.as_ref(), rp.as_ref(), |l, r| self.eq_pat(l, r));
527                if eq {
528                    self.locals.insert(*li, *ri);
529                }
530                eq
531            },
532            (PatKind::Expr(l), PatKind::Expr(r)) => self.eq_pat_expr(l, r),
533            (PatKind::Tuple(l, ls), PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
534            (PatKind::Range(ls, le, li), PatKind::Range(rs, re, ri)) => {
535                both(ls.as_ref(), rs.as_ref(), |a, b| self.eq_pat_expr(a, b))
536                    && both(le.as_ref(), re.as_ref(), |a, b| self.eq_pat_expr(a, b))
537                    && (li == ri)
538            },
539            (PatKind::Ref(le, lp, lm), PatKind::Ref(re, rp, rm)) => lp == rp && lm == rm && self.eq_pat(le, re),
540            (PatKind::Slice(ls, li, le), PatKind::Slice(rs, ri, re)) => {
541                over(ls, rs, |l, r| self.eq_pat(l, r))
542                    && over(le, re, |l, r| self.eq_pat(l, r))
543                    && both(li.as_ref(), ri.as_ref(), |l, r| self.eq_pat(l, r))
544            },
545            (PatKind::Wild, PatKind::Wild) => true,
546            _ => false,
547        }
548    }
549
550    fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
551        match (left, right) {
552            (QPath::Resolved(lty, lpath), QPath::Resolved(rty, rpath)) => {
553                both(lty.as_ref(), rty.as_ref(), |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
554            },
555            (QPath::TypeRelative(lty, lseg), QPath::TypeRelative(rty, rseg)) => {
556                self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
557            },
558            _ => false,
559        }
560    }
561
562    pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
563        match (left.res, right.res) {
564            (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
565            (Res::Local(_), _) | (_, Res::Local(_)) => false,
566            _ => self.eq_path_segments(left.segments, right.segments),
567        }
568    }
569
570    fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
571        if left.parenthesized == right.parenthesized {
572            over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
573                && over(left.constraints, right.constraints, |l, r| self.eq_assoc_eq_constraint(l, r))
574        } else {
575            false
576        }
577    }
578
579    pub fn eq_path_segments<'tcx>(
580        &mut self,
581        mut left: &'tcx [PathSegment<'tcx>],
582        mut right: &'tcx [PathSegment<'tcx>],
583    ) -> bool {
584        if let PathCheck::Resolution = self.inner.path_check
585            && let Some(left_seg) = generic_path_segments(left)
586            && let Some(right_seg) = generic_path_segments(right)
587        {
588            // If we compare by resolution, then only check the last segments that could possibly have generic
589            // arguments
590            left = left_seg;
591            right = right_seg;
592        }
593
594        over(left, right, |l, r| self.eq_path_segment(l, r))
595    }
596
597    pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
598        if !self.eq_path_parameters(left.args(), right.args()) {
599            return false;
600        }
601
602        if let PathCheck::Resolution = self.inner.path_check
603            && left.res != Res::Err
604            && right.res != Res::Err
605        {
606            left.res == right.res
607        } else {
608            // The == of idents doesn't work with different contexts,
609            // we have to be explicit about hygiene
610            left.ident.name == right.ident.name
611        }
612    }
613
614    pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
615        match (&left.kind, &right.kind) {
616            (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
617            (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
618            (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
619            (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
620                l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
621            },
622            (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
623            (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
624            (TyKind::Infer(()), TyKind::Infer(())) => true,
625            _ => false,
626        }
627    }
628
629    /// Checks whether two constraints designate the same equality constraint (same name, and same
630    /// type or const).
631    fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
632        // TODO: this could be extended to check for identical associated item bound constraints
633        left.ident.name == right.ident.name
634            && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
635                || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
636    }
637
638    fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> bool {
639        if self.left_ctxt == left && self.right_ctxt == right {
640            return true;
641        } else if self.left_ctxt == left || self.right_ctxt == right {
642            // Only one context has changed. This can only happen if the two nodes are written differently.
643            return false;
644        } else if left != SyntaxContext::root() {
645            let mut left_data = left.outer_expn_data();
646            let mut right_data = right.outer_expn_data();
647            loop {
648                use TokenKind::{BlockComment, LineComment, Whitespace};
649                if left_data.macro_def_id != right_data.macro_def_id
650                    || (matches!(
651                        left_data.kind,
652                        ExpnKind::Macro(MacroKind::Bang, name)
653                        if name == sym::cfg || name == sym::option_env
654                    ) && !eq_span_tokens(self.inner.cx, left_data.call_site, right_data.call_site, |t| {
655                        !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. })
656                    }))
657                {
658                    // Either a different chain of macro calls, or different arguments to the `cfg` macro.
659                    return false;
660                }
661                let left_ctxt = left_data.call_site.ctxt();
662                let right_ctxt = right_data.call_site.ctxt();
663                if left_ctxt == SyntaxContext::root() && right_ctxt == SyntaxContext::root() {
664                    break;
665                }
666                if left_ctxt == SyntaxContext::root() || right_ctxt == SyntaxContext::root() {
667                    // Different lengths for the expansion stack. This can only happen if nodes are written differently,
668                    // or shouldn't be compared to start with.
669                    return false;
670                }
671                left_data = left_ctxt.outer_expn_data();
672                right_data = right_ctxt.outer_expn_data();
673            }
674        }
675        self.left_ctxt = left;
676        self.right_ctxt = right;
677        true
678    }
679}
680
681/// Some simple reductions like `{ return }` => `return`
682fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
683    if let ExprKind::Block(block, _) = kind {
684        match (block.stmts, block.expr) {
685            // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
686            // block with an empty span.
687            ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
688            // `{}` => `()`
689            ([], None)
690                if block.span.check_source_text(cx, |src| {
691                    tokenize(src, FrontmatterAllowed::No)
692                        .map(|t| t.kind)
693                        .filter(|t| {
694                            !matches!(
695                                t,
696                                TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
697                            )
698                        })
699                        .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
700                }) =>
701            {
702                &ExprKind::Tup(&[])
703            },
704            ([], Some(expr)) => match expr.kind {
705                // `{ return .. }` => `return ..`
706                ExprKind::Ret(..) => &expr.kind,
707                _ => kind,
708            },
709            ([stmt], None) => match stmt.kind {
710                StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
711                    // `{ return ..; }` => `return ..`
712                    ExprKind::Ret(..) => &expr.kind,
713                    _ => kind,
714                },
715                _ => kind,
716            },
717            _ => kind,
718        }
719    } else {
720        kind
721    }
722}
723
724fn swap_binop<'a>(
725    binop: BinOpKind,
726    lhs: &'a Expr<'a>,
727    rhs: &'a Expr<'a>,
728) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
729    match binop {
730        BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
731            Some((binop, rhs, lhs))
732        },
733        BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
734        BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
735        BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
736        BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
737        BinOpKind::Mul // Not always commutative, e.g. with matrices. See issue #5698
738        | BinOpKind::Shl
739        | BinOpKind::Shr
740        | BinOpKind::Rem
741        | BinOpKind::Sub
742        | BinOpKind::Div
743        | BinOpKind::And
744        | BinOpKind::Or => None,
745    }
746}
747
748/// Checks if the two `Option`s are both `None` or some equal values as per
749/// `eq_fn`.
750pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
751    l.as_ref()
752        .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
753}
754
755/// Checks if the two `Option`s are both `Some` and pass the predicate function.
756pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
757    l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
758}
759
760/// Checks if two slices are equal as per `eq_fn`.
761pub fn over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
762    left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
763}
764
765/// Counts how many elements of the slices are equal as per `eq_fn`.
766pub fn count_eq<X: Sized>(
767    left: &mut dyn Iterator<Item = X>,
768    right: &mut dyn Iterator<Item = X>,
769    mut eq_fn: impl FnMut(&X, &X) -> bool,
770) -> usize {
771    left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
772}
773
774/// Checks if two expressions evaluate to the same value, and don't contain any side effects.
775pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
776    SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
777}
778
779/// Returns the segments of a path that might have generic parameters.
780/// Usually just the last segment for free items, except for when the path resolves to an associated
781/// item, in which case it is the last two
782fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
783    match segments.last()?.res {
784        Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => {
785            // <Ty as module::Trait<T>>::assoc::<U>
786            //        ^^^^^^^^^^^^^^^^   ^^^^^^^^^^ segments: [module, Trait<T>, assoc<U>]
787            Some(&segments[segments.len().checked_sub(2)?..])
788        },
789        Res::Err => None,
790        _ => Some(slice::from_ref(segments.last()?)),
791    }
792}
793
794/// Type used to hash an ast element. This is different from the `Hash` trait
795/// on ast types as this
796/// trait would consider IDs and spans.
797///
798/// All expressions kind are hashed, but some might have a weaker hash.
799pub struct SpanlessHash<'a, 'tcx> {
800    /// Context used to evaluate constant expressions.
801    cx: &'a LateContext<'tcx>,
802    maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
803    s: FxHasher,
804    path_check: PathCheck,
805}
806
807impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
808    pub fn new(cx: &'a LateContext<'tcx>) -> Self {
809        Self {
810            cx,
811            maybe_typeck_results: cx.maybe_typeck_results(),
812            s: FxHasher::default(),
813            path_check: PathCheck::default(),
814        }
815    }
816
817    /// Check paths by their resolution instead of exact equality. See [`PathCheck`] for more
818    /// details.
819    #[must_use]
820    pub fn paths_by_resolution(self) -> Self {
821        Self {
822            path_check: PathCheck::Resolution,
823            ..self
824        }
825    }
826
827    pub fn finish(self) -> u64 {
828        self.s.finish()
829    }
830
831    pub fn hash_block(&mut self, b: &Block<'_>) {
832        for s in b.stmts {
833            self.hash_stmt(s);
834        }
835
836        if let Some(e) = b.expr {
837            self.hash_expr(e);
838        }
839
840        std::mem::discriminant(&b.rules).hash(&mut self.s);
841    }
842
843    #[expect(clippy::too_many_lines)]
844    pub fn hash_expr(&mut self, e: &Expr<'_>) {
845        let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
846            ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_local(e, e.span.ctxt())
847        });
848
849        // const hashing may result in the same hash as some unrelated node, so add a sort of
850        // discriminant depending on which path we're choosing next
851        simple_const.hash(&mut self.s);
852        if simple_const.is_some() {
853            return;
854        }
855
856        std::mem::discriminant(&e.kind).hash(&mut self.s);
857
858        match &e.kind {
859            ExprKind::AddrOf(kind, m, e) => {
860                std::mem::discriminant(kind).hash(&mut self.s);
861                m.hash(&mut self.s);
862                self.hash_expr(e);
863            },
864            ExprKind::Continue(i) => {
865                if let Some(i) = i.label {
866                    self.hash_name(i.ident.name);
867                }
868            },
869            ExprKind::Array(v) => {
870                self.hash_exprs(v);
871            },
872            ExprKind::Assign(l, r, _) => {
873                self.hash_expr(l);
874                self.hash_expr(r);
875            },
876            ExprKind::AssignOp(o, l, r) => {
877                std::mem::discriminant(&o.node).hash(&mut self.s);
878                self.hash_expr(l);
879                self.hash_expr(r);
880            },
881            ExprKind::Become(f) => {
882                self.hash_expr(f);
883            },
884            ExprKind::Block(b, _) => {
885                self.hash_block(b);
886            },
887            ExprKind::Binary(op, l, r) => {
888                std::mem::discriminant(&op.node).hash(&mut self.s);
889                self.hash_expr(l);
890                self.hash_expr(r);
891            },
892            ExprKind::Break(i, j) => {
893                if let Some(i) = i.label {
894                    self.hash_name(i.ident.name);
895                }
896                if let Some(j) = j {
897                    self.hash_expr(j);
898                }
899            },
900            ExprKind::Call(fun, args) => {
901                self.hash_expr(fun);
902                self.hash_exprs(args);
903            },
904            ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
905                self.hash_expr(e);
906                self.hash_ty(ty);
907            },
908            ExprKind::Closure(Closure {
909                capture_clause, body, ..
910            }) => {
911                std::mem::discriminant(capture_clause).hash(&mut self.s);
912                // closures inherit TypeckResults
913                self.hash_expr(self.cx.tcx.hir_body(*body).value);
914            },
915            ExprKind::ConstBlock(l_id) => {
916                self.hash_body(l_id.body);
917            },
918            ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
919                self.hash_expr(e);
920            },
921            ExprKind::Field(e, f) => {
922                self.hash_expr(e);
923                self.hash_name(f.name);
924            },
925            ExprKind::Index(a, i, _) => {
926                self.hash_expr(a);
927                self.hash_expr(i);
928            },
929            ExprKind::InlineAsm(asm) => {
930                for piece in asm.template {
931                    match piece {
932                        InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
933                        InlineAsmTemplatePiece::Placeholder {
934                            operand_idx,
935                            modifier,
936                            span: _,
937                        } => {
938                            operand_idx.hash(&mut self.s);
939                            modifier.hash(&mut self.s);
940                        },
941                    }
942                }
943                asm.options.hash(&mut self.s);
944                for (op, _op_sp) in asm.operands {
945                    match op {
946                        InlineAsmOperand::In { reg, expr } => {
947                            reg.hash(&mut self.s);
948                            self.hash_expr(expr);
949                        },
950                        InlineAsmOperand::Out { reg, late, expr } => {
951                            reg.hash(&mut self.s);
952                            late.hash(&mut self.s);
953                            if let Some(expr) = expr {
954                                self.hash_expr(expr);
955                            }
956                        },
957                        InlineAsmOperand::InOut { reg, late, expr } => {
958                            reg.hash(&mut self.s);
959                            late.hash(&mut self.s);
960                            self.hash_expr(expr);
961                        },
962                        InlineAsmOperand::SplitInOut {
963                            reg,
964                            late,
965                            in_expr,
966                            out_expr,
967                        } => {
968                            reg.hash(&mut self.s);
969                            late.hash(&mut self.s);
970                            self.hash_expr(in_expr);
971                            if let Some(out_expr) = out_expr {
972                                self.hash_expr(out_expr);
973                            }
974                        },
975                        InlineAsmOperand::SymFn { expr } => {
976                            self.hash_expr(expr);
977                        },
978                        InlineAsmOperand::Const { anon_const } => {
979                            self.hash_body(anon_const.body);
980                        },
981                        InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
982                        InlineAsmOperand::Label { block } => self.hash_block(block),
983                    }
984                }
985            },
986            ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
987                self.hash_expr(init);
988                if let Some(ty) = ty {
989                    self.hash_ty(ty);
990                }
991                self.hash_pat(pat);
992            },
993            ExprKind::Lit(l) => {
994                l.node.hash(&mut self.s);
995            },
996            ExprKind::Loop(b, i, ..) => {
997                self.hash_block(b);
998                if let Some(i) = i {
999                    self.hash_name(i.ident.name);
1000                }
1001            },
1002            ExprKind::If(cond, then, else_opt) => {
1003                self.hash_expr(cond);
1004                self.hash_expr(then);
1005                if let Some(e) = else_opt {
1006                    self.hash_expr(e);
1007                }
1008            },
1009            ExprKind::Match(scrutinee, arms, _) => {
1010                self.hash_expr(scrutinee);
1011
1012                for arm in *arms {
1013                    self.hash_pat(arm.pat);
1014                    if let Some(e) = arm.guard {
1015                        self.hash_expr(e);
1016                    }
1017                    self.hash_expr(arm.body);
1018                }
1019            },
1020            ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1021                self.hash_name(path.ident.name);
1022                self.hash_expr(receiver);
1023                self.hash_exprs(args);
1024            },
1025            ExprKind::OffsetOf(container, fields) => {
1026                self.hash_ty(container);
1027                for field in *fields {
1028                    self.hash_name(field.name);
1029                }
1030            },
1031            ExprKind::Path(qpath) => {
1032                self.hash_qpath(qpath);
1033            },
1034            ExprKind::Repeat(e, len) => {
1035                self.hash_expr(e);
1036                self.hash_const_arg(len);
1037            },
1038            ExprKind::Ret(e) => {
1039                if let Some(e) = e {
1040                    self.hash_expr(e);
1041                }
1042            },
1043            ExprKind::Struct(path, fields, expr) => {
1044                self.hash_qpath(path);
1045
1046                for f in *fields {
1047                    self.hash_name(f.ident.name);
1048                    self.hash_expr(f.expr);
1049                }
1050
1051                if let StructTailExpr::Base(e) = expr {
1052                    self.hash_expr(e);
1053                }
1054            },
1055            ExprKind::Tup(tup) => {
1056                self.hash_exprs(tup);
1057            },
1058            ExprKind::Use(expr, _) => {
1059                self.hash_expr(expr);
1060            },
1061            ExprKind::Unary(l_op, le) => {
1062                std::mem::discriminant(l_op).hash(&mut self.s);
1063                self.hash_expr(le);
1064            },
1065            ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1066                std::mem::discriminant(kind).hash(&mut self.s);
1067                self.hash_expr(expr);
1068                if let Some(ty) = ty {
1069                    self.hash_ty(ty);
1070                }
1071            },
1072            ExprKind::Err(_) => {},
1073        }
1074    }
1075
1076    pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1077        for e in e {
1078            self.hash_expr(e);
1079        }
1080    }
1081
1082    pub fn hash_name(&mut self, n: Symbol) {
1083        n.hash(&mut self.s);
1084    }
1085
1086    pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1087        match p {
1088            QPath::Resolved(_, path) => {
1089                self.hash_path(path);
1090            },
1091            QPath::TypeRelative(_, path) => {
1092                self.hash_name(path.ident.name);
1093            },
1094        }
1095        // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
1096    }
1097
1098    pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1099        std::mem::discriminant(&lit.kind).hash(&mut self.s);
1100        match &lit.kind {
1101            PatExprKind::Lit { lit, negated } => {
1102                lit.node.hash(&mut self.s);
1103                negated.hash(&mut self.s);
1104            },
1105            PatExprKind::ConstBlock(c) => self.hash_body(c.body),
1106            PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1107        }
1108    }
1109
1110    pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1111        std::mem::discriminant(&pat.kind).hash(&mut self.s);
1112        match pat.kind {
1113            TyPatKind::Range(s, e) => {
1114                self.hash_const_arg(s);
1115                self.hash_const_arg(e);
1116            },
1117            TyPatKind::Or(variants) => {
1118                for variant in variants {
1119                    self.hash_ty_pat(variant);
1120                }
1121            },
1122            TyPatKind::NotNull | TyPatKind::Err(_) => {},
1123        }
1124    }
1125
1126    pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1127        std::mem::discriminant(&pat.kind).hash(&mut self.s);
1128        match &pat.kind {
1129            PatKind::Missing => unreachable!(),
1130            PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1131                std::mem::discriminant(by_ref).hash(&mut self.s);
1132                if let ByRef::Yes(pi, mu) = by_ref {
1133                    std::mem::discriminant(pi).hash(&mut self.s);
1134                    std::mem::discriminant(mu).hash(&mut self.s);
1135                }
1136                std::mem::discriminant(mutability).hash(&mut self.s);
1137                if let Some(pat) = pat {
1138                    self.hash_pat(pat);
1139                }
1140            },
1141            PatKind::Box(pat) | PatKind::Deref(pat) => self.hash_pat(pat),
1142            PatKind::Expr(expr) => self.hash_pat_expr(expr),
1143            PatKind::Or(pats) => {
1144                for pat in *pats {
1145                    self.hash_pat(pat);
1146                }
1147            },
1148            PatKind::Range(s, e, i) => {
1149                if let Some(s) = s {
1150                    self.hash_pat_expr(s);
1151                }
1152                if let Some(e) = e {
1153                    self.hash_pat_expr(e);
1154                }
1155                std::mem::discriminant(i).hash(&mut self.s);
1156            },
1157            PatKind::Ref(pat, pi, mu) => {
1158                self.hash_pat(pat);
1159                std::mem::discriminant(pi).hash(&mut self.s);
1160                std::mem::discriminant(mu).hash(&mut self.s);
1161            },
1162            PatKind::Guard(pat, guard) => {
1163                self.hash_pat(pat);
1164                self.hash_expr(guard);
1165            },
1166            PatKind::Slice(l, m, r) => {
1167                for pat in *l {
1168                    self.hash_pat(pat);
1169                }
1170                if let Some(pat) = m {
1171                    self.hash_pat(pat);
1172                }
1173                for pat in *r {
1174                    self.hash_pat(pat);
1175                }
1176            },
1177            PatKind::Struct(qpath, fields, e) => {
1178                self.hash_qpath(qpath);
1179                for f in *fields {
1180                    self.hash_name(f.ident.name);
1181                    self.hash_pat(f.pat);
1182                }
1183                e.hash(&mut self.s);
1184            },
1185            PatKind::Tuple(pats, e) => {
1186                for pat in *pats {
1187                    self.hash_pat(pat);
1188                }
1189                e.hash(&mut self.s);
1190            },
1191            PatKind::TupleStruct(qpath, pats, e) => {
1192                self.hash_qpath(qpath);
1193                for pat in *pats {
1194                    self.hash_pat(pat);
1195                }
1196                e.hash(&mut self.s);
1197            },
1198            PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1199        }
1200    }
1201
1202    pub fn hash_path(&mut self, path: &Path<'_>) {
1203        match path.res {
1204            // constant hash since equality is dependant on inter-expression context
1205            // e.g. The expressions `if let Some(x) = foo() {}` and `if let Some(y) = foo() {}` are considered equal
1206            // even though the binding names are different and they have different `HirId`s.
1207            Res::Local(_) => 1_usize.hash(&mut self.s),
1208            _ => {
1209                if let PathCheck::Resolution = self.path_check
1210                    && let [.., last] = path.segments
1211                    && let Some(segments) = generic_path_segments(path.segments)
1212                {
1213                    for seg in segments {
1214                        self.hash_generic_args(seg.args().args);
1215                    }
1216                    last.res.hash(&mut self.s);
1217                } else {
1218                    for seg in path.segments {
1219                        self.hash_name(seg.ident.name);
1220                        self.hash_generic_args(seg.args().args);
1221                    }
1222                }
1223            },
1224        }
1225    }
1226
1227    pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1228        let TraitBoundModifiers { constness, polarity } = modifiers;
1229        std::mem::discriminant(&polarity).hash(&mut self.s);
1230        std::mem::discriminant(&constness).hash(&mut self.s);
1231    }
1232
1233    pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1234        std::mem::discriminant(&b.kind).hash(&mut self.s);
1235
1236        match &b.kind {
1237            StmtKind::Let(local) => {
1238                self.hash_pat(local.pat);
1239                if let Some(init) = local.init {
1240                    self.hash_expr(init);
1241                }
1242                if let Some(els) = local.els {
1243                    self.hash_block(els);
1244                }
1245            },
1246            StmtKind::Item(..) => {},
1247            StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1248                self.hash_expr(expr);
1249            },
1250        }
1251    }
1252
1253    pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1254        lifetime.ident.name.hash(&mut self.s);
1255        std::mem::discriminant(&lifetime.kind).hash(&mut self.s);
1256        if let LifetimeKind::Param(param_id) = lifetime.kind {
1257            param_id.hash(&mut self.s);
1258        }
1259    }
1260
1261    pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1262        std::mem::discriminant(&ty.kind).hash(&mut self.s);
1263        self.hash_tykind(&ty.kind);
1264    }
1265
1266    pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1267        match ty {
1268            TyKind::Slice(ty) => {
1269                self.hash_ty(ty);
1270            },
1271            TyKind::Array(ty, len) => {
1272                self.hash_ty(ty);
1273                self.hash_const_arg(len);
1274            },
1275            TyKind::Pat(ty, pat) => {
1276                self.hash_ty(ty);
1277                self.hash_ty_pat(pat);
1278            },
1279            TyKind::Ptr(mut_ty) => {
1280                self.hash_ty(mut_ty.ty);
1281                mut_ty.mutbl.hash(&mut self.s);
1282            },
1283            TyKind::Ref(lifetime, mut_ty) => {
1284                self.hash_lifetime(lifetime);
1285                self.hash_ty(mut_ty.ty);
1286                mut_ty.mutbl.hash(&mut self.s);
1287            },
1288            TyKind::FnPtr(fn_ptr) => {
1289                fn_ptr.safety.hash(&mut self.s);
1290                fn_ptr.abi.hash(&mut self.s);
1291                for arg in fn_ptr.decl.inputs {
1292                    self.hash_ty(arg);
1293                }
1294                std::mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1295                match fn_ptr.decl.output {
1296                    FnRetTy::DefaultReturn(_) => {},
1297                    FnRetTy::Return(ty) => {
1298                        self.hash_ty(ty);
1299                    },
1300                }
1301                fn_ptr.decl.c_variadic.hash(&mut self.s);
1302            },
1303            TyKind::Tup(ty_list) => {
1304                for ty in *ty_list {
1305                    self.hash_ty(ty);
1306                }
1307            },
1308            TyKind::Path(qpath) => self.hash_qpath(qpath),
1309            TyKind::TraitObject(_, lifetime) => {
1310                self.hash_lifetime(lifetime);
1311            },
1312            TyKind::Typeof(anon_const) => {
1313                self.hash_body(anon_const.body);
1314            },
1315            TyKind::UnsafeBinder(binder) => {
1316                self.hash_ty(binder.inner_ty);
1317            },
1318            TyKind::Err(_)
1319            | TyKind::Infer(())
1320            | TyKind::Never
1321            | TyKind::InferDelegation(..)
1322            | TyKind::OpaqueDef(_)
1323            | TyKind::TraitAscription(_) => {},
1324        }
1325    }
1326
1327    pub fn hash_body(&mut self, body_id: BodyId) {
1328        // swap out TypeckResults when hashing a body
1329        let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1330        self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1331        self.maybe_typeck_results = old_maybe_typeck_results;
1332    }
1333
1334    fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1335        match &const_arg.kind {
1336            ConstArgKind::Path(path) => self.hash_qpath(path),
1337            ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1338            ConstArgKind::Infer(..) | ConstArgKind::Error(..) => {},
1339        }
1340    }
1341
1342    fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1343        for arg in arg_list {
1344            match arg {
1345                GenericArg::Lifetime(l) => self.hash_lifetime(l),
1346                GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1347                GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1348                GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1349            }
1350        }
1351    }
1352}
1353
1354pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1355    let mut h = SpanlessHash::new(cx);
1356    h.hash_stmt(s);
1357    h.finish()
1358}
1359
1360pub fn is_bool(ty: &Ty<'_>) -> bool {
1361    if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1362        matches!(path.res, Res::PrimTy(PrimTy::Bool))
1363    } else {
1364        false
1365    }
1366}
1367
1368pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1369    let mut h = SpanlessHash::new(cx);
1370    h.hash_expr(e);
1371    h.finish()
1372}
1373
1374fn eq_span_tokens(
1375    cx: &LateContext<'_>,
1376    left: impl SpanRange,
1377    right: impl SpanRange,
1378    pred: impl Fn(TokenKind) -> bool,
1379) -> bool {
1380    fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1381        if let Some(lsrc) = left.get_source_range(cx)
1382            && let Some(lsrc) = lsrc.as_str()
1383            && let Some(rsrc) = right.get_source_range(cx)
1384            && let Some(rsrc) = rsrc.as_str()
1385        {
1386            let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1387            let map = |(_, source, _)| source;
1388
1389            let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1390            let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1391            ltok.eq(rtok)
1392        } else {
1393            // Unable to access the source. Conservatively assume the blocks aren't equal.
1394            false
1395        }
1396    }
1397    f(cx, left.into_range(), right.into_range(), pred)
1398}
1399
1400/// Returns true if the expression contains ambiguous literals (unsuffixed float or int literals)
1401/// that could be interpreted as either f32/f64 or i32/i64 depending on context.
1402pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1403    match expr.kind {
1404        ExprKind::Path(ref qpath) => {
1405            if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1406                && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1407                && local.ty.is_none()
1408                && let Some(init) = local.init
1409            {
1410                return has_ambiguous_literal_in_expr(cx, init);
1411            }
1412            false
1413        },
1414        ExprKind::Lit(lit) => matches!(
1415            lit.node,
1416            ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1417        ),
1418
1419        ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1420
1421        ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1422            has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1423        },
1424
1425        ExprKind::Unary(_, e)
1426        | ExprKind::Cast(e, _)
1427        | ExprKind::Type(e, _)
1428        | ExprKind::DropTemps(e)
1429        | ExprKind::AddrOf(_, _, e)
1430        | ExprKind::Field(e, _)
1431        | ExprKind::Index(e, _, _)
1432        | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1433
1434        ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1435            has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1436        },
1437
1438        ExprKind::Closure(Closure { body, .. }) => {
1439            let body = cx.tcx.hir_body(*body);
1440            let closure_expr = crate::peel_blocks(body.value);
1441            has_ambiguous_literal_in_expr(cx, closure_expr)
1442        },
1443
1444        ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1445
1446        ExprKind::If(cond, then_expr, else_expr) => {
1447            has_ambiguous_literal_in_expr(cx, cond)
1448                || has_ambiguous_literal_in_expr(cx, then_expr)
1449                || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1450        },
1451
1452        ExprKind::Match(scrutinee, arms, _) => {
1453            has_ambiguous_literal_in_expr(cx, scrutinee)
1454                || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1455        },
1456
1457        ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1458
1459        ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1460            opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1461        },
1462
1463        _ => false,
1464    }
1465}