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, Closure, ConstArg, ConstArgKind, Expr, ExprField,
12 ExprKind, FnRetTy, GenericArg, GenericArgs, HirId, HirIdMap, InlineAsmOperand, LetExpr, Lifetime, LifetimeKind,
13 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
24type SpanlessEqCallback<'a> = dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a;
27
28#[derive(Copy, Clone, Debug, Default)]
30pub enum PathCheck {
31 #[default]
36 Exact,
37 Resolution,
47}
48
49pub struct SpanlessEq<'a, 'tcx> {
55 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 #[must_use]
76 pub fn deny_side_effects(self) -> Self {
77 Self {
78 allow_side_effects: false,
79 ..self
80 }
81 }
82
83 #[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 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 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 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 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 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 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 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 continue;
216 }
217 if lstmt_span.lo < lstart || rstmt_span.lo < rstart {
218 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 return true;
252 } else if lend < lstart || rend < rstart {
253 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 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).eval_simple(left),
294 ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_rhs).eval_simple(right),
295 )
296 && l == r
297 {
298 return true;
299 }
300
301 let is_eq = match (
302 reduce_exprkind(self.inner.cx, &left.kind),
303 reduce_exprkind(self.inner.cx, &right.kind),
304 ) {
305 (ExprKind::AddrOf(lb, l_mut, le), ExprKind::AddrOf(rb, r_mut, re)) => {
306 lb == rb && l_mut == r_mut && self.eq_expr(le, re)
307 },
308 (ExprKind::Array(l), ExprKind::Array(r)) => self.eq_exprs(l, r),
309 (ExprKind::Assign(ll, lr, _), ExprKind::Assign(rl, rr, _)) => {
310 self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
311 },
312 (ExprKind::AssignOp(lo, ll, lr), ExprKind::AssignOp(ro, rl, rr)) => {
313 self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
314 },
315 (ExprKind::Block(l, _), ExprKind::Block(r, _)) => self.eq_block(l, r),
316 (ExprKind::Binary(l_op, ll, lr), ExprKind::Binary(r_op, rl, rr)) => {
317 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
318 || swap_binop(l_op.node, ll, lr).is_some_and(|(l_op, ll, lr)| {
319 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
320 })
321 },
322 (ExprKind::Break(li, le), ExprKind::Break(ri, re)) => {
323 both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
324 && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
325 },
326 (ExprKind::Call(l_fun, l_args), ExprKind::Call(r_fun, r_args)) => {
327 self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
328 },
329 (ExprKind::Cast(lx, lt), ExprKind::Cast(rx, rt)) => {
330 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
331 },
332 (ExprKind::Closure(_l), ExprKind::Closure(_r)) => false,
333 (ExprKind::ConstBlock(lb), ExprKind::ConstBlock(rb)) => self.eq_body(lb.body, rb.body),
334 (ExprKind::Continue(li), ExprKind::Continue(ri)) => {
335 both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
336 },
337 (ExprKind::DropTemps(le), ExprKind::DropTemps(re)) => self.eq_expr(le, re),
338 (ExprKind::Field(l_f_exp, l_f_ident), ExprKind::Field(r_f_exp, r_f_ident)) => {
339 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
340 },
341 (ExprKind::Index(la, li, _), ExprKind::Index(ra, ri, _)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
342 (ExprKind::If(lc, lt, le), ExprKind::If(rc, rt, re)) => {
343 self.eq_expr(lc, rc) && self.eq_expr(lt, rt)
344 && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
345 },
346 (ExprKind::Let(l), ExprKind::Let(r)) => {
347 self.eq_pat(l.pat, r.pat)
348 && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
349 && self.eq_expr(l.init, r.init)
350 },
351 (ExprKind::Lit(l), ExprKind::Lit(r)) => l.node == r.node,
352 (ExprKind::Loop(lb, ll, lls, _), ExprKind::Loop(rb, rl, rls, _)) => {
353 lls == rls && self.eq_block(lb, rb)
354 && both(ll.as_ref(), rl.as_ref(), |l, r| l.ident.name == r.ident.name)
355 },
356 (ExprKind::Match(le, la, ls), ExprKind::Match(re, ra, rs)) => {
357 (ls == rs || (matches!((ls, rs), (TryDesugar(_), TryDesugar(_)))))
358 && self.eq_expr(le, re)
359 && over(la, ra, |l, r| {
360 self.eq_pat(l.pat, r.pat)
361 && both(l.guard.as_ref(), r.guard.as_ref(), |l, r| self.eq_expr(l, r))
362 && self.eq_expr(l.body, r.body)
363 })
364 },
365 (
366 ExprKind::MethodCall(l_path, l_receiver, l_args, _),
367 ExprKind::MethodCall(r_path, r_receiver, r_args, _),
368 ) => {
369 self.inner.allow_side_effects
370 && self.eq_path_segment(l_path, r_path)
371 && self.eq_expr(l_receiver, r_receiver)
372 && self.eq_exprs(l_args, r_args)
373 },
374 (ExprKind::UnsafeBinderCast(lkind, le, None), ExprKind::UnsafeBinderCast(rkind, re, None)) =>
375 lkind == rkind && self.eq_expr(le, re),
376 (ExprKind::UnsafeBinderCast(lkind, le, Some(lt)), ExprKind::UnsafeBinderCast(rkind, re, Some(rt))) =>
377 lkind == rkind && self.eq_expr(le, re) && self.eq_ty(lt, rt),
378 (ExprKind::OffsetOf(l_container, l_fields), ExprKind::OffsetOf(r_container, r_fields)) => {
379 self.eq_ty(l_container, r_container) && over(l_fields, r_fields, |l, r| l.name == r.name)
380 },
381 (ExprKind::Path(l), ExprKind::Path(r)) => self.eq_qpath(l, r),
382 (ExprKind::Repeat(le, ll), ExprKind::Repeat(re, rl)) => {
383 self.eq_expr(le, re) && self.eq_const_arg(ll, rl)
384 },
385 (ExprKind::Ret(l), ExprKind::Ret(r)) => both(l.as_ref(), r.as_ref(), |l, r| self.eq_expr(l, r)),
386 (ExprKind::Struct(l_path, lf, lo), ExprKind::Struct(r_path, rf, ro)) => {
387 self.eq_qpath(l_path, r_path)
388 && match (lo, ro) {
389 (StructTailExpr::Base(l),StructTailExpr::Base(r)) => self.eq_expr(l, r),
390 (StructTailExpr::None, StructTailExpr::None) |
391 (StructTailExpr::DefaultFields(_), StructTailExpr::DefaultFields(_)) => true,
392 _ => false,
393 }
394 && over(lf, rf, |l, r| self.eq_expr_field(l, r))
395 },
396 (ExprKind::Tup(l_tup), ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
397 (ExprKind::Use(l_expr, _), ExprKind::Use(r_expr, _)) => self.eq_expr(l_expr, r_expr),
398 (ExprKind::Type(le, lt), ExprKind::Type(re, rt)) => self.eq_expr(le, re) && self.eq_ty(lt, rt),
399 (ExprKind::Unary(l_op, le), ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
400 (ExprKind::Yield(le, _), ExprKind::Yield(re, _)) => return self.eq_expr(le, re),
401 (
402 | ExprKind::AddrOf(..)
404 | ExprKind::Array(..)
405 | ExprKind::Assign(..)
406 | ExprKind::AssignOp(..)
407 | ExprKind::Binary(..)
408 | ExprKind::Become(..)
409 | ExprKind::Block(..)
410 | ExprKind::Break(..)
411 | ExprKind::Call(..)
412 | ExprKind::Cast(..)
413 | ExprKind::ConstBlock(..)
414 | ExprKind::Continue(..)
415 | ExprKind::DropTemps(..)
416 | ExprKind::Field(..)
417 | ExprKind::Index(..)
418 | ExprKind::If(..)
419 | ExprKind::Let(..)
420 | ExprKind::Lit(..)
421 | ExprKind::Loop(..)
422 | ExprKind::Match(..)
423 | ExprKind::MethodCall(..)
424 | ExprKind::OffsetOf(..)
425 | ExprKind::Path(..)
426 | ExprKind::Repeat(..)
427 | ExprKind::Ret(..)
428 | ExprKind::Struct(..)
429 | ExprKind::Tup(..)
430 | ExprKind::Use(..)
431 | ExprKind::Type(..)
432 | ExprKind::Unary(..)
433 | ExprKind::Yield(..)
434 | ExprKind::UnsafeBinderCast(..)
435
436 | ExprKind::Err(..)
441
442 | ExprKind::Closure(..)
445 | ExprKind::InlineAsm(_)
448 , _
449 ) => false,
450 };
451 (is_eq && (!self.should_ignore(left) || !self.should_ignore(right)))
452 || self.inner.expr_fallback.as_mut().is_some_and(|f| f(left, right))
453 }
454
455 fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
456 over(left, right, |l, r| self.eq_expr(l, r))
457 }
458
459 fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
460 left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
461 }
462
463 fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
464 match (left, right) {
465 (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_const_arg(l.as_unambig_ct(), r.as_unambig_ct()),
466 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
467 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty.as_unambig_ty(), r_ty.as_unambig_ty()),
468 (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
469 _ => false,
470 }
471 }
472
473 fn eq_const_arg(&mut self, left: &ConstArg<'_>, right: &ConstArg<'_>) -> bool {
474 match (&left.kind, &right.kind) {
475 (ConstArgKind::Path(l_p), ConstArgKind::Path(r_p)) => self.eq_qpath(l_p, r_p),
476 (ConstArgKind::Anon(l_an), ConstArgKind::Anon(r_an)) => self.eq_body(l_an.body, r_an.body),
477 (ConstArgKind::Infer(..), ConstArgKind::Infer(..)) => true,
478 (ConstArgKind::Path(..), ConstArgKind::Anon(..))
480 | (ConstArgKind::Anon(..), ConstArgKind::Path(..))
481 | (ConstArgKind::Infer(..), _)
482 | (_, ConstArgKind::Infer(..)) => false,
483 }
484 }
485
486 fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
487 left.kind == right.kind
488 }
489
490 fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
491 let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
492 li.name == ri.name && self.eq_pat(lp, rp)
493 }
494
495 fn eq_pat_expr(&mut self, left: &PatExpr<'_>, right: &PatExpr<'_>) -> bool {
496 match (&left.kind, &right.kind) {
497 (
498 PatExprKind::Lit {
499 lit: left,
500 negated: left_neg,
501 },
502 PatExprKind::Lit {
503 lit: right,
504 negated: right_neg,
505 },
506 ) => left_neg == right_neg && left.node == right.node,
507 (PatExprKind::ConstBlock(left), PatExprKind::ConstBlock(right)) => self.eq_body(left.body, right.body),
508 (PatExprKind::Path(left), PatExprKind::Path(right)) => self.eq_qpath(left, right),
509 (PatExprKind::Lit { .. } | PatExprKind::ConstBlock(..) | PatExprKind::Path(..), _) => false,
510 }
511 }
512
513 fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
515 match (&left.kind, &right.kind) {
516 (PatKind::Box(l), PatKind::Box(r)) => self.eq_pat(l, r),
517 (PatKind::Struct(lp, la, ..), PatKind::Struct(rp, ra, ..)) => {
518 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
519 },
520 (PatKind::TupleStruct(lp, la, ls), PatKind::TupleStruct(rp, ra, rs)) => {
521 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
522 },
523 (PatKind::Binding(lb, li, _, lp), PatKind::Binding(rb, ri, _, rp)) => {
524 let eq = lb == rb && both(lp.as_ref(), rp.as_ref(), |l, r| self.eq_pat(l, r));
525 if eq {
526 self.locals.insert(*li, *ri);
527 }
528 eq
529 },
530 (PatKind::Expr(l), PatKind::Expr(r)) => self.eq_pat_expr(l, r),
531 (PatKind::Tuple(l, ls), PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
532 (PatKind::Range(ls, le, li), PatKind::Range(rs, re, ri)) => {
533 both(ls.as_ref(), rs.as_ref(), |a, b| self.eq_pat_expr(a, b))
534 && both(le.as_ref(), re.as_ref(), |a, b| self.eq_pat_expr(a, b))
535 && (li == ri)
536 },
537 (PatKind::Ref(le, lm), PatKind::Ref(re, rm)) => lm == rm && self.eq_pat(le, re),
538 (PatKind::Slice(ls, li, le), PatKind::Slice(rs, ri, re)) => {
539 over(ls, rs, |l, r| self.eq_pat(l, r))
540 && over(le, re, |l, r| self.eq_pat(l, r))
541 && both(li.as_ref(), ri.as_ref(), |l, r| self.eq_pat(l, r))
542 },
543 (PatKind::Wild, PatKind::Wild) => true,
544 _ => false,
545 }
546 }
547
548 fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
549 match (left, right) {
550 (QPath::Resolved(lty, lpath), QPath::Resolved(rty, rpath)) => {
551 both(lty.as_ref(), rty.as_ref(), |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
552 },
553 (QPath::TypeRelative(lty, lseg), QPath::TypeRelative(rty, rseg)) => {
554 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
555 },
556 (QPath::LangItem(llang_item, ..), QPath::LangItem(rlang_item, ..)) => llang_item == rlang_item,
557 _ => false,
558 }
559 }
560
561 pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
562 match (left.res, right.res) {
563 (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
564 (Res::Local(_), _) | (_, Res::Local(_)) => false,
565 _ => self.eq_path_segments(left.segments, right.segments),
566 }
567 }
568
569 fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
570 if left.parenthesized == right.parenthesized {
571 over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) && over(left.constraints, right.constraints, |l, r| self.eq_assoc_eq_constraint(l, r))
573 } else {
574 false
575 }
576 }
577
578 pub fn eq_path_segments<'tcx>(
579 &mut self,
580 mut left: &'tcx [PathSegment<'tcx>],
581 mut right: &'tcx [PathSegment<'tcx>],
582 ) -> bool {
583 if let PathCheck::Resolution = self.inner.path_check
584 && let Some(left_seg) = generic_path_segments(left)
585 && let Some(right_seg) = generic_path_segments(right)
586 {
587 left = left_seg;
590 right = right_seg;
591 }
592
593 over(left, right, |l, r| self.eq_path_segment(l, r))
594 }
595
596 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
597 if !self.eq_path_parameters(left.args(), right.args()) {
598 return false;
599 }
600
601 if let PathCheck::Resolution = self.inner.path_check
602 && left.res != Res::Err
603 && right.res != Res::Err
604 {
605 left.res == right.res
606 } else {
607 left.ident.name == right.ident.name
610 }
611 }
612
613 pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
614 match (&left.kind, &right.kind) {
615 (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
616 (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
617 (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
618 (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
619 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
620 },
621 (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
622 (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
623 (TyKind::Infer(()), TyKind::Infer(())) => true,
624 _ => false,
625 }
626 }
627
628 fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
631 left.ident.name == right.ident.name
633 && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
634 || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
635 }
636
637 fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> bool {
638 if self.left_ctxt == left && self.right_ctxt == right {
639 return true;
640 } else if self.left_ctxt == left || self.right_ctxt == right {
641 return false;
643 } else if left != SyntaxContext::root() {
644 let mut left_data = left.outer_expn_data();
645 let mut right_data = right.outer_expn_data();
646 loop {
647 use TokenKind::{BlockComment, LineComment, Whitespace};
648 if left_data.macro_def_id != right_data.macro_def_id
649 || (matches!(
650 left_data.kind,
651 ExpnKind::Macro(MacroKind::Bang, name)
652 if name == sym::cfg || name == sym::option_env
653 ) && !eq_span_tokens(self.inner.cx, left_data.call_site, right_data.call_site, |t| {
654 !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. })
655 }))
656 {
657 return false;
659 }
660 let left_ctxt = left_data.call_site.ctxt();
661 let right_ctxt = right_data.call_site.ctxt();
662 if left_ctxt == SyntaxContext::root() && right_ctxt == SyntaxContext::root() {
663 break;
664 }
665 if left_ctxt == SyntaxContext::root() || right_ctxt == SyntaxContext::root() {
666 return false;
669 }
670 left_data = left_ctxt.outer_expn_data();
671 right_data = right_ctxt.outer_expn_data();
672 }
673 }
674 self.left_ctxt = left;
675 self.right_ctxt = right;
676 true
677 }
678}
679
680fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
682 if let ExprKind::Block(block, _) = kind {
683 match (block.stmts, block.expr) {
684 ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
687 ([], None)
689 if block.span.check_source_text(cx, |src| {
690 tokenize(src, FrontmatterAllowed::No)
691 .map(|t| t.kind)
692 .filter(|t| {
693 !matches!(
694 t,
695 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
696 )
697 })
698 .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
699 }) =>
700 {
701 &ExprKind::Tup(&[])
702 },
703 ([], Some(expr)) => match expr.kind {
704 ExprKind::Ret(..) => &expr.kind,
706 _ => kind,
707 },
708 ([stmt], None) => match stmt.kind {
709 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
710 ExprKind::Ret(..) => &expr.kind,
712 _ => kind,
713 },
714 _ => kind,
715 },
716 _ => kind,
717 }
718 } else {
719 kind
720 }
721}
722
723fn swap_binop<'a>(
724 binop: BinOpKind,
725 lhs: &'a Expr<'a>,
726 rhs: &'a Expr<'a>,
727) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
728 match binop {
729 BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
730 Some((binop, rhs, lhs))
731 },
732 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
733 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
734 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
735 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
736 BinOpKind::Mul | BinOpKind::Shl
738 | BinOpKind::Shr
739 | BinOpKind::Rem
740 | BinOpKind::Sub
741 | BinOpKind::Div
742 | BinOpKind::And
743 | BinOpKind::Or => None,
744 }
745}
746
747pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
750 l.as_ref()
751 .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
752}
753
754pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
756 l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
757}
758
759pub fn over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
761 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
762}
763
764pub fn count_eq<X: Sized>(
766 left: &mut dyn Iterator<Item = X>,
767 right: &mut dyn Iterator<Item = X>,
768 mut eq_fn: impl FnMut(&X, &X) -> bool,
769) -> usize {
770 left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
771}
772
773pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
775 SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
776}
777
778fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
782 match segments.last()?.res {
783 Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => {
784 Some(&segments[segments.len().checked_sub(2)?..])
787 },
788 Res::Err => None,
789 _ => Some(slice::from_ref(segments.last()?)),
790 }
791}
792
793pub struct SpanlessHash<'a, 'tcx> {
799 cx: &'a LateContext<'tcx>,
801 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
802 s: FxHasher,
803 path_check: PathCheck,
804}
805
806impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
807 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
808 Self {
809 cx,
810 maybe_typeck_results: cx.maybe_typeck_results(),
811 s: FxHasher::default(),
812 path_check: PathCheck::default(),
813 }
814 }
815
816 #[must_use]
819 pub fn paths_by_resolution(self) -> Self {
820 Self {
821 path_check: PathCheck::Resolution,
822 ..self
823 }
824 }
825
826 pub fn finish(self) -> u64 {
827 self.s.finish()
828 }
829
830 pub fn hash_block(&mut self, b: &Block<'_>) {
831 for s in b.stmts {
832 self.hash_stmt(s);
833 }
834
835 if let Some(e) = b.expr {
836 self.hash_expr(e);
837 }
838
839 std::mem::discriminant(&b.rules).hash(&mut self.s);
840 }
841
842 #[expect(clippy::too_many_lines)]
843 pub fn hash_expr(&mut self, e: &Expr<'_>) {
844 let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
845 ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_simple(e)
846 });
847
848 simple_const.hash(&mut self.s);
851 if simple_const.is_some() {
852 return;
853 }
854
855 std::mem::discriminant(&e.kind).hash(&mut self.s);
856
857 match &e.kind {
858 ExprKind::AddrOf(kind, m, e) => {
859 std::mem::discriminant(kind).hash(&mut self.s);
860 m.hash(&mut self.s);
861 self.hash_expr(e);
862 },
863 ExprKind::Continue(i) => {
864 if let Some(i) = i.label {
865 self.hash_name(i.ident.name);
866 }
867 },
868 ExprKind::Array(v) => {
869 self.hash_exprs(v);
870 },
871 ExprKind::Assign(l, r, _) => {
872 self.hash_expr(l);
873 self.hash_expr(r);
874 },
875 ExprKind::AssignOp(o, l, r) => {
876 std::mem::discriminant(&o.node).hash(&mut self.s);
877 self.hash_expr(l);
878 self.hash_expr(r);
879 },
880 ExprKind::Become(f) => {
881 self.hash_expr(f);
882 },
883 ExprKind::Block(b, _) => {
884 self.hash_block(b);
885 },
886 ExprKind::Binary(op, l, r) => {
887 std::mem::discriminant(&op.node).hash(&mut self.s);
888 self.hash_expr(l);
889 self.hash_expr(r);
890 },
891 ExprKind::Break(i, j) => {
892 if let Some(i) = i.label {
893 self.hash_name(i.ident.name);
894 }
895 if let Some(j) = j {
896 self.hash_expr(j);
897 }
898 },
899 ExprKind::Call(fun, args) => {
900 self.hash_expr(fun);
901 self.hash_exprs(args);
902 },
903 ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
904 self.hash_expr(e);
905 self.hash_ty(ty);
906 },
907 ExprKind::Closure(Closure {
908 capture_clause, body, ..
909 }) => {
910 std::mem::discriminant(capture_clause).hash(&mut self.s);
911 self.hash_expr(self.cx.tcx.hir_body(*body).value);
913 },
914 ExprKind::ConstBlock(l_id) => {
915 self.hash_body(l_id.body);
916 },
917 ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
918 self.hash_expr(e);
919 },
920 ExprKind::Field(e, f) => {
921 self.hash_expr(e);
922 self.hash_name(f.name);
923 },
924 ExprKind::Index(a, i, _) => {
925 self.hash_expr(a);
926 self.hash_expr(i);
927 },
928 ExprKind::InlineAsm(asm) => {
929 for piece in asm.template {
930 match piece {
931 InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
932 InlineAsmTemplatePiece::Placeholder {
933 operand_idx,
934 modifier,
935 span: _,
936 } => {
937 operand_idx.hash(&mut self.s);
938 modifier.hash(&mut self.s);
939 },
940 }
941 }
942 asm.options.hash(&mut self.s);
943 for (op, _op_sp) in asm.operands {
944 match op {
945 InlineAsmOperand::In { reg, expr } => {
946 reg.hash(&mut self.s);
947 self.hash_expr(expr);
948 },
949 InlineAsmOperand::Out { reg, late, expr } => {
950 reg.hash(&mut self.s);
951 late.hash(&mut self.s);
952 if let Some(expr) = expr {
953 self.hash_expr(expr);
954 }
955 },
956 InlineAsmOperand::InOut { reg, late, expr } => {
957 reg.hash(&mut self.s);
958 late.hash(&mut self.s);
959 self.hash_expr(expr);
960 },
961 InlineAsmOperand::SplitInOut {
962 reg,
963 late,
964 in_expr,
965 out_expr,
966 } => {
967 reg.hash(&mut self.s);
968 late.hash(&mut self.s);
969 self.hash_expr(in_expr);
970 if let Some(out_expr) = out_expr {
971 self.hash_expr(out_expr);
972 }
973 },
974 InlineAsmOperand::SymFn { expr } => {
975 self.hash_expr(expr);
976 },
977 InlineAsmOperand::Const { anon_const } => {
978 self.hash_body(anon_const.body);
979 },
980 InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
981 InlineAsmOperand::Label { block } => self.hash_block(block),
982 }
983 }
984 },
985 ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
986 self.hash_expr(init);
987 if let Some(ty) = ty {
988 self.hash_ty(ty);
989 }
990 self.hash_pat(pat);
991 },
992 ExprKind::Lit(l) => {
993 l.node.hash(&mut self.s);
994 },
995 ExprKind::Loop(b, i, ..) => {
996 self.hash_block(b);
997 if let Some(i) = i {
998 self.hash_name(i.ident.name);
999 }
1000 },
1001 ExprKind::If(cond, then, else_opt) => {
1002 self.hash_expr(cond);
1003 self.hash_expr(then);
1004 if let Some(e) = else_opt {
1005 self.hash_expr(e);
1006 }
1007 },
1008 ExprKind::Match(scrutinee, arms, _) => {
1009 self.hash_expr(scrutinee);
1010
1011 for arm in *arms {
1012 self.hash_pat(arm.pat);
1013 if let Some(e) = arm.guard {
1014 self.hash_expr(e);
1015 }
1016 self.hash_expr(arm.body);
1017 }
1018 },
1019 ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1020 self.hash_name(path.ident.name);
1021 self.hash_expr(receiver);
1022 self.hash_exprs(args);
1023 },
1024 ExprKind::OffsetOf(container, fields) => {
1025 self.hash_ty(container);
1026 for field in *fields {
1027 self.hash_name(field.name);
1028 }
1029 },
1030 ExprKind::Path(qpath) => {
1031 self.hash_qpath(qpath);
1032 },
1033 ExprKind::Repeat(e, len) => {
1034 self.hash_expr(e);
1035 self.hash_const_arg(len);
1036 },
1037 ExprKind::Ret(e) => {
1038 if let Some(e) = e {
1039 self.hash_expr(e);
1040 }
1041 },
1042 ExprKind::Struct(path, fields, expr) => {
1043 self.hash_qpath(path);
1044
1045 for f in *fields {
1046 self.hash_name(f.ident.name);
1047 self.hash_expr(f.expr);
1048 }
1049
1050 if let StructTailExpr::Base(e) = expr {
1051 self.hash_expr(e);
1052 }
1053 },
1054 ExprKind::Tup(tup) => {
1055 self.hash_exprs(tup);
1056 },
1057 ExprKind::Use(expr, _) => {
1058 self.hash_expr(expr);
1059 },
1060 ExprKind::Unary(l_op, le) => {
1061 std::mem::discriminant(l_op).hash(&mut self.s);
1062 self.hash_expr(le);
1063 },
1064 ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1065 std::mem::discriminant(kind).hash(&mut self.s);
1066 self.hash_expr(expr);
1067 if let Some(ty) = ty {
1068 self.hash_ty(ty);
1069 }
1070 },
1071 ExprKind::Err(_) => {},
1072 }
1073 }
1074
1075 pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1076 for e in e {
1077 self.hash_expr(e);
1078 }
1079 }
1080
1081 pub fn hash_name(&mut self, n: Symbol) {
1082 n.hash(&mut self.s);
1083 }
1084
1085 pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1086 match p {
1087 QPath::Resolved(_, path) => {
1088 self.hash_path(path);
1089 },
1090 QPath::TypeRelative(_, path) => {
1091 self.hash_name(path.ident.name);
1092 },
1093 QPath::LangItem(lang_item, ..) => {
1094 std::mem::discriminant(lang_item).hash(&mut self.s);
1095 },
1096 }
1097 }
1099
1100 pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1101 std::mem::discriminant(&lit.kind).hash(&mut self.s);
1102 match &lit.kind {
1103 PatExprKind::Lit { lit, negated } => {
1104 lit.node.hash(&mut self.s);
1105 negated.hash(&mut self.s);
1106 },
1107 PatExprKind::ConstBlock(c) => self.hash_body(c.body),
1108 PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1109 }
1110 }
1111
1112 pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1113 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1114 match pat.kind {
1115 TyPatKind::Range(s, e) => {
1116 self.hash_const_arg(s);
1117 self.hash_const_arg(e);
1118 },
1119 TyPatKind::Or(variants) => {
1120 for variant in variants {
1121 self.hash_ty_pat(variant);
1122 }
1123 },
1124 TyPatKind::Err(_) => {},
1125 }
1126 }
1127
1128 pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1129 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1130 match &pat.kind {
1131 PatKind::Missing => unreachable!(),
1132 PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1133 std::mem::discriminant(by_ref).hash(&mut self.s);
1134 std::mem::discriminant(mutability).hash(&mut self.s);
1135 if let Some(pat) = pat {
1136 self.hash_pat(pat);
1137 }
1138 },
1139 PatKind::Box(pat) | PatKind::Deref(pat) => self.hash_pat(pat),
1140 PatKind::Expr(expr) => self.hash_pat_expr(expr),
1141 PatKind::Or(pats) => {
1142 for pat in *pats {
1143 self.hash_pat(pat);
1144 }
1145 },
1146 PatKind::Range(s, e, i) => {
1147 if let Some(s) = s {
1148 self.hash_pat_expr(s);
1149 }
1150 if let Some(e) = e {
1151 self.hash_pat_expr(e);
1152 }
1153 std::mem::discriminant(i).hash(&mut self.s);
1154 },
1155 PatKind::Ref(pat, mu) => {
1156 self.hash_pat(pat);
1157 std::mem::discriminant(mu).hash(&mut self.s);
1158 },
1159 PatKind::Guard(pat, guard) => {
1160 self.hash_pat(pat);
1161 self.hash_expr(guard);
1162 },
1163 PatKind::Slice(l, m, r) => {
1164 for pat in *l {
1165 self.hash_pat(pat);
1166 }
1167 if let Some(pat) = m {
1168 self.hash_pat(pat);
1169 }
1170 for pat in *r {
1171 self.hash_pat(pat);
1172 }
1173 },
1174 PatKind::Struct(qpath, fields, e) => {
1175 self.hash_qpath(qpath);
1176 for f in *fields {
1177 self.hash_name(f.ident.name);
1178 self.hash_pat(f.pat);
1179 }
1180 e.hash(&mut self.s);
1181 },
1182 PatKind::Tuple(pats, e) => {
1183 for pat in *pats {
1184 self.hash_pat(pat);
1185 }
1186 e.hash(&mut self.s);
1187 },
1188 PatKind::TupleStruct(qpath, pats, e) => {
1189 self.hash_qpath(qpath);
1190 for pat in *pats {
1191 self.hash_pat(pat);
1192 }
1193 e.hash(&mut self.s);
1194 },
1195 PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1196 }
1197 }
1198
1199 pub fn hash_path(&mut self, path: &Path<'_>) {
1200 match path.res {
1201 Res::Local(_) => 1_usize.hash(&mut self.s),
1205 _ => {
1206 if let PathCheck::Resolution = self.path_check
1207 && let [.., last] = path.segments
1208 && let Some(segments) = generic_path_segments(path.segments)
1209 {
1210 for seg in segments {
1211 self.hash_generic_args(seg.args().args);
1212 }
1213 last.res.hash(&mut self.s);
1214 } else {
1215 for seg in path.segments {
1216 self.hash_name(seg.ident.name);
1217 self.hash_generic_args(seg.args().args);
1218 }
1219 }
1220 },
1221 }
1222 }
1223
1224 pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1225 let TraitBoundModifiers { constness, polarity } = modifiers;
1226 std::mem::discriminant(&polarity).hash(&mut self.s);
1227 std::mem::discriminant(&constness).hash(&mut self.s);
1228 }
1229
1230 pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1231 std::mem::discriminant(&b.kind).hash(&mut self.s);
1232
1233 match &b.kind {
1234 StmtKind::Let(local) => {
1235 self.hash_pat(local.pat);
1236 if let Some(init) = local.init {
1237 self.hash_expr(init);
1238 }
1239 if let Some(els) = local.els {
1240 self.hash_block(els);
1241 }
1242 },
1243 StmtKind::Item(..) => {},
1244 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1245 self.hash_expr(expr);
1246 },
1247 }
1248 }
1249
1250 pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1251 lifetime.ident.name.hash(&mut self.s);
1252 std::mem::discriminant(&lifetime.kind).hash(&mut self.s);
1253 if let LifetimeKind::Param(param_id) = lifetime.kind {
1254 param_id.hash(&mut self.s);
1255 }
1256 }
1257
1258 pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1259 std::mem::discriminant(&ty.kind).hash(&mut self.s);
1260 self.hash_tykind(&ty.kind);
1261 }
1262
1263 pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1264 match ty {
1265 TyKind::Slice(ty) => {
1266 self.hash_ty(ty);
1267 },
1268 TyKind::Array(ty, len) => {
1269 self.hash_ty(ty);
1270 self.hash_const_arg(len);
1271 },
1272 TyKind::Pat(ty, pat) => {
1273 self.hash_ty(ty);
1274 self.hash_ty_pat(pat);
1275 },
1276 TyKind::Ptr(mut_ty) => {
1277 self.hash_ty(mut_ty.ty);
1278 mut_ty.mutbl.hash(&mut self.s);
1279 },
1280 TyKind::Ref(lifetime, mut_ty) => {
1281 self.hash_lifetime(lifetime);
1282 self.hash_ty(mut_ty.ty);
1283 mut_ty.mutbl.hash(&mut self.s);
1284 },
1285 TyKind::FnPtr(fn_ptr) => {
1286 fn_ptr.safety.hash(&mut self.s);
1287 fn_ptr.abi.hash(&mut self.s);
1288 for arg in fn_ptr.decl.inputs {
1289 self.hash_ty(arg);
1290 }
1291 std::mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1292 match fn_ptr.decl.output {
1293 FnRetTy::DefaultReturn(_) => {},
1294 FnRetTy::Return(ty) => {
1295 self.hash_ty(ty);
1296 },
1297 }
1298 fn_ptr.decl.c_variadic.hash(&mut self.s);
1299 },
1300 TyKind::Tup(ty_list) => {
1301 for ty in *ty_list {
1302 self.hash_ty(ty);
1303 }
1304 },
1305 TyKind::Path(qpath) => self.hash_qpath(qpath),
1306 TyKind::TraitObject(_, lifetime) => {
1307 self.hash_lifetime(lifetime);
1308 },
1309 TyKind::Typeof(anon_const) => {
1310 self.hash_body(anon_const.body);
1311 },
1312 TyKind::UnsafeBinder(binder) => {
1313 self.hash_ty(binder.inner_ty);
1314 },
1315 TyKind::Err(_)
1316 | TyKind::Infer(())
1317 | TyKind::Never
1318 | TyKind::InferDelegation(..)
1319 | TyKind::OpaqueDef(_)
1320 | TyKind::TraitAscription(_) => {},
1321 }
1322 }
1323
1324 pub fn hash_body(&mut self, body_id: BodyId) {
1325 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1327 self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1328 self.maybe_typeck_results = old_maybe_typeck_results;
1329 }
1330
1331 fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1332 match &const_arg.kind {
1333 ConstArgKind::Path(path) => self.hash_qpath(path),
1334 ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1335 ConstArgKind::Infer(..) => {},
1336 }
1337 }
1338
1339 fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1340 for arg in arg_list {
1341 match arg {
1342 GenericArg::Lifetime(l) => self.hash_lifetime(l),
1343 GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1344 GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1345 GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1346 }
1347 }
1348 }
1349}
1350
1351pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1352 let mut h = SpanlessHash::new(cx);
1353 h.hash_stmt(s);
1354 h.finish()
1355}
1356
1357pub fn is_bool(ty: &Ty<'_>) -> bool {
1358 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1359 matches!(path.res, Res::PrimTy(PrimTy::Bool))
1360 } else {
1361 false
1362 }
1363}
1364
1365pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1366 let mut h = SpanlessHash::new(cx);
1367 h.hash_expr(e);
1368 h.finish()
1369}
1370
1371fn eq_span_tokens(
1372 cx: &LateContext<'_>,
1373 left: impl SpanRange,
1374 right: impl SpanRange,
1375 pred: impl Fn(TokenKind) -> bool,
1376) -> bool {
1377 fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1378 if let Some(lsrc) = left.get_source_range(cx)
1379 && let Some(lsrc) = lsrc.as_str()
1380 && let Some(rsrc) = right.get_source_range(cx)
1381 && let Some(rsrc) = rsrc.as_str()
1382 {
1383 let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1384 let map = |(_, source, _)| source;
1385
1386 let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1387 let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1388 ltok.eq(rtok)
1389 } else {
1390 false
1392 }
1393 }
1394 f(cx, left.into_range(), right.into_range(), pred)
1395}
1396
1397pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1400 match expr.kind {
1401 ExprKind::Path(ref qpath) => {
1402 if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1403 && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1404 && local.ty.is_none()
1405 && let Some(init) = local.init
1406 {
1407 return has_ambiguous_literal_in_expr(cx, init);
1408 }
1409 false
1410 },
1411 ExprKind::Lit(lit) => matches!(
1412 lit.node,
1413 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1414 ),
1415
1416 ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1417
1418 ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1419 has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1420 },
1421
1422 ExprKind::Unary(_, e)
1423 | ExprKind::Cast(e, _)
1424 | ExprKind::Type(e, _)
1425 | ExprKind::DropTemps(e)
1426 | ExprKind::AddrOf(_, _, e)
1427 | ExprKind::Field(e, _)
1428 | ExprKind::Index(e, _, _)
1429 | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1430
1431 ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1432 has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1433 },
1434
1435 ExprKind::Closure(Closure { body, .. }) => {
1436 let body = cx.tcx.hir_body(*body);
1437 let closure_expr = crate::peel_blocks(body.value);
1438 has_ambiguous_literal_in_expr(cx, closure_expr)
1439 },
1440
1441 ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1442
1443 ExprKind::If(cond, then_expr, else_expr) => {
1444 has_ambiguous_literal_in_expr(cx, cond)
1445 || has_ambiguous_literal_in_expr(cx, then_expr)
1446 || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1447 },
1448
1449 ExprKind::Match(scrutinee, arms, _) => {
1450 has_ambiguous_literal_in_expr(cx, scrutinee)
1451 || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1452 },
1453
1454 ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1455
1456 ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1457 opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1458 },
1459
1460 _ => false,
1461 }
1462}