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)
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 | 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 | ExprKind::Err(..)
443
444 | ExprKind::Closure(..)
447 | 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 (ConstArgKind::Path(..), ConstArgKind::Anon(..))
482 | (ConstArgKind::Anon(..), ConstArgKind::Path(..))
483 | (ConstArgKind::Infer(..), _)
484 | (_, ConstArgKind::Infer(..)) => 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 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, lm), PatKind::Ref(re, rm)) => 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 (QPath::LangItem(llang_item, ..), QPath::LangItem(rlang_item, ..)) => llang_item == rlang_item,
559 _ => false,
560 }
561 }
562
563 pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
564 match (left.res, right.res) {
565 (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
566 (Res::Local(_), _) | (_, Res::Local(_)) => false,
567 _ => self.eq_path_segments(left.segments, right.segments),
568 }
569 }
570
571 fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
572 if left.parenthesized == right.parenthesized {
573 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))
575 } else {
576 false
577 }
578 }
579
580 pub fn eq_path_segments<'tcx>(
581 &mut self,
582 mut left: &'tcx [PathSegment<'tcx>],
583 mut right: &'tcx [PathSegment<'tcx>],
584 ) -> bool {
585 if let PathCheck::Resolution = self.inner.path_check
586 && let Some(left_seg) = generic_path_segments(left)
587 && let Some(right_seg) = generic_path_segments(right)
588 {
589 left = left_seg;
592 right = right_seg;
593 }
594
595 over(left, right, |l, r| self.eq_path_segment(l, r))
596 }
597
598 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
599 if !self.eq_path_parameters(left.args(), right.args()) {
600 return false;
601 }
602
603 if let PathCheck::Resolution = self.inner.path_check
604 && left.res != Res::Err
605 && right.res != Res::Err
606 {
607 left.res == right.res
608 } else {
609 left.ident.name == right.ident.name
612 }
613 }
614
615 pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
616 match (&left.kind, &right.kind) {
617 (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
618 (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
619 (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
620 (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
621 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
622 },
623 (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
624 (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
625 (TyKind::Infer(()), TyKind::Infer(())) => true,
626 _ => false,
627 }
628 }
629
630 fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
633 left.ident.name == right.ident.name
635 && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
636 || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
637 }
638
639 fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> bool {
640 if self.left_ctxt == left && self.right_ctxt == right {
641 return true;
642 } else if self.left_ctxt == left || self.right_ctxt == right {
643 return false;
645 } else if left != SyntaxContext::root() {
646 let mut left_data = left.outer_expn_data();
647 let mut right_data = right.outer_expn_data();
648 loop {
649 use TokenKind::{BlockComment, LineComment, Whitespace};
650 if left_data.macro_def_id != right_data.macro_def_id
651 || (matches!(
652 left_data.kind,
653 ExpnKind::Macro(MacroKind::Bang, name)
654 if name == sym::cfg || name == sym::option_env
655 ) && !eq_span_tokens(self.inner.cx, left_data.call_site, right_data.call_site, |t| {
656 !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. })
657 }))
658 {
659 return false;
661 }
662 let left_ctxt = left_data.call_site.ctxt();
663 let right_ctxt = right_data.call_site.ctxt();
664 if left_ctxt == SyntaxContext::root() && right_ctxt == SyntaxContext::root() {
665 break;
666 }
667 if left_ctxt == SyntaxContext::root() || right_ctxt == SyntaxContext::root() {
668 return false;
671 }
672 left_data = left_ctxt.outer_expn_data();
673 right_data = right_ctxt.outer_expn_data();
674 }
675 }
676 self.left_ctxt = left;
677 self.right_ctxt = right;
678 true
679 }
680}
681
682fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
684 if let ExprKind::Block(block, _) = kind {
685 match (block.stmts, block.expr) {
686 ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
689 ([], None)
691 if block.span.check_source_text(cx, |src| {
692 tokenize(src, FrontmatterAllowed::No)
693 .map(|t| t.kind)
694 .filter(|t| {
695 !matches!(
696 t,
697 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
698 )
699 })
700 .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
701 }) =>
702 {
703 &ExprKind::Tup(&[])
704 },
705 ([], Some(expr)) => match expr.kind {
706 ExprKind::Ret(..) => &expr.kind,
708 _ => kind,
709 },
710 ([stmt], None) => match stmt.kind {
711 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
712 ExprKind::Ret(..) => &expr.kind,
714 _ => kind,
715 },
716 _ => kind,
717 },
718 _ => kind,
719 }
720 } else {
721 kind
722 }
723}
724
725fn swap_binop<'a>(
726 binop: BinOpKind,
727 lhs: &'a Expr<'a>,
728 rhs: &'a Expr<'a>,
729) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
730 match binop {
731 BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
732 Some((binop, rhs, lhs))
733 },
734 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
735 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
736 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
737 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
738 BinOpKind::Mul | BinOpKind::Shl
740 | BinOpKind::Shr
741 | BinOpKind::Rem
742 | BinOpKind::Sub
743 | BinOpKind::Div
744 | BinOpKind::And
745 | BinOpKind::Or => None,
746 }
747}
748
749pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
752 l.as_ref()
753 .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
754}
755
756pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
758 l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
759}
760
761pub fn over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
763 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
764}
765
766pub fn count_eq<X: Sized>(
768 left: &mut dyn Iterator<Item = X>,
769 right: &mut dyn Iterator<Item = X>,
770 mut eq_fn: impl FnMut(&X, &X) -> bool,
771) -> usize {
772 left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
773}
774
775pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
777 SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
778}
779
780fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
784 match segments.last()?.res {
785 Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => {
786 Some(&segments[segments.len().checked_sub(2)?..])
789 },
790 Res::Err => None,
791 _ => Some(slice::from_ref(segments.last()?)),
792 }
793}
794
795pub struct SpanlessHash<'a, 'tcx> {
801 cx: &'a LateContext<'tcx>,
803 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
804 s: FxHasher,
805 path_check: PathCheck,
806}
807
808impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
809 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
810 Self {
811 cx,
812 maybe_typeck_results: cx.maybe_typeck_results(),
813 s: FxHasher::default(),
814 path_check: PathCheck::default(),
815 }
816 }
817
818 #[must_use]
821 pub fn paths_by_resolution(self) -> Self {
822 Self {
823 path_check: PathCheck::Resolution,
824 ..self
825 }
826 }
827
828 pub fn finish(self) -> u64 {
829 self.s.finish()
830 }
831
832 pub fn hash_block(&mut self, b: &Block<'_>) {
833 for s in b.stmts {
834 self.hash_stmt(s);
835 }
836
837 if let Some(e) = b.expr {
838 self.hash_expr(e);
839 }
840
841 std::mem::discriminant(&b.rules).hash(&mut self.s);
842 }
843
844 #[expect(clippy::too_many_lines)]
845 pub fn hash_expr(&mut self, e: &Expr<'_>) {
846 let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
847 ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_local(e, e.span.ctxt())
848 });
849
850 simple_const.hash(&mut self.s);
853 if simple_const.is_some() {
854 return;
855 }
856
857 std::mem::discriminant(&e.kind).hash(&mut self.s);
858
859 match &e.kind {
860 ExprKind::AddrOf(kind, m, e) => {
861 std::mem::discriminant(kind).hash(&mut self.s);
862 m.hash(&mut self.s);
863 self.hash_expr(e);
864 },
865 ExprKind::Continue(i) => {
866 if let Some(i) = i.label {
867 self.hash_name(i.ident.name);
868 }
869 },
870 ExprKind::Array(v) => {
871 self.hash_exprs(v);
872 },
873 ExprKind::Assign(l, r, _) => {
874 self.hash_expr(l);
875 self.hash_expr(r);
876 },
877 ExprKind::AssignOp(o, l, r) => {
878 std::mem::discriminant(&o.node).hash(&mut self.s);
879 self.hash_expr(l);
880 self.hash_expr(r);
881 },
882 ExprKind::Become(f) => {
883 self.hash_expr(f);
884 },
885 ExprKind::Block(b, _) => {
886 self.hash_block(b);
887 },
888 ExprKind::Binary(op, l, r) => {
889 std::mem::discriminant(&op.node).hash(&mut self.s);
890 self.hash_expr(l);
891 self.hash_expr(r);
892 },
893 ExprKind::Break(i, j) => {
894 if let Some(i) = i.label {
895 self.hash_name(i.ident.name);
896 }
897 if let Some(j) = j {
898 self.hash_expr(j);
899 }
900 },
901 ExprKind::Call(fun, args) => {
902 self.hash_expr(fun);
903 self.hash_exprs(args);
904 },
905 ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
906 self.hash_expr(e);
907 self.hash_ty(ty);
908 },
909 ExprKind::Closure(Closure {
910 capture_clause, body, ..
911 }) => {
912 std::mem::discriminant(capture_clause).hash(&mut self.s);
913 self.hash_expr(self.cx.tcx.hir_body(*body).value);
915 },
916 ExprKind::ConstBlock(l_id) => {
917 self.hash_body(l_id.body);
918 },
919 ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
920 self.hash_expr(e);
921 },
922 ExprKind::Field(e, f) => {
923 self.hash_expr(e);
924 self.hash_name(f.name);
925 },
926 ExprKind::Index(a, i, _) => {
927 self.hash_expr(a);
928 self.hash_expr(i);
929 },
930 ExprKind::InlineAsm(asm) => {
931 for piece in asm.template {
932 match piece {
933 InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
934 InlineAsmTemplatePiece::Placeholder {
935 operand_idx,
936 modifier,
937 span: _,
938 } => {
939 operand_idx.hash(&mut self.s);
940 modifier.hash(&mut self.s);
941 },
942 }
943 }
944 asm.options.hash(&mut self.s);
945 for (op, _op_sp) in asm.operands {
946 match op {
947 InlineAsmOperand::In { reg, expr } => {
948 reg.hash(&mut self.s);
949 self.hash_expr(expr);
950 },
951 InlineAsmOperand::Out { reg, late, expr } => {
952 reg.hash(&mut self.s);
953 late.hash(&mut self.s);
954 if let Some(expr) = expr {
955 self.hash_expr(expr);
956 }
957 },
958 InlineAsmOperand::InOut { reg, late, expr } => {
959 reg.hash(&mut self.s);
960 late.hash(&mut self.s);
961 self.hash_expr(expr);
962 },
963 InlineAsmOperand::SplitInOut {
964 reg,
965 late,
966 in_expr,
967 out_expr,
968 } => {
969 reg.hash(&mut self.s);
970 late.hash(&mut self.s);
971 self.hash_expr(in_expr);
972 if let Some(out_expr) = out_expr {
973 self.hash_expr(out_expr);
974 }
975 },
976 InlineAsmOperand::SymFn { expr } => {
977 self.hash_expr(expr);
978 },
979 InlineAsmOperand::Const { anon_const } => {
980 self.hash_body(anon_const.body);
981 },
982 InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
983 InlineAsmOperand::Label { block } => self.hash_block(block),
984 }
985 }
986 },
987 ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
988 self.hash_expr(init);
989 if let Some(ty) = ty {
990 self.hash_ty(ty);
991 }
992 self.hash_pat(pat);
993 },
994 ExprKind::Lit(l) => {
995 l.node.hash(&mut self.s);
996 },
997 ExprKind::Loop(b, i, ..) => {
998 self.hash_block(b);
999 if let Some(i) = i {
1000 self.hash_name(i.ident.name);
1001 }
1002 },
1003 ExprKind::If(cond, then, else_opt) => {
1004 self.hash_expr(cond);
1005 self.hash_expr(then);
1006 if let Some(e) = else_opt {
1007 self.hash_expr(e);
1008 }
1009 },
1010 ExprKind::Match(scrutinee, arms, _) => {
1011 self.hash_expr(scrutinee);
1012
1013 for arm in *arms {
1014 self.hash_pat(arm.pat);
1015 if let Some(e) = arm.guard {
1016 self.hash_expr(e);
1017 }
1018 self.hash_expr(arm.body);
1019 }
1020 },
1021 ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1022 self.hash_name(path.ident.name);
1023 self.hash_expr(receiver);
1024 self.hash_exprs(args);
1025 },
1026 ExprKind::OffsetOf(container, fields) => {
1027 self.hash_ty(container);
1028 for field in *fields {
1029 self.hash_name(field.name);
1030 }
1031 },
1032 ExprKind::Path(qpath) => {
1033 self.hash_qpath(qpath);
1034 },
1035 ExprKind::Repeat(e, len) => {
1036 self.hash_expr(e);
1037 self.hash_const_arg(len);
1038 },
1039 ExprKind::Ret(e) => {
1040 if let Some(e) = e {
1041 self.hash_expr(e);
1042 }
1043 },
1044 ExprKind::Struct(path, fields, expr) => {
1045 self.hash_qpath(path);
1046
1047 for f in *fields {
1048 self.hash_name(f.ident.name);
1049 self.hash_expr(f.expr);
1050 }
1051
1052 if let StructTailExpr::Base(e) = expr {
1053 self.hash_expr(e);
1054 }
1055 },
1056 ExprKind::Tup(tup) => {
1057 self.hash_exprs(tup);
1058 },
1059 ExprKind::Use(expr, _) => {
1060 self.hash_expr(expr);
1061 },
1062 ExprKind::Unary(l_op, le) => {
1063 std::mem::discriminant(l_op).hash(&mut self.s);
1064 self.hash_expr(le);
1065 },
1066 ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1067 std::mem::discriminant(kind).hash(&mut self.s);
1068 self.hash_expr(expr);
1069 if let Some(ty) = ty {
1070 self.hash_ty(ty);
1071 }
1072 },
1073 ExprKind::Err(_) => {},
1074 }
1075 }
1076
1077 pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1078 for e in e {
1079 self.hash_expr(e);
1080 }
1081 }
1082
1083 pub fn hash_name(&mut self, n: Symbol) {
1084 n.hash(&mut self.s);
1085 }
1086
1087 pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1088 match p {
1089 QPath::Resolved(_, path) => {
1090 self.hash_path(path);
1091 },
1092 QPath::TypeRelative(_, path) => {
1093 self.hash_name(path.ident.name);
1094 },
1095 QPath::LangItem(lang_item, ..) => {
1096 std::mem::discriminant(lang_item).hash(&mut self.s);
1097 },
1098 }
1099 }
1101
1102 pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1103 std::mem::discriminant(&lit.kind).hash(&mut self.s);
1104 match &lit.kind {
1105 PatExprKind::Lit { lit, negated } => {
1106 lit.node.hash(&mut self.s);
1107 negated.hash(&mut self.s);
1108 },
1109 PatExprKind::ConstBlock(c) => self.hash_body(c.body),
1110 PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1111 }
1112 }
1113
1114 pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1115 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1116 match pat.kind {
1117 TyPatKind::Range(s, e) => {
1118 self.hash_const_arg(s);
1119 self.hash_const_arg(e);
1120 },
1121 TyPatKind::Or(variants) => {
1122 for variant in variants {
1123 self.hash_ty_pat(variant);
1124 }
1125 },
1126 TyPatKind::NotNull | TyPatKind::Err(_) => {},
1127 }
1128 }
1129
1130 pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1131 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1132 match &pat.kind {
1133 PatKind::Missing => unreachable!(),
1134 PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1135 std::mem::discriminant(by_ref).hash(&mut self.s);
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, mu) => {
1158 self.hash_pat(pat);
1159 std::mem::discriminant(mu).hash(&mut self.s);
1160 },
1161 PatKind::Guard(pat, guard) => {
1162 self.hash_pat(pat);
1163 self.hash_expr(guard);
1164 },
1165 PatKind::Slice(l, m, r) => {
1166 for pat in *l {
1167 self.hash_pat(pat);
1168 }
1169 if let Some(pat) = m {
1170 self.hash_pat(pat);
1171 }
1172 for pat in *r {
1173 self.hash_pat(pat);
1174 }
1175 },
1176 PatKind::Struct(qpath, fields, e) => {
1177 self.hash_qpath(qpath);
1178 for f in *fields {
1179 self.hash_name(f.ident.name);
1180 self.hash_pat(f.pat);
1181 }
1182 e.hash(&mut self.s);
1183 },
1184 PatKind::Tuple(pats, e) => {
1185 for pat in *pats {
1186 self.hash_pat(pat);
1187 }
1188 e.hash(&mut self.s);
1189 },
1190 PatKind::TupleStruct(qpath, pats, e) => {
1191 self.hash_qpath(qpath);
1192 for pat in *pats {
1193 self.hash_pat(pat);
1194 }
1195 e.hash(&mut self.s);
1196 },
1197 PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1198 }
1199 }
1200
1201 pub fn hash_path(&mut self, path: &Path<'_>) {
1202 match path.res {
1203 Res::Local(_) => 1_usize.hash(&mut self.s),
1207 _ => {
1208 if let PathCheck::Resolution = self.path_check
1209 && let [.., last] = path.segments
1210 && let Some(segments) = generic_path_segments(path.segments)
1211 {
1212 for seg in segments {
1213 self.hash_generic_args(seg.args().args);
1214 }
1215 last.res.hash(&mut self.s);
1216 } else {
1217 for seg in path.segments {
1218 self.hash_name(seg.ident.name);
1219 self.hash_generic_args(seg.args().args);
1220 }
1221 }
1222 },
1223 }
1224 }
1225
1226 pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1227 let TraitBoundModifiers { constness, polarity } = modifiers;
1228 std::mem::discriminant(&polarity).hash(&mut self.s);
1229 std::mem::discriminant(&constness).hash(&mut self.s);
1230 }
1231
1232 pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1233 std::mem::discriminant(&b.kind).hash(&mut self.s);
1234
1235 match &b.kind {
1236 StmtKind::Let(local) => {
1237 self.hash_pat(local.pat);
1238 if let Some(init) = local.init {
1239 self.hash_expr(init);
1240 }
1241 if let Some(els) = local.els {
1242 self.hash_block(els);
1243 }
1244 },
1245 StmtKind::Item(..) => {},
1246 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1247 self.hash_expr(expr);
1248 },
1249 }
1250 }
1251
1252 pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1253 lifetime.ident.name.hash(&mut self.s);
1254 std::mem::discriminant(&lifetime.kind).hash(&mut self.s);
1255 if let LifetimeKind::Param(param_id) = lifetime.kind {
1256 param_id.hash(&mut self.s);
1257 }
1258 }
1259
1260 pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1261 std::mem::discriminant(&ty.kind).hash(&mut self.s);
1262 self.hash_tykind(&ty.kind);
1263 }
1264
1265 pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1266 match ty {
1267 TyKind::Slice(ty) => {
1268 self.hash_ty(ty);
1269 },
1270 TyKind::Array(ty, len) => {
1271 self.hash_ty(ty);
1272 self.hash_const_arg(len);
1273 },
1274 TyKind::Pat(ty, pat) => {
1275 self.hash_ty(ty);
1276 self.hash_ty_pat(pat);
1277 },
1278 TyKind::Ptr(mut_ty) => {
1279 self.hash_ty(mut_ty.ty);
1280 mut_ty.mutbl.hash(&mut self.s);
1281 },
1282 TyKind::Ref(lifetime, mut_ty) => {
1283 self.hash_lifetime(lifetime);
1284 self.hash_ty(mut_ty.ty);
1285 mut_ty.mutbl.hash(&mut self.s);
1286 },
1287 TyKind::FnPtr(fn_ptr) => {
1288 fn_ptr.safety.hash(&mut self.s);
1289 fn_ptr.abi.hash(&mut self.s);
1290 for arg in fn_ptr.decl.inputs {
1291 self.hash_ty(arg);
1292 }
1293 std::mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1294 match fn_ptr.decl.output {
1295 FnRetTy::DefaultReturn(_) => {},
1296 FnRetTy::Return(ty) => {
1297 self.hash_ty(ty);
1298 },
1299 }
1300 fn_ptr.decl.c_variadic.hash(&mut self.s);
1301 },
1302 TyKind::Tup(ty_list) => {
1303 for ty in *ty_list {
1304 self.hash_ty(ty);
1305 }
1306 },
1307 TyKind::Path(qpath) => self.hash_qpath(qpath),
1308 TyKind::TraitObject(_, lifetime) => {
1309 self.hash_lifetime(lifetime);
1310 },
1311 TyKind::Typeof(anon_const) => {
1312 self.hash_body(anon_const.body);
1313 },
1314 TyKind::UnsafeBinder(binder) => {
1315 self.hash_ty(binder.inner_ty);
1316 },
1317 TyKind::Err(_)
1318 | TyKind::Infer(())
1319 | TyKind::Never
1320 | TyKind::InferDelegation(..)
1321 | TyKind::OpaqueDef(_)
1322 | TyKind::TraitAscription(_) => {},
1323 }
1324 }
1325
1326 pub fn hash_body(&mut self, body_id: BodyId) {
1327 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1329 self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1330 self.maybe_typeck_results = old_maybe_typeck_results;
1331 }
1332
1333 fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1334 match &const_arg.kind {
1335 ConstArgKind::Path(path) => self.hash_qpath(path),
1336 ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1337 ConstArgKind::Infer(..) => {},
1338 }
1339 }
1340
1341 fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1342 for arg in arg_list {
1343 match arg {
1344 GenericArg::Lifetime(l) => self.hash_lifetime(l),
1345 GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1346 GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1347 GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1348 }
1349 }
1350 }
1351}
1352
1353pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1354 let mut h = SpanlessHash::new(cx);
1355 h.hash_stmt(s);
1356 h.finish()
1357}
1358
1359pub fn is_bool(ty: &Ty<'_>) -> bool {
1360 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1361 matches!(path.res, Res::PrimTy(PrimTy::Bool))
1362 } else {
1363 false
1364 }
1365}
1366
1367pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1368 let mut h = SpanlessHash::new(cx);
1369 h.hash_expr(e);
1370 h.finish()
1371}
1372
1373fn eq_span_tokens(
1374 cx: &LateContext<'_>,
1375 left: impl SpanRange,
1376 right: impl SpanRange,
1377 pred: impl Fn(TokenKind) -> bool,
1378) -> bool {
1379 fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1380 if let Some(lsrc) = left.get_source_range(cx)
1381 && let Some(lsrc) = lsrc.as_str()
1382 && let Some(rsrc) = right.get_source_range(cx)
1383 && let Some(rsrc) = rsrc.as_str()
1384 {
1385 let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1386 let map = |(_, source, _)| source;
1387
1388 let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1389 let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1390 ltok.eq(rtok)
1391 } else {
1392 false
1394 }
1395 }
1396 f(cx, left.into_range(), right.into_range(), pred)
1397}
1398
1399pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1402 match expr.kind {
1403 ExprKind::Path(ref qpath) => {
1404 if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1405 && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1406 && local.ty.is_none()
1407 && let Some(init) = local.init
1408 {
1409 return has_ambiguous_literal_in_expr(cx, init);
1410 }
1411 false
1412 },
1413 ExprKind::Lit(lit) => matches!(
1414 lit.node,
1415 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1416 ),
1417
1418 ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1419
1420 ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1421 has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1422 },
1423
1424 ExprKind::Unary(_, e)
1425 | ExprKind::Cast(e, _)
1426 | ExprKind::Type(e, _)
1427 | ExprKind::DropTemps(e)
1428 | ExprKind::AddrOf(_, _, e)
1429 | ExprKind::Field(e, _)
1430 | ExprKind::Index(e, _, _)
1431 | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1432
1433 ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1434 has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1435 },
1436
1437 ExprKind::Closure(Closure { body, .. }) => {
1438 let body = cx.tcx.hir_body(*body);
1439 let closure_expr = crate::peel_blocks(body.value);
1440 has_ambiguous_literal_in_expr(cx, closure_expr)
1441 },
1442
1443 ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1444
1445 ExprKind::If(cond, then_expr, else_expr) => {
1446 has_ambiguous_literal_in_expr(cx, cond)
1447 || has_ambiguous_literal_in_expr(cx, then_expr)
1448 || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1449 },
1450
1451 ExprKind::Match(scrutinee, arms, _) => {
1452 has_ambiguous_literal_in_expr(cx, scrutinee)
1453 || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1454 },
1455
1456 ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1457
1458 ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1459 opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1460 },
1461
1462 _ => false,
1463 }
1464}