1use crate::consts::ConstEvalCtxt;
2use crate::macros::macro_backtrace;
3use crate::source::{SpanRange, SpanRangeExt, walk_span_to_context};
4use crate::{sym, tokenize_with_text};
5use rustc_ast::ast;
6use rustc_ast::ast::InlineAsmTemplatePiece;
7use rustc_data_structures::fx::{FxHasher, FxIndexMap};
8use rustc_hir::MatchSource::TryDesugar;
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::{
12 AssocItemConstraint, BinOpKind, BindingMode, Block, BodyId, ByRef, Closure, ConstArg, ConstArgKind, ConstItemRhs,
13 Expr, ExprField, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericArgs, GenericBound, GenericBounds,
14 GenericParam, GenericParamKind, GenericParamSource, Generics, HirId, HirIdMap, InlineAsmOperand, ItemId, ItemKind,
15 LetExpr, Lifetime, LifetimeKind, LifetimeParamKind, Node, ParamName, Pat, PatExpr, PatExprKind, PatField, PatKind,
16 Path, PathSegment, PreciseCapturingArgKind, PrimTy, QPath, Stmt, StmtKind, StructTailExpr, TraitBoundModifiers, Ty,
17 TyFieldPath, TyKind, TyPat, TyPatKind, UseKind, WherePredicate, WherePredicateKind,
18};
19use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize};
20use rustc_lint::LateContext;
21use rustc_middle::ty::TypeckResults;
22use rustc_span::{BytePos, ExpnKind, MacroKind, Symbol, SyntaxContext};
23use std::hash::{Hash, Hasher};
24use std::ops::Range;
25use std::slice;
26
27type SpanlessEqCallback<'a, 'tcx> =
30 dyn FnMut(&TypeckResults<'tcx>, &Expr<'_>, &TypeckResults<'tcx>, &Expr<'_>) -> bool + 'a;
31
32#[derive(Copy, Clone, Debug, Default)]
34pub enum PathCheck {
35 #[default]
40 Exact,
41 Resolution,
51}
52
53pub struct SpanlessEq<'a, 'tcx> {
59 cx: &'a LateContext<'tcx>,
61 maybe_typeck_results: Option<(&'tcx TypeckResults<'tcx>, &'tcx TypeckResults<'tcx>)>,
62 allow_side_effects: bool,
63 expr_fallback: Option<Box<SpanlessEqCallback<'a, 'tcx>>>,
64 path_check: PathCheck,
65}
66
67impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
68 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
69 Self {
70 cx,
71 maybe_typeck_results: cx.maybe_typeck_results().map(|x| (x, x)),
72 allow_side_effects: true,
73 expr_fallback: None,
74 path_check: PathCheck::default(),
75 }
76 }
77
78 #[must_use]
80 pub fn deny_side_effects(self) -> Self {
81 Self {
82 allow_side_effects: false,
83 ..self
84 }
85 }
86
87 #[must_use]
90 pub fn paths_by_resolution(self) -> Self {
91 Self {
92 path_check: PathCheck::Resolution,
93 ..self
94 }
95 }
96
97 #[must_use]
98 pub fn expr_fallback(
99 self,
100 expr_fallback: impl FnMut(&TypeckResults<'tcx>, &Expr<'_>, &TypeckResults<'tcx>, &Expr<'_>) -> bool + 'a,
101 ) -> Self {
102 Self {
103 expr_fallback: Some(Box::new(expr_fallback)),
104 ..self
105 }
106 }
107
108 pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
111 HirEqInterExpr {
112 inner: self,
113 left_ctxt: SyntaxContext::root(),
114 right_ctxt: SyntaxContext::root(),
115 locals: HirIdMap::default(),
116 local_items: FxIndexMap::default(),
117 }
118 }
119
120 pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
121 self.inter_expr().eq_block(left, right)
122 }
123
124 pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
125 self.inter_expr().eq_expr(left, right)
126 }
127
128 pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
129 self.inter_expr().eq_path(left, right)
130 }
131
132 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
133 self.inter_expr().eq_path_segment(left, right)
134 }
135
136 pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
137 self.inter_expr().eq_path_segments(left, right)
138 }
139
140 pub fn eq_modifiers(left: TraitBoundModifiers, right: TraitBoundModifiers) -> bool {
141 std::mem::discriminant(&left.constness) == std::mem::discriminant(&right.constness)
142 && std::mem::discriminant(&left.polarity) == std::mem::discriminant(&right.polarity)
143 }
144}
145
146pub struct HirEqInterExpr<'a, 'b, 'tcx> {
147 inner: &'a mut SpanlessEq<'b, 'tcx>,
148 left_ctxt: SyntaxContext,
149 right_ctxt: SyntaxContext,
150
151 pub locals: HirIdMap<HirId>,
155 pub local_items: FxIndexMap<DefId, DefId>,
156}
157
158impl HirEqInterExpr<'_, '_, '_> {
159 pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
160 match (&left.kind, &right.kind) {
161 (StmtKind::Let(l), StmtKind::Let(r)) => {
162 if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
165 let l_ty = typeck_lhs.pat_ty(l.pat);
166 let r_ty = typeck_rhs.pat_ty(r.pat);
167 if l_ty != r_ty {
168 return false;
169 }
170 }
171
172 both(l.init.as_ref(), r.init.as_ref(), |l, r| self.eq_expr(l, r))
175 && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
176 && both(l.els.as_ref(), r.els.as_ref(), |l, r| self.eq_block(l, r))
177 && self.eq_pat(l.pat, r.pat)
178 },
179 (StmtKind::Expr(l), StmtKind::Expr(r)) | (StmtKind::Semi(l), StmtKind::Semi(r)) => self.eq_expr(l, r),
180 (StmtKind::Item(l), StmtKind::Item(r)) => self.eq_item(*l, *r),
181 _ => false,
182 }
183 }
184
185 pub fn eq_item(&mut self, l: ItemId, r: ItemId) -> bool {
186 let left = self.inner.cx.tcx.hir_item(l);
187 let right = self.inner.cx.tcx.hir_item(r);
188 let eq = match (left.kind, right.kind) {
189 (
190 ItemKind::Const(l_ident, l_generics, l_ty, ConstItemRhs::Body(l_body)),
191 ItemKind::Const(r_ident, r_generics, r_ty, ConstItemRhs::Body(r_body)),
192 ) => {
193 l_ident.name == r_ident.name
194 && self.eq_generics(l_generics, r_generics)
195 && self.eq_ty(l_ty, r_ty)
196 && self.eq_body(l_body, r_body)
197 },
198 (ItemKind::Static(l_mut, l_ident, l_ty, l_body), ItemKind::Static(r_mut, r_ident, r_ty, r_body)) => {
199 l_mut == r_mut && l_ident.name == r_ident.name && self.eq_ty(l_ty, r_ty) && self.eq_body(l_body, r_body)
200 },
201 (
202 ItemKind::Fn {
203 sig: l_sig,
204 ident: l_ident,
205 generics: l_generics,
206 body: l_body,
207 has_body: l_has_body,
208 },
209 ItemKind::Fn {
210 sig: r_sig,
211 ident: r_ident,
212 generics: r_generics,
213 body: r_body,
214 has_body: r_has_body,
215 },
216 ) => {
217 l_ident.name == r_ident.name
218 && (l_has_body == r_has_body)
219 && self.eq_fn_sig(&l_sig, &r_sig)
220 && self.eq_generics(l_generics, r_generics)
221 && self.eq_body(l_body, r_body)
222 },
223 (ItemKind::TyAlias(l_ident, l_generics, l_ty), ItemKind::TyAlias(r_ident, r_generics, r_ty)) => {
224 l_ident.name == r_ident.name && self.eq_generics(l_generics, r_generics) && self.eq_ty(l_ty, r_ty)
225 },
226 (ItemKind::Use(l_path, l_kind), ItemKind::Use(r_path, r_kind)) => {
227 self.eq_path_segments(l_path.segments, r_path.segments)
228 && match (l_kind, r_kind) {
229 (UseKind::Single(l_ident), UseKind::Single(r_ident)) => l_ident.name == r_ident.name,
230 (UseKind::Glob, UseKind::Glob) | (UseKind::ListStem, UseKind::ListStem) => true,
231 _ => false,
232 }
233 },
234 (ItemKind::Mod(l_ident, l_mod), ItemKind::Mod(r_ident, r_mod)) => {
235 l_ident.name == r_ident.name && over(l_mod.item_ids, r_mod.item_ids, |l, r| self.eq_item(*l, *r))
236 },
237 _ => false,
238 };
239 if eq {
240 self.local_items.insert(l.owner_id.to_def_id(), r.owner_id.to_def_id());
241 }
242 eq
243 }
244
245 fn eq_fn_sig(&mut self, left: &FnSig<'_>, right: &FnSig<'_>) -> bool {
246 left.header.safety == right.header.safety
247 && left.header.constness == right.header.constness
248 && left.header.asyncness == right.header.asyncness
249 && left.header.abi == right.header.abi
250 && self.eq_fn_decl(left.decl, right.decl)
251 }
252
253 fn eq_fn_decl(&mut self, left: &FnDecl<'_>, right: &FnDecl<'_>) -> bool {
254 over(left.inputs, right.inputs, |l, r| self.eq_ty(l, r))
255 && (match (left.output, right.output) {
256 (FnRetTy::DefaultReturn(_), FnRetTy::DefaultReturn(_)) => true,
257 (FnRetTy::Return(l_ty), FnRetTy::Return(r_ty)) => self.eq_ty(l_ty, r_ty),
258 _ => false,
259 })
260 && left.c_variadic == right.c_variadic
261 && left.implicit_self == right.implicit_self
262 && left.lifetime_elision_allowed == right.lifetime_elision_allowed
263 }
264
265 fn eq_generics(&mut self, left: &Generics<'_>, right: &Generics<'_>) -> bool {
266 self.eq_generics_param(left.params, right.params)
267 && self.eq_generics_predicate(left.predicates, right.predicates)
268 }
269
270 fn eq_generics_predicate(&mut self, left: &[WherePredicate<'_>], right: &[WherePredicate<'_>]) -> bool {
271 over(left, right, |l, r| match (l.kind, r.kind) {
272 (WherePredicateKind::BoundPredicate(l_bound), WherePredicateKind::BoundPredicate(r_bound)) => {
273 l_bound.origin == r_bound.origin
274 && self.eq_ty(l_bound.bounded_ty, r_bound.bounded_ty)
275 && self.eq_generics_param(l_bound.bound_generic_params, r_bound.bound_generic_params)
276 && self.eq_generics_bound(l_bound.bounds, r_bound.bounds)
277 },
278 (WherePredicateKind::RegionPredicate(l_region), WherePredicateKind::RegionPredicate(r_region)) => {
279 Self::eq_lifetime(l_region.lifetime, r_region.lifetime)
280 && self.eq_generics_bound(l_region.bounds, r_region.bounds)
281 },
282 (WherePredicateKind::EqPredicate(l_eq), WherePredicateKind::EqPredicate(r_eq)) => {
283 self.eq_ty(l_eq.lhs_ty, r_eq.lhs_ty)
284 },
285 _ => false,
286 })
287 }
288
289 fn eq_generics_bound(&mut self, left: GenericBounds<'_>, right: GenericBounds<'_>) -> bool {
290 over(left, right, |l, r| match (l, r) {
291 (GenericBound::Trait(l_trait), GenericBound::Trait(r_trait)) => {
292 l_trait.modifiers == r_trait.modifiers
293 && self.eq_path(l_trait.trait_ref.path, r_trait.trait_ref.path)
294 && self.eq_generics_param(l_trait.bound_generic_params, r_trait.bound_generic_params)
295 },
296 (GenericBound::Outlives(l_lifetime), GenericBound::Outlives(r_lifetime)) => {
297 Self::eq_lifetime(l_lifetime, r_lifetime)
298 },
299 (GenericBound::Use(l_capture, _), GenericBound::Use(r_capture, _)) => {
300 over(l_capture, r_capture, |l, r| match (l, r) {
301 (PreciseCapturingArgKind::Lifetime(l_lifetime), PreciseCapturingArgKind::Lifetime(r_lifetime)) => {
302 Self::eq_lifetime(l_lifetime, r_lifetime)
303 },
304 (PreciseCapturingArgKind::Param(l_param), PreciseCapturingArgKind::Param(r_param)) => {
305 l_param.ident == r_param.ident && l_param.res == r_param.res
306 },
307 _ => false,
308 })
309 },
310 _ => false,
311 })
312 }
313
314 fn eq_generics_param(&mut self, left: &[GenericParam<'_>], right: &[GenericParam<'_>]) -> bool {
315 over(left, right, |l, r| {
316 (match (l.name, r.name) {
317 (ParamName::Plain(l_ident), ParamName::Plain(r_ident))
318 | (ParamName::Error(l_ident), ParamName::Error(r_ident)) => l_ident.name == r_ident.name,
319 (ParamName::Fresh, ParamName::Fresh) => true,
320 _ => false,
321 }) && l.pure_wrt_drop == r.pure_wrt_drop
322 && self.eq_generics_param_kind(&l.kind, &r.kind)
323 && (matches!(
324 (l.source, r.source),
325 (GenericParamSource::Generics, GenericParamSource::Generics)
326 | (GenericParamSource::Binder, GenericParamSource::Binder)
327 ))
328 })
329 }
330
331 fn eq_generics_param_kind(&mut self, left: &GenericParamKind<'_>, right: &GenericParamKind<'_>) -> bool {
332 match (left, right) {
333 (GenericParamKind::Lifetime { kind: l_kind }, GenericParamKind::Lifetime { kind: r_kind }) => {
334 match (l_kind, r_kind) {
335 (LifetimeParamKind::Explicit, LifetimeParamKind::Explicit)
336 | (LifetimeParamKind::Error, LifetimeParamKind::Error) => true,
337 (LifetimeParamKind::Elided(l_lifetime_kind), LifetimeParamKind::Elided(r_lifetime_kind)) => {
338 l_lifetime_kind == r_lifetime_kind
339 },
340 _ => false,
341 }
342 },
343 (
344 GenericParamKind::Type {
345 default: l_default,
346 synthetic: l_synthetic,
347 },
348 GenericParamKind::Type {
349 default: r_default,
350 synthetic: r_synthetic,
351 },
352 ) => both(*l_default, *r_default, |l, r| self.eq_ty(l, r)) && l_synthetic == r_synthetic,
353 (
354 GenericParamKind::Const {
355 ty: l_ty,
356 default: l_default,
357 },
358 GenericParamKind::Const {
359 ty: r_ty,
360 default: r_default,
361 },
362 ) => self.eq_ty(l_ty, r_ty) && both(*l_default, *r_default, |l, r| self.eq_const_arg(l, r)),
363 _ => false,
364 }
365 }
366
367 fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
369 use TokenKind::{Semi, Whitespace};
370 if left.stmts.len() != right.stmts.len() {
371 return false;
372 }
373 let lspan = left.span.data();
374 let rspan = right.span.data();
375 if lspan.ctxt != SyntaxContext::root() && rspan.ctxt != SyntaxContext::root() {
376 return over(left.stmts, right.stmts, |left, right| self.eq_stmt(left, right))
378 && both(left.expr.as_ref(), right.expr.as_ref(), |left, right| {
379 self.eq_expr(left, right)
380 });
381 }
382 if lspan.ctxt != rspan.ctxt {
383 return false;
384 }
385
386 let mut lstart = lspan.lo;
387 let mut rstart = rspan.lo;
388
389 for (left, right) in left.stmts.iter().zip(right.stmts) {
390 if !self.eq_stmt(left, right) {
391 return false;
392 }
393
394 let Some(lstmt_span) = walk_span_to_context(left.span, lspan.ctxt) else {
396 return false;
397 };
398 let Some(rstmt_span) = walk_span_to_context(right.span, rspan.ctxt) else {
399 return false;
400 };
401 let lstmt_span = lstmt_span.data();
402 let rstmt_span = rstmt_span.data();
403
404 if lstmt_span.lo < lstart && rstmt_span.lo < rstart {
405 continue;
408 }
409 if lstmt_span.lo < lstart || rstmt_span.lo < rstart {
410 return false;
412 }
413 if !eq_span_tokens(self.inner.cx, lstart..lstmt_span.lo, rstart..rstmt_span.lo, |t| {
414 !matches!(t, Whitespace | Semi)
415 }) {
416 return false;
417 }
418
419 lstart = lstmt_span.hi;
420 rstart = rstmt_span.hi;
421 }
422
423 let (lend, rend) = match (left.expr, right.expr) {
424 (Some(left), Some(right)) => {
425 if !self.eq_expr(left, right) {
426 return false;
427 }
428 let Some(lexpr_span) = walk_span_to_context(left.span, lspan.ctxt) else {
429 return false;
430 };
431 let Some(rexpr_span) = walk_span_to_context(right.span, rspan.ctxt) else {
432 return false;
433 };
434 (lexpr_span.lo(), rexpr_span.lo())
435 },
436 (None, None) => (lspan.hi, rspan.hi),
437 (Some(_), None) | (None, Some(_)) => return false,
438 };
439
440 if lend < lstart && rend < rstart {
441 return true;
444 } else if lend < lstart || rend < rstart {
445 return false;
447 }
448 eq_span_tokens(self.inner.cx, lstart..lend, rstart..rend, |t| {
449 !matches!(t, Whitespace | Semi)
450 })
451 }
452
453 fn should_ignore(&self, expr: &Expr<'_>) -> bool {
454 macro_backtrace(expr.span).last().is_some_and(|macro_call| {
455 matches!(
456 self.inner.cx.tcx.get_diagnostic_name(macro_call.def_id),
457 Some(sym::todo_macro | sym::unimplemented_macro)
458 )
459 })
460 }
461
462 pub fn eq_body(&mut self, left: BodyId, right: BodyId) -> bool {
463 let old_maybe_typeck_results = self.inner.maybe_typeck_results.replace((
465 self.inner.cx.tcx.typeck_body(left),
466 self.inner.cx.tcx.typeck_body(right),
467 ));
468 let res = self.eq_expr(
469 self.inner.cx.tcx.hir_body(left).value,
470 self.inner.cx.tcx.hir_body(right).value,
471 );
472 self.inner.maybe_typeck_results = old_maybe_typeck_results;
473 res
474 }
475
476 #[expect(clippy::too_many_lines)]
477 pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
478 if !self.check_ctxt(left.span.ctxt(), right.span.ctxt()) {
479 return false;
480 }
481
482 if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results
483 && typeck_lhs.expr_ty(left) == typeck_rhs.expr_ty(right)
484 && let (Some(l), Some(r)) = (
485 ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_lhs)
486 .eval_local(left, self.left_ctxt),
487 ConstEvalCtxt::with_env(self.inner.cx.tcx, self.inner.cx.typing_env(), typeck_rhs)
488 .eval_local(right, self.right_ctxt),
489 )
490 && l == r
491 {
492 return true;
493 }
494
495 let is_eq = match (
496 reduce_exprkind(self.inner.cx, &left.kind),
497 reduce_exprkind(self.inner.cx, &right.kind),
498 ) {
499 (ExprKind::AddrOf(lb, l_mut, le), ExprKind::AddrOf(rb, r_mut, re)) => {
500 lb == rb && l_mut == r_mut && self.eq_expr(le, re)
501 },
502 (ExprKind::Array(l), ExprKind::Array(r)) => self.eq_exprs(l, r),
503 (ExprKind::Assign(ll, lr, _), ExprKind::Assign(rl, rr, _)) => {
504 self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
505 },
506 (ExprKind::AssignOp(lo, ll, lr), ExprKind::AssignOp(ro, rl, rr)) => {
507 self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
508 },
509 (ExprKind::Block(l, _), ExprKind::Block(r, _)) => self.eq_block(l, r),
510 (ExprKind::Binary(l_op, ll, lr), ExprKind::Binary(r_op, rl, rr)) => {
511 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
512 || self.swap_binop(l_op.node, ll, lr).is_some_and(|(l_op, ll, lr)| {
513 l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
514 })
515 },
516 (ExprKind::Break(li, le), ExprKind::Break(ri, re)) => {
517 both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
518 && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
519 },
520 (ExprKind::Call(l_fun, l_args), ExprKind::Call(r_fun, r_args)) => {
521 self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
522 },
523 (ExprKind::Cast(lx, lt), ExprKind::Cast(rx, rt)) => {
524 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
525 },
526 (ExprKind::Closure(_l), ExprKind::Closure(_r)) => false,
527 (ExprKind::ConstBlock(lb), ExprKind::ConstBlock(rb)) => self.eq_body(lb.body, rb.body),
528 (ExprKind::Continue(li), ExprKind::Continue(ri)) => {
529 both(li.label.as_ref(), ri.label.as_ref(), |l, r| l.ident.name == r.ident.name)
530 },
531 (ExprKind::DropTemps(le), ExprKind::DropTemps(re)) => self.eq_expr(le, re),
532 (ExprKind::Field(l_f_exp, l_f_ident), ExprKind::Field(r_f_exp, r_f_ident)) => {
533 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
534 },
535 (ExprKind::Index(la, li, _), ExprKind::Index(ra, ri, _)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
536 (ExprKind::If(lc, lt, le), ExprKind::If(rc, rt, re)) => {
537 self.eq_expr(lc, rc) && self.eq_expr(lt, rt)
538 && both(le.as_ref(), re.as_ref(), |l, r| self.eq_expr(l, r))
539 },
540 (ExprKind::Let(l), ExprKind::Let(r)) => {
541 self.eq_pat(l.pat, r.pat)
542 && both(l.ty.as_ref(), r.ty.as_ref(), |l, r| self.eq_ty(l, r))
543 && self.eq_expr(l.init, r.init)
544 },
545 (ExprKind::Lit(l), ExprKind::Lit(r)) => l.node == r.node,
546 (ExprKind::Loop(lb, ll, lls, _), ExprKind::Loop(rb, rl, rls, _)) => {
547 lls == rls && self.eq_block(lb, rb)
548 && both(ll.as_ref(), rl.as_ref(), |l, r| l.ident.name == r.ident.name)
549 },
550 (ExprKind::Match(le, la, ls), ExprKind::Match(re, ra, rs)) => {
551 (ls == rs || (matches!((ls, rs), (TryDesugar(_), TryDesugar(_)))))
552 && self.eq_expr(le, re)
553 && over(la, ra, |l, r| {
554 self.eq_pat(l.pat, r.pat)
555 && both(l.guard.as_ref(), r.guard.as_ref(), |l, r| self.eq_expr(l, r))
556 && self.eq_expr(l.body, r.body)
557 })
558 },
559 (
560 ExprKind::MethodCall(l_path, l_receiver, l_args, _),
561 ExprKind::MethodCall(r_path, r_receiver, r_args, _),
562 ) => {
563 self.inner.allow_side_effects
564 && self.eq_path_segment(l_path, r_path)
565 && self.eq_expr(l_receiver, r_receiver)
566 && self.eq_exprs(l_args, r_args)
567 },
568 (ExprKind::UnsafeBinderCast(lkind, le, None), ExprKind::UnsafeBinderCast(rkind, re, None)) =>
569 lkind == rkind && self.eq_expr(le, re),
570 (ExprKind::UnsafeBinderCast(lkind, le, Some(lt)), ExprKind::UnsafeBinderCast(rkind, re, Some(rt))) =>
571 lkind == rkind && self.eq_expr(le, re) && self.eq_ty(lt, rt),
572 (ExprKind::OffsetOf(l_container, l_fields), ExprKind::OffsetOf(r_container, r_fields)) => {
573 self.eq_ty(l_container, r_container) && over(l_fields, r_fields, |l, r| l.name == r.name)
574 },
575 (ExprKind::Path(l), ExprKind::Path(r)) => self.eq_qpath(l, r),
576 (ExprKind::Repeat(le, ll), ExprKind::Repeat(re, rl)) => {
577 self.eq_expr(le, re) && self.eq_const_arg(ll, rl)
578 },
579 (ExprKind::Ret(l), ExprKind::Ret(r)) => both(l.as_ref(), r.as_ref(), |l, r| self.eq_expr(l, r)),
580 (ExprKind::Struct(l_path, lf, lo), ExprKind::Struct(r_path, rf, ro)) => {
581 self.eq_qpath(l_path, r_path)
582 && match (lo, ro) {
583 (StructTailExpr::Base(l),StructTailExpr::Base(r)) => self.eq_expr(l, r),
584 (StructTailExpr::None, StructTailExpr::None) |
585 (StructTailExpr::DefaultFields(_), StructTailExpr::DefaultFields(_)) => true,
586 _ => false,
587 }
588 && over(lf, rf, |l, r| self.eq_expr_field(l, r))
589 },
590 (ExprKind::Tup(l_tup), ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
591 (ExprKind::Use(l_expr, _), ExprKind::Use(r_expr, _)) => self.eq_expr(l_expr, r_expr),
592 (ExprKind::Type(le, lt), ExprKind::Type(re, rt)) => self.eq_expr(le, re) && self.eq_ty(lt, rt),
593 (ExprKind::Unary(l_op, le), ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
594 (ExprKind::Yield(le, _), ExprKind::Yield(re, _)) => return self.eq_expr(le, re),
595 (
596 | ExprKind::AddrOf(..)
598 | ExprKind::Array(..)
599 | ExprKind::Assign(..)
600 | ExprKind::AssignOp(..)
601 | ExprKind::Binary(..)
602 | ExprKind::Become(..)
603 | ExprKind::Block(..)
604 | ExprKind::Break(..)
605 | ExprKind::Call(..)
606 | ExprKind::Cast(..)
607 | ExprKind::ConstBlock(..)
608 | ExprKind::Continue(..)
609 | ExprKind::DropTemps(..)
610 | ExprKind::Field(..)
611 | ExprKind::Index(..)
612 | ExprKind::If(..)
613 | ExprKind::Let(..)
614 | ExprKind::Lit(..)
615 | ExprKind::Loop(..)
616 | ExprKind::Match(..)
617 | ExprKind::MethodCall(..)
618 | ExprKind::OffsetOf(..)
619 | ExprKind::Path(..)
620 | ExprKind::Repeat(..)
621 | ExprKind::Ret(..)
622 | ExprKind::Struct(..)
623 | ExprKind::Tup(..)
624 | ExprKind::Use(..)
625 | ExprKind::Type(..)
626 | ExprKind::Unary(..)
627 | ExprKind::Yield(..)
628 | ExprKind::UnsafeBinderCast(..)
629
630 | ExprKind::Err(..)
635
636 | ExprKind::Closure(..)
639 | ExprKind::InlineAsm(_)
642 , _
643 ) => false,
644 };
645 (is_eq && (!self.should_ignore(left) || !self.should_ignore(right)))
646 || self
647 .inner
648 .maybe_typeck_results
649 .is_some_and(|(left_typeck_results, right_typeck_results)| {
650 self.inner
651 .expr_fallback
652 .as_mut()
653 .is_some_and(|f| f(left_typeck_results, left, right_typeck_results, right))
654 })
655 }
656
657 fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
658 over(left, right, |l, r| self.eq_expr(l, r))
659 }
660
661 fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
662 left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
663 }
664
665 fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
666 match (left, right) {
667 (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_const_arg(l.as_unambig_ct(), r.as_unambig_ct()),
668 (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
669 (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty.as_unambig_ty(), r_ty.as_unambig_ty()),
670 (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
671 _ => false,
672 }
673 }
674
675 fn eq_const_arg(&mut self, left: &ConstArg<'_>, right: &ConstArg<'_>) -> bool {
676 if !self.check_ctxt(left.span.ctxt(), right.span.ctxt()) {
677 return false;
678 }
679
680 match (&left.kind, &right.kind) {
681 (ConstArgKind::Tup(l_t), ConstArgKind::Tup(r_t)) => {
682 l_t.len() == r_t.len() && l_t.iter().zip(*r_t).all(|(l_c, r_c)| self.eq_const_arg(l_c, r_c))
683 },
684 (ConstArgKind::Path(l_p), ConstArgKind::Path(r_p)) => self.eq_qpath(l_p, r_p),
685 (ConstArgKind::Anon(l_an), ConstArgKind::Anon(r_an)) => self.eq_body(l_an.body, r_an.body),
686 (ConstArgKind::Infer(..), ConstArgKind::Infer(..)) => true,
687 (ConstArgKind::Struct(path_a, inits_a), ConstArgKind::Struct(path_b, inits_b)) => {
688 self.eq_qpath(path_a, path_b)
689 && inits_a
690 .iter()
691 .zip(*inits_b)
692 .all(|(init_a, init_b)| self.eq_const_arg(init_a.expr, init_b.expr))
693 },
694 (ConstArgKind::TupleCall(path_a, args_a), ConstArgKind::TupleCall(path_b, args_b)) => {
695 self.eq_qpath(path_a, path_b)
696 && args_a
697 .iter()
698 .zip(*args_b)
699 .all(|(arg_a, arg_b)| self.eq_const_arg(arg_a, arg_b))
700 },
701 (
702 ConstArgKind::Literal {
703 lit: kind_l,
704 negated: negated_l,
705 },
706 ConstArgKind::Literal {
707 lit: kind_r,
708 negated: negated_r,
709 },
710 ) => kind_l == kind_r && negated_l == negated_r,
711 (ConstArgKind::Array(l_arr), ConstArgKind::Array(r_arr)) => {
712 l_arr.elems.len() == r_arr.elems.len()
713 && l_arr
714 .elems
715 .iter()
716 .zip(r_arr.elems.iter())
717 .all(|(l_elem, r_elem)| self.eq_const_arg(l_elem, r_elem))
718 },
719 (
721 ConstArgKind::Path(..)
722 | ConstArgKind::Tup(..)
723 | ConstArgKind::Anon(..)
724 | ConstArgKind::TupleCall(..)
725 | ConstArgKind::Infer(..)
726 | ConstArgKind::Struct(..)
727 | ConstArgKind::Literal { .. }
728 | ConstArgKind::Array(..)
729 | ConstArgKind::Error(..),
730 _,
731 ) => false,
732 }
733 }
734
735 fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
736 left.kind == right.kind
737 }
738
739 fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
740 let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
741 li.name == ri.name && self.eq_pat(lp, rp)
742 }
743
744 fn eq_pat_expr(&mut self, left: &PatExpr<'_>, right: &PatExpr<'_>) -> bool {
745 match (&left.kind, &right.kind) {
746 (
747 PatExprKind::Lit {
748 lit: left,
749 negated: left_neg,
750 },
751 PatExprKind::Lit {
752 lit: right,
753 negated: right_neg,
754 },
755 ) => left_neg == right_neg && left.node == right.node,
756 (PatExprKind::Path(left), PatExprKind::Path(right)) => self.eq_qpath(left, right),
757 (PatExprKind::Lit { .. } | PatExprKind::Path(..), _) => false,
758 }
759 }
760
761 fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
763 match (&left.kind, &right.kind) {
764 (PatKind::Box(l), PatKind::Box(r)) => self.eq_pat(l, r),
765 (PatKind::Struct(lp, la, ..), PatKind::Struct(rp, ra, ..)) => {
766 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
767 },
768 (PatKind::TupleStruct(lp, la, ls), PatKind::TupleStruct(rp, ra, rs)) => {
769 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
770 },
771 (PatKind::Binding(lb, li, _, lp), PatKind::Binding(rb, ri, _, rp)) => {
772 let eq = lb == rb && both(lp.as_ref(), rp.as_ref(), |l, r| self.eq_pat(l, r));
773 if eq {
774 self.locals.insert(*li, *ri);
775 }
776 eq
777 },
778 (PatKind::Expr(l), PatKind::Expr(r)) => self.eq_pat_expr(l, r),
779 (PatKind::Tuple(l, ls), PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
780 (PatKind::Range(ls, le, li), PatKind::Range(rs, re, ri)) => {
781 both(ls.as_ref(), rs.as_ref(), |a, b| self.eq_pat_expr(a, b))
782 && both(le.as_ref(), re.as_ref(), |a, b| self.eq_pat_expr(a, b))
783 && (li == ri)
784 },
785 (PatKind::Ref(le, lp, lm), PatKind::Ref(re, rp, rm)) => lp == rp && lm == rm && self.eq_pat(le, re),
786 (PatKind::Slice(ls, li, le), PatKind::Slice(rs, ri, re)) => {
787 over(ls, rs, |l, r| self.eq_pat(l, r))
788 && over(le, re, |l, r| self.eq_pat(l, r))
789 && both(li.as_ref(), ri.as_ref(), |l, r| self.eq_pat(l, r))
790 },
791 (PatKind::Wild, PatKind::Wild) => true,
792 _ => false,
793 }
794 }
795
796 fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
797 match (left, right) {
798 (QPath::Resolved(lty, lpath), QPath::Resolved(rty, rpath)) => {
799 both(lty.as_ref(), rty.as_ref(), |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
800 },
801 (QPath::TypeRelative(lty, lseg), QPath::TypeRelative(rty, rseg)) => {
802 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
803 },
804 _ => false,
805 }
806 }
807
808 pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
809 match (left.res, right.res) {
810 (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
811 (Res::Local(_), _) | (_, Res::Local(_)) => false,
812 (Res::Def(l_kind, l), Res::Def(r_kind, r))
813 if l_kind == r_kind
814 && let DefKind::Const { .. }
815 | DefKind::Static { .. }
816 | DefKind::Fn
817 | DefKind::TyAlias
818 | DefKind::Use
819 | DefKind::Mod = l_kind =>
820 {
821 (l == r || self.local_items.get(&l) == Some(&r)) && self.eq_path_segments(left.segments, right.segments)
822 },
823 _ => self.eq_path_segments(left.segments, right.segments),
824 }
825 }
826
827 fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
828 if left.parenthesized == right.parenthesized {
829 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))
831 } else {
832 false
833 }
834 }
835
836 pub fn eq_path_segments<'tcx>(
837 &mut self,
838 mut left: &'tcx [PathSegment<'tcx>],
839 mut right: &'tcx [PathSegment<'tcx>],
840 ) -> bool {
841 if let PathCheck::Resolution = self.inner.path_check
842 && let Some(left_seg) = generic_path_segments(left)
843 && let Some(right_seg) = generic_path_segments(right)
844 {
845 left = left_seg;
848 right = right_seg;
849 }
850
851 over(left, right, |l, r| self.eq_path_segment(l, r))
852 }
853
854 pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
855 if !self.eq_path_parameters(left.args(), right.args()) {
856 return false;
857 }
858
859 if let PathCheck::Resolution = self.inner.path_check
860 && left.res != Res::Err
861 && right.res != Res::Err
862 {
863 left.res == right.res
864 } else {
865 left.ident.name == right.ident.name
868 }
869 }
870
871 pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
872 match (&left.kind, &right.kind) {
873 (TyKind::Slice(l_vec), TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
874 (TyKind::Array(lt, ll), TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_const_arg(ll, rl),
875 (TyKind::Ptr(l_mut), TyKind::Ptr(r_mut)) => l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty),
876 (TyKind::Ref(_, l_rmut), TyKind::Ref(_, r_rmut)) => {
877 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
878 },
879 (TyKind::Path(l), TyKind::Path(r)) => self.eq_qpath(l, r),
880 (TyKind::Tup(l), TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
881 (TyKind::Infer(()), TyKind::Infer(())) => true,
882 _ => false,
883 }
884 }
885
886 fn eq_assoc_eq_constraint(&mut self, left: &AssocItemConstraint<'_>, right: &AssocItemConstraint<'_>) -> bool {
889 left.ident.name == right.ident.name
891 && (both_some_and(left.ty(), right.ty(), |l, r| self.eq_ty(l, r))
892 || both_some_and(left.ct(), right.ct(), |l, r| self.eq_const_arg(l, r)))
893 }
894
895 fn check_ctxt(&mut self, left: SyntaxContext, right: SyntaxContext) -> bool {
896 if self.left_ctxt == left && self.right_ctxt == right {
897 return true;
898 } else if self.left_ctxt == left || self.right_ctxt == right {
899 return false;
901 } else if left != SyntaxContext::root() {
902 let mut left_data = left.outer_expn_data();
903 let mut right_data = right.outer_expn_data();
904 loop {
905 use TokenKind::{BlockComment, LineComment, Whitespace};
906 if left_data.macro_def_id != right_data.macro_def_id
907 || (matches!(
908 left_data.kind,
909 ExpnKind::Macro(MacroKind::Bang, name)
910 if name == sym::cfg || name == sym::option_env
911 ) && !eq_span_tokens(self.inner.cx, left_data.call_site, right_data.call_site, |t| {
912 !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. })
913 }))
914 {
915 return false;
917 }
918 let left_ctxt = left_data.call_site.ctxt();
919 let right_ctxt = right_data.call_site.ctxt();
920 if left_ctxt == SyntaxContext::root() && right_ctxt == SyntaxContext::root() {
921 break;
922 }
923 if left_ctxt == SyntaxContext::root() || right_ctxt == SyntaxContext::root() {
924 return false;
927 }
928 left_data = left_ctxt.outer_expn_data();
929 right_data = right_ctxt.outer_expn_data();
930 }
931 }
932 self.left_ctxt = left;
933 self.right_ctxt = right;
934 true
935 }
936
937 fn swap_binop<'a>(
938 &self,
939 binop: BinOpKind,
940 lhs: &'a Expr<'a>,
941 rhs: &'a Expr<'a>,
942 ) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
943 match binop {
944 BinOpKind::Eq | BinOpKind::Ne => Some((binop, rhs, lhs)),
946 BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
948 BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
949 BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
950 BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
951 BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Rem | BinOpKind::Sub | BinOpKind::Div => None,
953 BinOpKind::Mul
956 | BinOpKind::Add
957 | BinOpKind::And
958 | BinOpKind::Or
959 | BinOpKind::BitAnd
960 | BinOpKind::BitXor
961 | BinOpKind::BitOr => self.inner.maybe_typeck_results.and_then(|(typeck_lhs, _)| {
962 typeck_lhs
963 .expr_ty_adjusted(lhs)
964 .peel_refs()
965 .is_primitive()
966 .then_some((binop, rhs, lhs))
967 }),
968 }
969 }
970}
971
972fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
974 if let ExprKind::Block(block, _) = kind {
975 match (block.stmts, block.expr) {
976 ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
979 ([], None)
981 if block.span.check_source_text(cx, |src| {
982 tokenize(src, FrontmatterAllowed::No)
983 .map(|t| t.kind)
984 .filter(|t| {
985 !matches!(
986 t,
987 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
988 )
989 })
990 .eq([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied())
991 }) =>
992 {
993 &ExprKind::Tup(&[])
994 },
995 ([], Some(expr)) => match expr.kind {
996 ExprKind::Ret(..) => &expr.kind,
998 _ => kind,
999 },
1000 ([stmt], None) => match stmt.kind {
1001 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
1002 ExprKind::Ret(..) => &expr.kind,
1004 _ => kind,
1005 },
1006 _ => kind,
1007 },
1008 _ => kind,
1009 }
1010 } else {
1011 kind
1012 }
1013}
1014
1015pub fn both<X>(l: Option<&X>, r: Option<&X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
1018 l.as_ref()
1019 .map_or_else(|| r.is_none(), |x| r.as_ref().is_some_and(|y| eq_fn(x, y)))
1020}
1021
1022pub fn both_some_and<X, Y>(l: Option<X>, r: Option<Y>, mut pred: impl FnMut(X, Y) -> bool) -> bool {
1024 l.is_some_and(|l| r.is_some_and(|r| pred(l, r)))
1025}
1026
1027pub fn over<X, Y>(left: &[X], right: &[Y], mut eq_fn: impl FnMut(&X, &Y) -> bool) -> bool {
1029 left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
1030}
1031
1032pub fn count_eq<X: Sized>(
1034 left: &mut dyn Iterator<Item = X>,
1035 right: &mut dyn Iterator<Item = X>,
1036 mut eq_fn: impl FnMut(&X, &X) -> bool,
1037) -> usize {
1038 left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
1039}
1040
1041pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
1043 SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
1044}
1045
1046fn generic_path_segments<'tcx>(segments: &'tcx [PathSegment<'tcx>]) -> Option<&'tcx [PathSegment<'tcx>]> {
1050 match segments.last()?.res {
1051 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _) => {
1052 Some(&segments[segments.len().checked_sub(2)?..])
1055 },
1056 Res::Err => None,
1057 _ => Some(slice::from_ref(segments.last()?)),
1058 }
1059}
1060
1061pub struct SpanlessHash<'a, 'tcx> {
1067 cx: &'a LateContext<'tcx>,
1069 maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
1070 s: FxHasher,
1071 path_check: PathCheck,
1072}
1073
1074impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
1075 pub fn new(cx: &'a LateContext<'tcx>) -> Self {
1076 Self {
1077 cx,
1078 maybe_typeck_results: cx.maybe_typeck_results(),
1079 s: FxHasher::default(),
1080 path_check: PathCheck::default(),
1081 }
1082 }
1083
1084 #[must_use]
1087 pub fn paths_by_resolution(self) -> Self {
1088 Self {
1089 path_check: PathCheck::Resolution,
1090 ..self
1091 }
1092 }
1093
1094 pub fn finish(self) -> u64 {
1095 self.s.finish()
1096 }
1097
1098 pub fn hash_block(&mut self, b: &Block<'_>) {
1099 for s in b.stmts {
1100 self.hash_stmt(s);
1101 }
1102
1103 if let Some(e) = b.expr {
1104 self.hash_expr(e);
1105 }
1106
1107 std::mem::discriminant(&b.rules).hash(&mut self.s);
1108 }
1109
1110 #[expect(clippy::too_many_lines)]
1111 pub fn hash_expr(&mut self, e: &Expr<'_>) {
1112 let simple_const = self.maybe_typeck_results.and_then(|typeck_results| {
1113 ConstEvalCtxt::with_env(self.cx.tcx, self.cx.typing_env(), typeck_results).eval_local(e, e.span.ctxt())
1114 });
1115
1116 simple_const.hash(&mut self.s);
1119 if simple_const.is_some() {
1120 return;
1121 }
1122
1123 std::mem::discriminant(&e.kind).hash(&mut self.s);
1124
1125 match &e.kind {
1126 ExprKind::AddrOf(kind, m, e) => {
1127 std::mem::discriminant(kind).hash(&mut self.s);
1128 m.hash(&mut self.s);
1129 self.hash_expr(e);
1130 },
1131 ExprKind::Continue(i) => {
1132 if let Some(i) = i.label {
1133 self.hash_name(i.ident.name);
1134 }
1135 },
1136 ExprKind::Array(v) => {
1137 self.hash_exprs(v);
1138 },
1139 ExprKind::Assign(l, r, _) => {
1140 self.hash_expr(l);
1141 self.hash_expr(r);
1142 },
1143 ExprKind::AssignOp(o, l, r) => {
1144 std::mem::discriminant(&o.node).hash(&mut self.s);
1145 self.hash_expr(l);
1146 self.hash_expr(r);
1147 },
1148 ExprKind::Become(f) => {
1149 self.hash_expr(f);
1150 },
1151 ExprKind::Block(b, _) => {
1152 self.hash_block(b);
1153 },
1154 ExprKind::Binary(op, l, r) => {
1155 std::mem::discriminant(&op.node).hash(&mut self.s);
1156 self.hash_expr(l);
1157 self.hash_expr(r);
1158 },
1159 ExprKind::Break(i, j) => {
1160 if let Some(i) = i.label {
1161 self.hash_name(i.ident.name);
1162 }
1163 if let Some(j) = j {
1164 self.hash_expr(j);
1165 }
1166 },
1167 ExprKind::Call(fun, args) => {
1168 self.hash_expr(fun);
1169 self.hash_exprs(args);
1170 },
1171 ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
1172 self.hash_expr(e);
1173 self.hash_ty(ty);
1174 },
1175 ExprKind::Closure(Closure {
1176 capture_clause, body, ..
1177 }) => {
1178 std::mem::discriminant(capture_clause).hash(&mut self.s);
1179 self.hash_expr(self.cx.tcx.hir_body(*body).value);
1181 },
1182 ExprKind::ConstBlock(l_id) => {
1183 self.hash_body(l_id.body);
1184 },
1185 ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
1186 self.hash_expr(e);
1187 },
1188 ExprKind::Field(e, f) => {
1189 self.hash_expr(e);
1190 self.hash_name(f.name);
1191 },
1192 ExprKind::Index(a, i, _) => {
1193 self.hash_expr(a);
1194 self.hash_expr(i);
1195 },
1196 ExprKind::InlineAsm(asm) => {
1197 for piece in asm.template {
1198 match piece {
1199 InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
1200 InlineAsmTemplatePiece::Placeholder {
1201 operand_idx,
1202 modifier,
1203 span: _,
1204 } => {
1205 operand_idx.hash(&mut self.s);
1206 modifier.hash(&mut self.s);
1207 },
1208 }
1209 }
1210 asm.options.hash(&mut self.s);
1211 for (op, _op_sp) in asm.operands {
1212 match op {
1213 InlineAsmOperand::In { reg, expr } => {
1214 reg.hash(&mut self.s);
1215 self.hash_expr(expr);
1216 },
1217 InlineAsmOperand::Out { reg, late, expr } => {
1218 reg.hash(&mut self.s);
1219 late.hash(&mut self.s);
1220 if let Some(expr) = expr {
1221 self.hash_expr(expr);
1222 }
1223 },
1224 InlineAsmOperand::InOut { reg, late, expr } => {
1225 reg.hash(&mut self.s);
1226 late.hash(&mut self.s);
1227 self.hash_expr(expr);
1228 },
1229 InlineAsmOperand::SplitInOut {
1230 reg,
1231 late,
1232 in_expr,
1233 out_expr,
1234 } => {
1235 reg.hash(&mut self.s);
1236 late.hash(&mut self.s);
1237 self.hash_expr(in_expr);
1238 if let Some(out_expr) = out_expr {
1239 self.hash_expr(out_expr);
1240 }
1241 },
1242 InlineAsmOperand::SymFn { expr } => {
1243 self.hash_expr(expr);
1244 },
1245 InlineAsmOperand::Const { anon_const } => {
1246 self.hash_body(anon_const.body);
1247 },
1248 InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
1249 InlineAsmOperand::Label { block } => self.hash_block(block),
1250 }
1251 }
1252 },
1253 ExprKind::Let(LetExpr { pat, init, ty, .. }) => {
1254 self.hash_expr(init);
1255 if let Some(ty) = ty {
1256 self.hash_ty(ty);
1257 }
1258 self.hash_pat(pat);
1259 },
1260 ExprKind::Lit(l) => {
1261 l.node.hash(&mut self.s);
1262 },
1263 ExprKind::Loop(b, i, ..) => {
1264 self.hash_block(b);
1265 if let Some(i) = i {
1266 self.hash_name(i.ident.name);
1267 }
1268 },
1269 ExprKind::If(cond, then, else_opt) => {
1270 self.hash_expr(cond);
1271 self.hash_expr(then);
1272 if let Some(e) = else_opt {
1273 self.hash_expr(e);
1274 }
1275 },
1276 ExprKind::Match(scrutinee, arms, _) => {
1277 self.hash_expr(scrutinee);
1278
1279 for arm in *arms {
1280 self.hash_pat(arm.pat);
1281 if let Some(e) = arm.guard {
1282 self.hash_expr(e);
1283 }
1284 self.hash_expr(arm.body);
1285 }
1286 },
1287 ExprKind::MethodCall(path, receiver, args, _fn_span) => {
1288 self.hash_name(path.ident.name);
1289 self.hash_expr(receiver);
1290 self.hash_exprs(args);
1291 },
1292 ExprKind::OffsetOf(container, fields) => {
1293 self.hash_ty(container);
1294 for field in *fields {
1295 self.hash_name(field.name);
1296 }
1297 },
1298 ExprKind::Path(qpath) => {
1299 self.hash_qpath(qpath);
1300 },
1301 ExprKind::Repeat(e, len) => {
1302 self.hash_expr(e);
1303 self.hash_const_arg(len);
1304 },
1305 ExprKind::Ret(e) => {
1306 if let Some(e) = e {
1307 self.hash_expr(e);
1308 }
1309 },
1310 ExprKind::Struct(path, fields, expr) => {
1311 self.hash_qpath(path);
1312
1313 for f in *fields {
1314 self.hash_name(f.ident.name);
1315 self.hash_expr(f.expr);
1316 }
1317
1318 if let StructTailExpr::Base(e) = expr {
1319 self.hash_expr(e);
1320 }
1321 },
1322 ExprKind::Tup(tup) => {
1323 self.hash_exprs(tup);
1324 },
1325 ExprKind::Use(expr, _) => {
1326 self.hash_expr(expr);
1327 },
1328 ExprKind::Unary(l_op, le) => {
1329 std::mem::discriminant(l_op).hash(&mut self.s);
1330 self.hash_expr(le);
1331 },
1332 ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1333 std::mem::discriminant(kind).hash(&mut self.s);
1334 self.hash_expr(expr);
1335 if let Some(ty) = ty {
1336 self.hash_ty(ty);
1337 }
1338 },
1339 ExprKind::Err(_) => {},
1340 }
1341 }
1342
1343 pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
1344 for e in e {
1345 self.hash_expr(e);
1346 }
1347 }
1348
1349 pub fn hash_name(&mut self, n: Symbol) {
1350 n.hash(&mut self.s);
1351 }
1352
1353 pub fn hash_qpath(&mut self, p: &QPath<'_>) {
1354 match p {
1355 QPath::Resolved(_, path) => {
1356 self.hash_path(path);
1357 },
1358 QPath::TypeRelative(_, path) => {
1359 self.hash_name(path.ident.name);
1360 },
1361 }
1362 }
1364
1365 pub fn hash_pat_expr(&mut self, lit: &PatExpr<'_>) {
1366 std::mem::discriminant(&lit.kind).hash(&mut self.s);
1367 match &lit.kind {
1368 PatExprKind::Lit { lit, negated } => {
1369 lit.node.hash(&mut self.s);
1370 negated.hash(&mut self.s);
1371 },
1372 PatExprKind::Path(qpath) => self.hash_qpath(qpath),
1373 }
1374 }
1375
1376 pub fn hash_ty_pat(&mut self, pat: &TyPat<'_>) {
1377 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1378 match pat.kind {
1379 TyPatKind::Range(s, e) => {
1380 self.hash_const_arg(s);
1381 self.hash_const_arg(e);
1382 },
1383 TyPatKind::Or(variants) => {
1384 for variant in variants {
1385 self.hash_ty_pat(variant);
1386 }
1387 },
1388 TyPatKind::NotNull | TyPatKind::Err(_) => {},
1389 }
1390 }
1391
1392 pub fn hash_pat(&mut self, pat: &Pat<'_>) {
1393 std::mem::discriminant(&pat.kind).hash(&mut self.s);
1394 match &pat.kind {
1395 PatKind::Missing => unreachable!(),
1396 PatKind::Binding(BindingMode(by_ref, mutability), _, _, pat) => {
1397 std::mem::discriminant(by_ref).hash(&mut self.s);
1398 if let ByRef::Yes(pi, mu) = by_ref {
1399 std::mem::discriminant(pi).hash(&mut self.s);
1400 std::mem::discriminant(mu).hash(&mut self.s);
1401 }
1402 std::mem::discriminant(mutability).hash(&mut self.s);
1403 if let Some(pat) = pat {
1404 self.hash_pat(pat);
1405 }
1406 },
1407 PatKind::Box(pat) | PatKind::Deref(pat) => self.hash_pat(pat),
1408 PatKind::Expr(expr) => self.hash_pat_expr(expr),
1409 PatKind::Or(pats) => {
1410 for pat in *pats {
1411 self.hash_pat(pat);
1412 }
1413 },
1414 PatKind::Range(s, e, i) => {
1415 if let Some(s) = s {
1416 self.hash_pat_expr(s);
1417 }
1418 if let Some(e) = e {
1419 self.hash_pat_expr(e);
1420 }
1421 std::mem::discriminant(i).hash(&mut self.s);
1422 },
1423 PatKind::Ref(pat, pi, mu) => {
1424 self.hash_pat(pat);
1425 std::mem::discriminant(pi).hash(&mut self.s);
1426 std::mem::discriminant(mu).hash(&mut self.s);
1427 },
1428 PatKind::Guard(pat, guard) => {
1429 self.hash_pat(pat);
1430 self.hash_expr(guard);
1431 },
1432 PatKind::Slice(l, m, r) => {
1433 for pat in *l {
1434 self.hash_pat(pat);
1435 }
1436 if let Some(pat) = m {
1437 self.hash_pat(pat);
1438 }
1439 for pat in *r {
1440 self.hash_pat(pat);
1441 }
1442 },
1443 PatKind::Struct(qpath, fields, e) => {
1444 self.hash_qpath(qpath);
1445 for f in *fields {
1446 self.hash_name(f.ident.name);
1447 self.hash_pat(f.pat);
1448 }
1449 e.hash(&mut self.s);
1450 },
1451 PatKind::Tuple(pats, e) => {
1452 for pat in *pats {
1453 self.hash_pat(pat);
1454 }
1455 e.hash(&mut self.s);
1456 },
1457 PatKind::TupleStruct(qpath, pats, e) => {
1458 self.hash_qpath(qpath);
1459 for pat in *pats {
1460 self.hash_pat(pat);
1461 }
1462 e.hash(&mut self.s);
1463 },
1464 PatKind::Never | PatKind::Wild | PatKind::Err(_) => {},
1465 }
1466 }
1467
1468 pub fn hash_path(&mut self, path: &Path<'_>) {
1469 match path.res {
1470 Res::Local(_) => 1_usize.hash(&mut self.s),
1474 _ => {
1475 if let PathCheck::Resolution = self.path_check
1476 && let [.., last] = path.segments
1477 && let Some(segments) = generic_path_segments(path.segments)
1478 {
1479 for seg in segments {
1480 self.hash_generic_args(seg.args().args);
1481 }
1482 last.res.hash(&mut self.s);
1483 } else {
1484 for seg in path.segments {
1485 self.hash_name(seg.ident.name);
1486 self.hash_generic_args(seg.args().args);
1487 }
1488 }
1489 },
1490 }
1491 }
1492
1493 pub fn hash_modifiers(&mut self, modifiers: TraitBoundModifiers) {
1494 let TraitBoundModifiers { constness, polarity } = modifiers;
1495 std::mem::discriminant(&polarity).hash(&mut self.s);
1496 std::mem::discriminant(&constness).hash(&mut self.s);
1497 }
1498
1499 pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
1500 std::mem::discriminant(&b.kind).hash(&mut self.s);
1501
1502 match &b.kind {
1503 StmtKind::Let(local) => {
1504 self.hash_pat(local.pat);
1505 if let Some(init) = local.init {
1506 self.hash_expr(init);
1507 }
1508 if let Some(els) = local.els {
1509 self.hash_block(els);
1510 }
1511 },
1512 StmtKind::Item(..) => {},
1513 StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
1514 self.hash_expr(expr);
1515 },
1516 }
1517 }
1518
1519 pub fn hash_lifetime(&mut self, lifetime: &Lifetime) {
1520 lifetime.ident.name.hash(&mut self.s);
1521 std::mem::discriminant(&lifetime.kind).hash(&mut self.s);
1522 if let LifetimeKind::Param(param_id) = lifetime.kind {
1523 param_id.hash(&mut self.s);
1524 }
1525 }
1526
1527 pub fn hash_ty(&mut self, ty: &Ty<'_>) {
1528 std::mem::discriminant(&ty.kind).hash(&mut self.s);
1529 self.hash_tykind(&ty.kind);
1530 }
1531
1532 pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
1533 match ty {
1534 TyKind::Slice(ty) => {
1535 self.hash_ty(ty);
1536 },
1537 TyKind::Array(ty, len) => {
1538 self.hash_ty(ty);
1539 self.hash_const_arg(len);
1540 },
1541 TyKind::Pat(ty, pat) => {
1542 self.hash_ty(ty);
1543 self.hash_ty_pat(pat);
1544 },
1545 TyKind::FieldOf(base, TyFieldPath { variant, field }) => {
1546 self.hash_ty(base);
1547 if let Some(variant) = variant {
1548 self.hash_name(variant.name);
1549 }
1550 self.hash_name(field.name);
1551 },
1552 TyKind::Ptr(mut_ty) => {
1553 self.hash_ty(mut_ty.ty);
1554 mut_ty.mutbl.hash(&mut self.s);
1555 },
1556 TyKind::Ref(lifetime, mut_ty) => {
1557 self.hash_lifetime(lifetime);
1558 self.hash_ty(mut_ty.ty);
1559 mut_ty.mutbl.hash(&mut self.s);
1560 },
1561 TyKind::FnPtr(fn_ptr) => {
1562 fn_ptr.safety.hash(&mut self.s);
1563 fn_ptr.abi.hash(&mut self.s);
1564 for arg in fn_ptr.decl.inputs {
1565 self.hash_ty(arg);
1566 }
1567 std::mem::discriminant(&fn_ptr.decl.output).hash(&mut self.s);
1568 match fn_ptr.decl.output {
1569 FnRetTy::DefaultReturn(_) => {},
1570 FnRetTy::Return(ty) => {
1571 self.hash_ty(ty);
1572 },
1573 }
1574 fn_ptr.decl.c_variadic.hash(&mut self.s);
1575 },
1576 TyKind::Tup(ty_list) => {
1577 for ty in *ty_list {
1578 self.hash_ty(ty);
1579 }
1580 },
1581 TyKind::Path(qpath) => self.hash_qpath(qpath),
1582 TyKind::TraitObject(_, lifetime) => {
1583 self.hash_lifetime(lifetime);
1584 },
1585 TyKind::UnsafeBinder(binder) => {
1586 self.hash_ty(binder.inner_ty);
1587 },
1588 TyKind::Err(_)
1589 | TyKind::Infer(())
1590 | TyKind::Never
1591 | TyKind::InferDelegation(..)
1592 | TyKind::OpaqueDef(_)
1593 | TyKind::TraitAscription(_) => {},
1594 }
1595 }
1596
1597 pub fn hash_body(&mut self, body_id: BodyId) {
1598 let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1600 self.hash_expr(self.cx.tcx.hir_body(body_id).value);
1601 self.maybe_typeck_results = old_maybe_typeck_results;
1602 }
1603
1604 fn hash_const_arg(&mut self, const_arg: &ConstArg<'_>) {
1605 match &const_arg.kind {
1606 ConstArgKind::Tup(tup) => {
1607 for arg in *tup {
1608 self.hash_const_arg(arg);
1609 }
1610 },
1611 ConstArgKind::Path(path) => self.hash_qpath(path),
1612 ConstArgKind::Anon(anon) => self.hash_body(anon.body),
1613 ConstArgKind::Struct(path, inits) => {
1614 self.hash_qpath(path);
1615 for init in *inits {
1616 self.hash_const_arg(init.expr);
1617 }
1618 },
1619 ConstArgKind::TupleCall(path, args) => {
1620 self.hash_qpath(path);
1621 for arg in *args {
1622 self.hash_const_arg(arg);
1623 }
1624 },
1625 ConstArgKind::Array(array_expr) => {
1626 for elem in array_expr.elems {
1627 self.hash_const_arg(elem);
1628 }
1629 },
1630 ConstArgKind::Infer(..) | ConstArgKind::Error(..) => {},
1631 ConstArgKind::Literal { lit, negated } => {
1632 lit.hash(&mut self.s);
1633 negated.hash(&mut self.s);
1634 },
1635 }
1636 }
1637
1638 fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1639 for arg in arg_list {
1640 match arg {
1641 GenericArg::Lifetime(l) => self.hash_lifetime(l),
1642 GenericArg::Type(ty) => self.hash_ty(ty.as_unambig_ty()),
1643 GenericArg::Const(ca) => self.hash_const_arg(ca.as_unambig_ct()),
1644 GenericArg::Infer(inf) => self.hash_ty(&inf.to_ty()),
1645 }
1646 }
1647 }
1648}
1649
1650pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1651 let mut h = SpanlessHash::new(cx);
1652 h.hash_stmt(s);
1653 h.finish()
1654}
1655
1656pub fn is_bool(ty: &Ty<'_>) -> bool {
1657 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
1658 matches!(path.res, Res::PrimTy(PrimTy::Bool))
1659 } else {
1660 false
1661 }
1662}
1663
1664pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1665 let mut h = SpanlessHash::new(cx);
1666 h.hash_expr(e);
1667 h.finish()
1668}
1669
1670fn eq_span_tokens(
1671 cx: &LateContext<'_>,
1672 left: impl SpanRange,
1673 right: impl SpanRange,
1674 pred: impl Fn(TokenKind) -> bool,
1675) -> bool {
1676 fn f(cx: &LateContext<'_>, left: Range<BytePos>, right: Range<BytePos>, pred: impl Fn(TokenKind) -> bool) -> bool {
1677 if let Some(lsrc) = left.get_source_range(cx)
1678 && let Some(lsrc) = lsrc.as_str()
1679 && let Some(rsrc) = right.get_source_range(cx)
1680 && let Some(rsrc) = rsrc.as_str()
1681 {
1682 let pred = |&(token, ..): &(TokenKind, _, _)| pred(token);
1683 let map = |(_, source, _)| source;
1684
1685 let ltok = tokenize_with_text(lsrc).filter(pred).map(map);
1686 let rtok = tokenize_with_text(rsrc).filter(pred).map(map);
1687 ltok.eq(rtok)
1688 } else {
1689 false
1691 }
1692 }
1693 f(cx, left.into_range(), right.into_range(), pred)
1694}
1695
1696pub fn has_ambiguous_literal_in_expr(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1699 match expr.kind {
1700 ExprKind::Path(ref qpath) => {
1701 if let Res::Local(hir_id) = cx.qpath_res(qpath, expr.hir_id)
1702 && let Node::LetStmt(local) = cx.tcx.parent_hir_node(hir_id)
1703 && local.ty.is_none()
1704 && let Some(init) = local.init
1705 {
1706 return has_ambiguous_literal_in_expr(cx, init);
1707 }
1708 false
1709 },
1710 ExprKind::Lit(lit) => matches!(
1711 lit.node,
1712 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) | ast::LitKind::Int(_, ast::LitIntType::Unsuffixed)
1713 ),
1714
1715 ExprKind::Array(exprs) | ExprKind::Tup(exprs) => exprs.iter().any(|e| has_ambiguous_literal_in_expr(cx, e)),
1716
1717 ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) | ExprKind::Binary(_, lhs, rhs) => {
1718 has_ambiguous_literal_in_expr(cx, lhs) || has_ambiguous_literal_in_expr(cx, rhs)
1719 },
1720
1721 ExprKind::Unary(_, e)
1722 | ExprKind::Cast(e, _)
1723 | ExprKind::Type(e, _)
1724 | ExprKind::DropTemps(e)
1725 | ExprKind::AddrOf(_, _, e)
1726 | ExprKind::Field(e, _)
1727 | ExprKind::Index(e, _, _)
1728 | ExprKind::Yield(e, _) => has_ambiguous_literal_in_expr(cx, e),
1729
1730 ExprKind::MethodCall(_, receiver, args, _) | ExprKind::Call(receiver, args) => {
1731 has_ambiguous_literal_in_expr(cx, receiver) || args.iter().any(|e| has_ambiguous_literal_in_expr(cx, e))
1732 },
1733
1734 ExprKind::Closure(Closure { body, .. }) => {
1735 let body = cx.tcx.hir_body(*body);
1736 let closure_expr = crate::peel_blocks(body.value);
1737 has_ambiguous_literal_in_expr(cx, closure_expr)
1738 },
1739
1740 ExprKind::Block(blk, _) => blk.expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1741
1742 ExprKind::If(cond, then_expr, else_expr) => {
1743 has_ambiguous_literal_in_expr(cx, cond)
1744 || has_ambiguous_literal_in_expr(cx, then_expr)
1745 || else_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1746 },
1747
1748 ExprKind::Match(scrutinee, arms, _) => {
1749 has_ambiguous_literal_in_expr(cx, scrutinee)
1750 || arms.iter().any(|arm| has_ambiguous_literal_in_expr(cx, arm.body))
1751 },
1752
1753 ExprKind::Loop(body, ..) => body.expr.is_some_and(|e| has_ambiguous_literal_in_expr(cx, e)),
1754
1755 ExprKind::Ret(opt_expr) | ExprKind::Break(_, opt_expr) => {
1756 opt_expr.as_ref().is_some_and(|e| has_ambiguous_literal_in_expr(cx, e))
1757 },
1758
1759 _ => false,
1760 }
1761}