]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/hir_utils.rs
Rollup merge of #99342 - TaKO8Ki:avoid-symbol-to-string-conversions, r=compiler-errors
[rust.git] / clippy_utils / src / hir_utils.rs
1 use crate::consts::constant_simple;
2 use crate::macros::macro_backtrace;
3 use crate::source::snippet_opt;
4 use rustc_ast::ast::InlineAsmTemplatePiece;
5 use rustc_data_structures::fx::FxHasher;
6 use rustc_hir::def::Res;
7 use rustc_hir::HirIdMap;
8 use rustc_hir::{
9     ArrayLen, BinOpKind, Closure, Block, BodyId, Expr, ExprField, ExprKind, FnRetTy, GenericArg, GenericArgs, Guard, HirId,
10     InlineAsmOperand, Let, Lifetime, LifetimeName, ParamName, Pat, PatField, PatKind, Path, PathSegment, QPath, Stmt,
11     StmtKind, Ty, TyKind, TypeBinding,
12 };
13 use rustc_lexer::{tokenize, TokenKind};
14 use rustc_lint::LateContext;
15 use rustc_middle::ty::TypeckResults;
16 use rustc_span::{sym, Symbol};
17 use std::hash::{Hash, Hasher};
18
19 /// Callback that is called when two expressions are not equal in the sense of `SpanlessEq`, but
20 /// other conditions would make them equal.
21 type SpanlessEqCallback<'a> = dyn FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a;
22
23 /// Type used to check whether two ast are the same. This is different from the
24 /// operator `==` on ast types as this operator would compare true equality with
25 /// ID and span.
26 ///
27 /// Note that some expressions kinds are not considered but could be added.
28 pub struct SpanlessEq<'a, 'tcx> {
29     /// Context used to evaluate constant expressions.
30     cx: &'a LateContext<'tcx>,
31     maybe_typeck_results: Option<(&'tcx TypeckResults<'tcx>, &'tcx TypeckResults<'tcx>)>,
32     allow_side_effects: bool,
33     expr_fallback: Option<Box<SpanlessEqCallback<'a>>>,
34 }
35
36 impl<'a, 'tcx> SpanlessEq<'a, 'tcx> {
37     pub fn new(cx: &'a LateContext<'tcx>) -> Self {
38         Self {
39             cx,
40             maybe_typeck_results: cx.maybe_typeck_results().map(|x| (x, x)),
41             allow_side_effects: true,
42             expr_fallback: None,
43         }
44     }
45
46     /// Consider expressions containing potential side effects as not equal.
47     #[must_use]
48     pub fn deny_side_effects(self) -> Self {
49         Self {
50             allow_side_effects: false,
51             ..self
52         }
53     }
54
55     #[must_use]
56     pub fn expr_fallback(self, expr_fallback: impl FnMut(&Expr<'_>, &Expr<'_>) -> bool + 'a) -> Self {
57         Self {
58             expr_fallback: Some(Box::new(expr_fallback)),
59             ..self
60         }
61     }
62
63     /// Use this method to wrap comparisons that may involve inter-expression context.
64     /// See `self.locals`.
65     pub fn inter_expr(&mut self) -> HirEqInterExpr<'_, 'a, 'tcx> {
66         HirEqInterExpr {
67             inner: self,
68             locals: HirIdMap::default(),
69         }
70     }
71
72     pub fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
73         self.inter_expr().eq_block(left, right)
74     }
75
76     pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
77         self.inter_expr().eq_expr(left, right)
78     }
79
80     pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
81         self.inter_expr().eq_path(left, right)
82     }
83
84     pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
85         self.inter_expr().eq_path_segment(left, right)
86     }
87
88     pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
89         self.inter_expr().eq_path_segments(left, right)
90     }
91 }
92
93 pub struct HirEqInterExpr<'a, 'b, 'tcx> {
94     inner: &'a mut SpanlessEq<'b, 'tcx>,
95
96     // When binding are declared, the binding ID in the left expression is mapped to the one on the
97     // right. For example, when comparing `{ let x = 1; x + 2 }` and `{ let y = 1; y + 2 }`,
98     // these blocks are considered equal since `x` is mapped to `y`.
99     pub locals: HirIdMap<HirId>,
100 }
101
102 impl HirEqInterExpr<'_, '_, '_> {
103     pub fn eq_stmt(&mut self, left: &Stmt<'_>, right: &Stmt<'_>) -> bool {
104         match (&left.kind, &right.kind) {
105             (&StmtKind::Local(l, ), &StmtKind::Local(r, )) => {
106                 // This additional check ensures that the type of the locals are equivalent even if the init
107                 // expression or type have some inferred parts.
108                 if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
109                     let l_ty = typeck_lhs.pat_ty(l.pat);
110                     let r_ty = typeck_rhs.pat_ty(r.pat);
111                     if l_ty != r_ty {
112                         return false;
113                     }
114                 }
115
116                 // eq_pat adds the HirIds to the locals map. We therefor call it last to make sure that
117                 // these only get added if the init and type is equal.
118                 both(&l.init, &r.init, |l, r| self.eq_expr(l, r))
119                     && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r))
120                     && both(&l.els, &r.els, |l, r| self.eq_block(l, r))
121                     && self.eq_pat(l.pat, r.pat)
122             },
123             (&StmtKind::Expr(l), &StmtKind::Expr(r)) | (&StmtKind::Semi(l), &StmtKind::Semi(r)) => self.eq_expr(l, r),
124             _ => false,
125         }
126     }
127
128     /// Checks whether two blocks are the same.
129     fn eq_block(&mut self, left: &Block<'_>, right: &Block<'_>) -> bool {
130         if self.cannot_be_compared_block(left) || self.cannot_be_compared_block(right) {
131             return false;
132         }
133         match (left.stmts, left.expr, right.stmts, right.expr) {
134             ([], None, [], None) => {
135                 // For empty blocks, check to see if the tokens are equal. This will catch the case where a macro
136                 // expanded to nothing, or the cfg attribute was used.
137                 let (left, right) = match (
138                     snippet_opt(self.inner.cx, left.span),
139                     snippet_opt(self.inner.cx, right.span),
140                 ) {
141                     (Some(left), Some(right)) => (left, right),
142                     _ => return true,
143                 };
144                 let mut left_pos = 0;
145                 let left = tokenize(&left)
146                     .map(|t| {
147                         let end = left_pos + t.len;
148                         let s = &left[left_pos..end];
149                         left_pos = end;
150                         (t, s)
151                     })
152                     .filter(|(t, _)| {
153                         !matches!(
154                             t.kind,
155                             TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
156                         )
157                     })
158                     .map(|(_, s)| s);
159                 let mut right_pos = 0;
160                 let right = tokenize(&right)
161                     .map(|t| {
162                         let end = right_pos + t.len;
163                         let s = &right[right_pos..end];
164                         right_pos = end;
165                         (t, s)
166                     })
167                     .filter(|(t, _)| {
168                         !matches!(
169                             t.kind,
170                             TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
171                         )
172                     })
173                     .map(|(_, s)| s);
174                 left.eq(right)
175             },
176             _ => {
177                 over(left.stmts, right.stmts, |l, r| self.eq_stmt(l, r))
178                     && both(&left.expr, &right.expr, |l, r| self.eq_expr(l, r))
179             },
180         }
181     }
182
183     fn cannot_be_compared_block(&mut self, block: &Block<'_>) -> bool {
184         if block.stmts.last().map_or(false, |stmt| {
185             matches!(
186                 stmt.kind,
187                 StmtKind::Semi(semi_expr) if self.should_ignore(semi_expr)
188             )
189         }) {
190             return true;
191         }
192
193         if let Some(block_expr) = block.expr
194             && self.should_ignore(block_expr)
195         {
196             return true
197         }
198
199         false
200     }
201
202     fn should_ignore(&mut self, expr: &Expr<'_>) -> bool {
203         if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
204             matches!(
205                 &self.inner.cx.tcx.get_diagnostic_name(macro_call.def_id),
206                 Some(sym::todo_macro | sym::unimplemented_macro)
207             )
208         }) {
209             return true;
210         }
211
212         false
213     }
214
215     pub fn eq_array_length(&mut self, left: ArrayLen, right: ArrayLen) -> bool {
216         match (left, right) {
217             (ArrayLen::Infer(..), ArrayLen::Infer(..)) => true,
218             (ArrayLen::Body(l_ct), ArrayLen::Body(r_ct)) => self.eq_body(l_ct.body, r_ct.body),
219             (_, _) => false,
220         }
221     }
222
223     pub fn eq_body(&mut self, left: BodyId, right: BodyId) -> bool {
224         // swap out TypeckResults when hashing a body
225         let old_maybe_typeck_results = self.inner.maybe_typeck_results.replace((
226             self.inner.cx.tcx.typeck_body(left),
227             self.inner.cx.tcx.typeck_body(right),
228         ));
229         let res = self.eq_expr(
230             &self.inner.cx.tcx.hir().body(left).value,
231             &self.inner.cx.tcx.hir().body(right).value,
232         );
233         self.inner.maybe_typeck_results = old_maybe_typeck_results;
234         res
235     }
236
237     #[expect(clippy::similar_names)]
238     pub fn eq_expr(&mut self, left: &Expr<'_>, right: &Expr<'_>) -> bool {
239         if !self.inner.allow_side_effects && left.span.ctxt() != right.span.ctxt() {
240             return false;
241         }
242
243         if let Some((typeck_lhs, typeck_rhs)) = self.inner.maybe_typeck_results {
244             if let (Some(l), Some(r)) = (
245                 constant_simple(self.inner.cx, typeck_lhs, left),
246                 constant_simple(self.inner.cx, typeck_rhs, right),
247             ) {
248                 if l == r {
249                     return true;
250                 }
251             }
252         }
253
254         let is_eq = match (
255             reduce_exprkind(self.inner.cx, &left.kind),
256             reduce_exprkind(self.inner.cx, &right.kind),
257         ) {
258             (&ExprKind::AddrOf(lb, l_mut, le), &ExprKind::AddrOf(rb, r_mut, re)) => {
259                 lb == rb && l_mut == r_mut && self.eq_expr(le, re)
260             },
261             (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => {
262                 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
263             },
264             (&ExprKind::Assign(ll, lr, _), &ExprKind::Assign(rl, rr, _)) => {
265                 self.inner.allow_side_effects && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
266             },
267             (&ExprKind::AssignOp(ref lo, ll, lr), &ExprKind::AssignOp(ref ro, rl, rr)) => {
268                 self.inner.allow_side_effects && lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
269             },
270             (&ExprKind::Block(l, _), &ExprKind::Block(r, _)) => self.eq_block(l, r),
271             (&ExprKind::Binary(l_op, ll, lr), &ExprKind::Binary(r_op, rl, rr)) => {
272                 l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
273                     || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
274                         l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
275                     })
276             },
277             (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => {
278                 both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name)
279                     && both(le, re, |l, r| self.eq_expr(l, r))
280             },
281             (&ExprKind::Box(l), &ExprKind::Box(r)) => self.eq_expr(l, r),
282             (&ExprKind::Call(l_fun, l_args), &ExprKind::Call(r_fun, r_args)) => {
283                 self.inner.allow_side_effects && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args)
284             },
285             (&ExprKind::Cast(lx, lt), &ExprKind::Cast(rx, rt)) | (&ExprKind::Type(lx, lt), &ExprKind::Type(rx, rt)) => {
286                 self.eq_expr(lx, rx) && self.eq_ty(lt, rt)
287             },
288             (&ExprKind::Field(l_f_exp, ref l_f_ident), &ExprKind::Field(r_f_exp, ref r_f_ident)) => {
289                 l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp)
290             },
291             (&ExprKind::Index(la, li), &ExprKind::Index(ra, ri)) => self.eq_expr(la, ra) && self.eq_expr(li, ri),
292             (&ExprKind::If(lc, lt, ref le), &ExprKind::If(rc, rt, ref re)) => {
293                 self.eq_expr(lc, rc) && self.eq_expr(lt, rt) && both(le, re, |l, r| self.eq_expr(l, r))
294             },
295             (&ExprKind::Let(l), &ExprKind::Let(r)) => {
296                 self.eq_pat(l.pat, r.pat) && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r)) && self.eq_expr(l.init, r.init)
297             },
298             (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node,
299             (&ExprKind::Loop(lb, ref ll, ref lls, _), &ExprKind::Loop(rb, ref rl, ref rls, _)) => {
300                 lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.name == r.ident.name)
301             },
302             (&ExprKind::Match(le, la, ref ls), &ExprKind::Match(re, ra, ref rs)) => {
303                 ls == rs
304                     && self.eq_expr(le, re)
305                     && over(la, ra, |l, r| {
306                         self.eq_pat(l.pat, r.pat)
307                             && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r))
308                             && self.eq_expr(l.body, r.body)
309                     })
310             },
311             (&ExprKind::MethodCall(l_path, l_args, _), &ExprKind::MethodCall(r_path, r_args, _)) => {
312                 self.inner.allow_side_effects && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args)
313             },
314             (&ExprKind::Repeat(le, ll), &ExprKind::Repeat(re, rl)) => {
315                 self.eq_expr(le, re) && self.eq_array_length(ll, rl)
316             },
317             (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)),
318             (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r),
319             (&ExprKind::Struct(l_path, lf, ref lo), &ExprKind::Struct(r_path, rf, ref ro)) => {
320                 self.eq_qpath(l_path, r_path)
321                     && both(lo, ro, |l, r| self.eq_expr(l, r))
322                     && over(lf, rf, |l, r| self.eq_expr_field(l, r))
323             },
324             (&ExprKind::Tup(l_tup), &ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup),
325             (&ExprKind::Unary(l_op, le), &ExprKind::Unary(r_op, re)) => l_op == r_op && self.eq_expr(le, re),
326             (&ExprKind::Array(l), &ExprKind::Array(r)) => self.eq_exprs(l, r),
327             (&ExprKind::DropTemps(le), &ExprKind::DropTemps(re)) => self.eq_expr(le, re),
328             _ => false,
329         };
330         is_eq || self.inner.expr_fallback.as_mut().map_or(false, |f| f(left, right))
331     }
332
333     fn eq_exprs(&mut self, left: &[Expr<'_>], right: &[Expr<'_>]) -> bool {
334         over(left, right, |l, r| self.eq_expr(l, r))
335     }
336
337     fn eq_expr_field(&mut self, left: &ExprField<'_>, right: &ExprField<'_>) -> bool {
338         left.ident.name == right.ident.name && self.eq_expr(left.expr, right.expr)
339     }
340
341     fn eq_guard(&mut self, left: &Guard<'_>, right: &Guard<'_>) -> bool {
342         match (left, right) {
343             (Guard::If(l), Guard::If(r)) => self.eq_expr(l, r),
344             (Guard::IfLet(l), Guard::IfLet(r)) => {
345                 self.eq_pat(l.pat, r.pat) && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r)) && self.eq_expr(l.init, r.init)
346             },
347             _ => false,
348         }
349     }
350
351     fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool {
352         match (left, right) {
353             (GenericArg::Const(l), GenericArg::Const(r)) => self.eq_body(l.value.body, r.value.body),
354             (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt),
355             (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty),
356             (GenericArg::Infer(l_inf), GenericArg::Infer(r_inf)) => self.eq_ty(&l_inf.to_ty(), &r_inf.to_ty()),
357             _ => false,
358         }
359     }
360
361     fn eq_lifetime(left: &Lifetime, right: &Lifetime) -> bool {
362         left.name == right.name
363     }
364
365     fn eq_pat_field(&mut self, left: &PatField<'_>, right: &PatField<'_>) -> bool {
366         let (PatField { ident: li, pat: lp, .. }, PatField { ident: ri, pat: rp, .. }) = (&left, &right);
367         li.name == ri.name && self.eq_pat(lp, rp)
368     }
369
370     /// Checks whether two patterns are the same.
371     fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool {
372         match (&left.kind, &right.kind) {
373             (&PatKind::Box(l), &PatKind::Box(r)) => self.eq_pat(l, r),
374             (&PatKind::Struct(ref lp, la, ..), &PatKind::Struct(ref rp, ra, ..)) => {
375                 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat_field(l, r))
376             },
377             (&PatKind::TupleStruct(ref lp, la, ls), &PatKind::TupleStruct(ref rp, ra, rs)) => {
378                 self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs
379             },
380             (&PatKind::Binding(lb, li, _, ref lp), &PatKind::Binding(rb, ri, _, ref rp)) => {
381                 let eq = lb == rb && both(lp, rp, |l, r| self.eq_pat(l, r));
382                 if eq {
383                     self.locals.insert(li, ri);
384                 }
385                 eq
386             },
387             (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r),
388             (&PatKind::Lit(l), &PatKind::Lit(r)) => self.eq_expr(l, r),
389             (&PatKind::Tuple(l, ls), &PatKind::Tuple(r, rs)) => ls == rs && over(l, r, |l, r| self.eq_pat(l, r)),
390             (&PatKind::Range(ref ls, ref le, li), &PatKind::Range(ref rs, ref re, ri)) => {
391                 both(ls, rs, |a, b| self.eq_expr(a, b)) && both(le, re, |a, b| self.eq_expr(a, b)) && (li == ri)
392             },
393             (&PatKind::Ref(le, ref lm), &PatKind::Ref(re, ref rm)) => lm == rm && self.eq_pat(le, re),
394             (&PatKind::Slice(ls, ref li, le), &PatKind::Slice(rs, ref ri, re)) => {
395                 over(ls, rs, |l, r| self.eq_pat(l, r))
396                     && over(le, re, |l, r| self.eq_pat(l, r))
397                     && both(li, ri, |l, r| self.eq_pat(l, r))
398             },
399             (&PatKind::Wild, &PatKind::Wild) => true,
400             _ => false,
401         }
402     }
403
404     #[expect(clippy::similar_names)]
405     fn eq_qpath(&mut self, left: &QPath<'_>, right: &QPath<'_>) -> bool {
406         match (left, right) {
407             (&QPath::Resolved(ref lty, lpath), &QPath::Resolved(ref rty, rpath)) => {
408                 both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath)
409             },
410             (&QPath::TypeRelative(lty, lseg), &QPath::TypeRelative(rty, rseg)) => {
411                 self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg)
412             },
413             (&QPath::LangItem(llang_item, ..), &QPath::LangItem(rlang_item, ..)) => llang_item == rlang_item,
414             _ => false,
415         }
416     }
417
418     pub fn eq_path(&mut self, left: &Path<'_>, right: &Path<'_>) -> bool {
419         match (left.res, right.res) {
420             (Res::Local(l), Res::Local(r)) => l == r || self.locals.get(&l) == Some(&r),
421             (Res::Local(_), _) | (_, Res::Local(_)) => false,
422             _ => over(left.segments, right.segments, |l, r| self.eq_path_segment(l, r)),
423         }
424     }
425
426     fn eq_path_parameters(&mut self, left: &GenericArgs<'_>, right: &GenericArgs<'_>) -> bool {
427         if !(left.parenthesized || right.parenthesized) {
428             over(left.args, right.args, |l, r| self.eq_generic_arg(l, r)) // FIXME(flip1995): may not work
429                 && over(left.bindings, right.bindings, |l, r| self.eq_type_binding(l, r))
430         } else if left.parenthesized && right.parenthesized {
431             over(left.inputs(), right.inputs(), |l, r| self.eq_ty(l, r))
432                 && both(&Some(&left.bindings[0].ty()), &Some(&right.bindings[0].ty()), |l, r| {
433                     self.eq_ty(l, r)
434                 })
435         } else {
436             false
437         }
438     }
439
440     pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool {
441         left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r))
442     }
443
444     pub fn eq_path_segment(&mut self, left: &PathSegment<'_>, right: &PathSegment<'_>) -> bool {
445         // The == of idents doesn't work with different contexts,
446         // we have to be explicit about hygiene
447         left.ident.name == right.ident.name && both(&left.args, &right.args, |l, r| self.eq_path_parameters(l, r))
448     }
449
450     pub fn eq_ty(&mut self, left: &Ty<'_>, right: &Ty<'_>) -> bool {
451         match (&left.kind, &right.kind) {
452             (&TyKind::Slice(l_vec), &TyKind::Slice(r_vec)) => self.eq_ty(l_vec, r_vec),
453             (&TyKind::Array(lt, ll), &TyKind::Array(rt, rl)) => self.eq_ty(lt, rt) && self.eq_array_length(ll, rl),
454             (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => {
455                 l_mut.mutbl == r_mut.mutbl && self.eq_ty(l_mut.ty, r_mut.ty)
456             },
457             (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => {
458                 l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(l_rmut.ty, r_rmut.ty)
459             },
460             (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r),
461             (&TyKind::Tup(l), &TyKind::Tup(r)) => over(l, r, |l, r| self.eq_ty(l, r)),
462             (&TyKind::Infer, &TyKind::Infer) => true,
463             _ => false,
464         }
465     }
466
467     fn eq_type_binding(&mut self, left: &TypeBinding<'_>, right: &TypeBinding<'_>) -> bool {
468         left.ident.name == right.ident.name && self.eq_ty(left.ty(), right.ty())
469     }
470 }
471
472 /// Some simple reductions like `{ return }` => `return`
473 fn reduce_exprkind<'hir>(cx: &LateContext<'_>, kind: &'hir ExprKind<'hir>) -> &'hir ExprKind<'hir> {
474     if let ExprKind::Block(block, _) = kind {
475         match (block.stmts, block.expr) {
476             // From an `if let` expression without an `else` block. The arm for the implicit wild pattern is an empty
477             // block with an empty span.
478             ([], None) if block.span.is_empty() => &ExprKind::Tup(&[]),
479             // `{}` => `()`
480             ([], None) => match snippet_opt(cx, block.span) {
481                 // Don't reduce if there are any tokens contained in the braces
482                 Some(snip)
483                     if tokenize(&snip)
484                         .map(|t| t.kind)
485                         .filter(|t| {
486                             !matches!(
487                                 t,
488                                 TokenKind::LineComment { .. } | TokenKind::BlockComment { .. } | TokenKind::Whitespace
489                             )
490                         })
491                         .ne([TokenKind::OpenBrace, TokenKind::CloseBrace].iter().copied()) =>
492                 {
493                     kind
494                 },
495                 _ => &ExprKind::Tup(&[]),
496             },
497             ([], Some(expr)) => match expr.kind {
498                 // `{ return .. }` => `return ..`
499                 ExprKind::Ret(..) => &expr.kind,
500                 _ => kind,
501             },
502             ([stmt], None) => match stmt.kind {
503                 StmtKind::Expr(expr) | StmtKind::Semi(expr) => match expr.kind {
504                     // `{ return ..; }` => `return ..`
505                     ExprKind::Ret(..) => &expr.kind,
506                     _ => kind,
507                 },
508                 _ => kind,
509             },
510             _ => kind,
511         }
512     } else {
513         kind
514     }
515 }
516
517 fn swap_binop<'a>(
518     binop: BinOpKind,
519     lhs: &'a Expr<'a>,
520     rhs: &'a Expr<'a>,
521 ) -> Option<(BinOpKind, &'a Expr<'a>, &'a Expr<'a>)> {
522     match binop {
523         BinOpKind::Add | BinOpKind::Eq | BinOpKind::Ne | BinOpKind::BitAnd | BinOpKind::BitXor | BinOpKind::BitOr => {
524             Some((binop, rhs, lhs))
525         },
526         BinOpKind::Lt => Some((BinOpKind::Gt, rhs, lhs)),
527         BinOpKind::Le => Some((BinOpKind::Ge, rhs, lhs)),
528         BinOpKind::Ge => Some((BinOpKind::Le, rhs, lhs)),
529         BinOpKind::Gt => Some((BinOpKind::Lt, rhs, lhs)),
530         BinOpKind::Mul // Not always commutative, e.g. with matrices. See issue #5698
531         | BinOpKind::Shl
532         | BinOpKind::Shr
533         | BinOpKind::Rem
534         | BinOpKind::Sub
535         | BinOpKind::Div
536         | BinOpKind::And
537         | BinOpKind::Or => None,
538     }
539 }
540
541 /// Checks if the two `Option`s are both `None` or some equal values as per
542 /// `eq_fn`.
543 pub fn both<X>(l: &Option<X>, r: &Option<X>, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
544     l.as_ref()
545         .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
546 }
547
548 /// Checks if two slices are equal as per `eq_fn`.
549 pub fn over<X>(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool {
550     left.len() == right.len() && left.iter().zip(right).all(|(x, y)| eq_fn(x, y))
551 }
552
553 /// Counts how many elements of the slices are equal as per `eq_fn`.
554 pub fn count_eq<X: Sized>(
555     left: &mut dyn Iterator<Item = X>,
556     right: &mut dyn Iterator<Item = X>,
557     mut eq_fn: impl FnMut(&X, &X) -> bool,
558 ) -> usize {
559     left.zip(right).take_while(|(l, r)| eq_fn(l, r)).count()
560 }
561
562 /// Checks if two expressions evaluate to the same value, and don't contain any side effects.
563 pub fn eq_expr_value(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>) -> bool {
564     SpanlessEq::new(cx).deny_side_effects().eq_expr(left, right)
565 }
566
567 /// Type used to hash an ast element. This is different from the `Hash` trait
568 /// on ast types as this
569 /// trait would consider IDs and spans.
570 ///
571 /// All expressions kind are hashed, but some might have a weaker hash.
572 pub struct SpanlessHash<'a, 'tcx> {
573     /// Context used to evaluate constant expressions.
574     cx: &'a LateContext<'tcx>,
575     maybe_typeck_results: Option<&'tcx TypeckResults<'tcx>>,
576     s: FxHasher,
577 }
578
579 impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
580     pub fn new(cx: &'a LateContext<'tcx>) -> Self {
581         Self {
582             cx,
583             maybe_typeck_results: cx.maybe_typeck_results(),
584             s: FxHasher::default(),
585         }
586     }
587
588     pub fn finish(self) -> u64 {
589         self.s.finish()
590     }
591
592     pub fn hash_block(&mut self, b: &Block<'_>) {
593         for s in b.stmts {
594             self.hash_stmt(s);
595         }
596
597         if let Some(e) = b.expr {
598             self.hash_expr(e);
599         }
600
601         std::mem::discriminant(&b.rules).hash(&mut self.s);
602     }
603
604     #[expect(clippy::too_many_lines)]
605     pub fn hash_expr(&mut self, e: &Expr<'_>) {
606         let simple_const = self
607             .maybe_typeck_results
608             .and_then(|typeck_results| constant_simple(self.cx, typeck_results, e));
609
610         // const hashing may result in the same hash as some unrelated node, so add a sort of
611         // discriminant depending on which path we're choosing next
612         simple_const.hash(&mut self.s);
613         if simple_const.is_some() {
614             return;
615         }
616
617         std::mem::discriminant(&e.kind).hash(&mut self.s);
618
619         match e.kind {
620             ExprKind::AddrOf(kind, m, e) => {
621                 std::mem::discriminant(&kind).hash(&mut self.s);
622                 m.hash(&mut self.s);
623                 self.hash_expr(e);
624             },
625             ExprKind::Continue(i) => {
626                 if let Some(i) = i.label {
627                     self.hash_name(i.ident.name);
628                 }
629             },
630             ExprKind::Assign(l, r, _) => {
631                 self.hash_expr(l);
632                 self.hash_expr(r);
633             },
634             ExprKind::AssignOp(ref o, l, r) => {
635                 std::mem::discriminant(&o.node).hash(&mut self.s);
636                 self.hash_expr(l);
637                 self.hash_expr(r);
638             },
639             ExprKind::Block(b, _) => {
640                 self.hash_block(b);
641             },
642             ExprKind::Binary(op, l, r) => {
643                 std::mem::discriminant(&op.node).hash(&mut self.s);
644                 self.hash_expr(l);
645                 self.hash_expr(r);
646             },
647             ExprKind::Break(i, ref j) => {
648                 if let Some(i) = i.label {
649                     self.hash_name(i.ident.name);
650                 }
651                 if let Some(j) = *j {
652                     self.hash_expr(j);
653                 }
654             },
655             ExprKind::Box(e) | ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => {
656                 self.hash_expr(e);
657             },
658             ExprKind::Call(fun, args) => {
659                 self.hash_expr(fun);
660                 self.hash_exprs(args);
661             },
662             ExprKind::Cast(e, ty) | ExprKind::Type(e, ty) => {
663                 self.hash_expr(e);
664                 self.hash_ty(ty);
665             },
666             ExprKind::Closure(&Closure {
667                 capture_clause, body, ..
668             }) => {
669                 std::mem::discriminant(&capture_clause).hash(&mut self.s);
670                 // closures inherit TypeckResults
671                 self.hash_expr(&self.cx.tcx.hir().body(body).value);
672             },
673             ExprKind::Field(e, ref f) => {
674                 self.hash_expr(e);
675                 self.hash_name(f.name);
676             },
677             ExprKind::Index(a, i) => {
678                 self.hash_expr(a);
679                 self.hash_expr(i);
680             },
681             ExprKind::InlineAsm(asm) => {
682                 for piece in asm.template {
683                     match piece {
684                         InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s),
685                         InlineAsmTemplatePiece::Placeholder {
686                             operand_idx,
687                             modifier,
688                             span: _,
689                         } => {
690                             operand_idx.hash(&mut self.s);
691                             modifier.hash(&mut self.s);
692                         },
693                     }
694                 }
695                 asm.options.hash(&mut self.s);
696                 for (op, _op_sp) in asm.operands {
697                     match op {
698                         InlineAsmOperand::In { reg, expr } => {
699                             reg.hash(&mut self.s);
700                             self.hash_expr(expr);
701                         },
702                         InlineAsmOperand::Out { reg, late, expr } => {
703                             reg.hash(&mut self.s);
704                             late.hash(&mut self.s);
705                             if let Some(expr) = expr {
706                                 self.hash_expr(expr);
707                             }
708                         },
709                         InlineAsmOperand::InOut { reg, late, expr } => {
710                             reg.hash(&mut self.s);
711                             late.hash(&mut self.s);
712                             self.hash_expr(expr);
713                         },
714                         InlineAsmOperand::SplitInOut {
715                             reg,
716                             late,
717                             in_expr,
718                             out_expr,
719                         } => {
720                             reg.hash(&mut self.s);
721                             late.hash(&mut self.s);
722                             self.hash_expr(in_expr);
723                             if let Some(out_expr) = out_expr {
724                                 self.hash_expr(out_expr);
725                             }
726                         },
727                         InlineAsmOperand::Const { anon_const } | InlineAsmOperand::SymFn { anon_const } => {
728                             self.hash_body(anon_const.body);
729                         },
730                         InlineAsmOperand::SymStatic { path, def_id: _ } => self.hash_qpath(path),
731                     }
732                 }
733             },
734             ExprKind::Let(Let { pat, init, ty, .. }) => {
735                 self.hash_expr(init);
736                 if let Some(ty) = ty {
737                     self.hash_ty(ty);
738                 }
739                 self.hash_pat(pat);
740             },
741             ExprKind::Err => {},
742             ExprKind::Lit(ref l) => {
743                 l.node.hash(&mut self.s);
744             },
745             ExprKind::Loop(b, ref i, ..) => {
746                 self.hash_block(b);
747                 if let Some(i) = *i {
748                     self.hash_name(i.ident.name);
749                 }
750             },
751             ExprKind::If(cond, then, ref else_opt) => {
752                 self.hash_expr(cond);
753                 self.hash_expr(then);
754                 if let Some(e) = *else_opt {
755                     self.hash_expr(e);
756                 }
757             },
758             ExprKind::Match(e, arms, ref s) => {
759                 self.hash_expr(e);
760
761                 for arm in arms {
762                     self.hash_pat(arm.pat);
763                     if let Some(ref e) = arm.guard {
764                         self.hash_guard(e);
765                     }
766                     self.hash_expr(arm.body);
767                 }
768
769                 s.hash(&mut self.s);
770             },
771             ExprKind::MethodCall(path, args, ref _fn_span) => {
772                 self.hash_name(path.ident.name);
773                 self.hash_exprs(args);
774             },
775             ExprKind::ConstBlock(ref l_id) => {
776                 self.hash_body(l_id.body);
777             },
778             ExprKind::Repeat(e, len) => {
779                 self.hash_expr(e);
780                 self.hash_array_length(len);
781             },
782             ExprKind::Ret(ref e) => {
783                 if let Some(e) = *e {
784                     self.hash_expr(e);
785                 }
786             },
787             ExprKind::Path(ref qpath) => {
788                 self.hash_qpath(qpath);
789             },
790             ExprKind::Struct(path, fields, ref expr) => {
791                 self.hash_qpath(path);
792
793                 for f in fields {
794                     self.hash_name(f.ident.name);
795                     self.hash_expr(f.expr);
796                 }
797
798                 if let Some(e) = *expr {
799                     self.hash_expr(e);
800                 }
801             },
802             ExprKind::Tup(tup) => {
803                 self.hash_exprs(tup);
804             },
805             ExprKind::Array(v) => {
806                 self.hash_exprs(v);
807             },
808             ExprKind::Unary(lop, le) => {
809                 std::mem::discriminant(&lop).hash(&mut self.s);
810                 self.hash_expr(le);
811             },
812         }
813     }
814
815     pub fn hash_exprs(&mut self, e: &[Expr<'_>]) {
816         for e in e {
817             self.hash_expr(e);
818         }
819     }
820
821     pub fn hash_name(&mut self, n: Symbol) {
822         n.hash(&mut self.s);
823     }
824
825     pub fn hash_qpath(&mut self, p: &QPath<'_>) {
826         match *p {
827             QPath::Resolved(_, path) => {
828                 self.hash_path(path);
829             },
830             QPath::TypeRelative(_, path) => {
831                 self.hash_name(path.ident.name);
832             },
833             QPath::LangItem(lang_item, ..) => {
834                 std::mem::discriminant(&lang_item).hash(&mut self.s);
835             },
836         }
837         // self.maybe_typeck_results.unwrap().qpath_res(p, id).hash(&mut self.s);
838     }
839
840     pub fn hash_pat(&mut self, pat: &Pat<'_>) {
841         std::mem::discriminant(&pat.kind).hash(&mut self.s);
842         match pat.kind {
843             PatKind::Binding(ann, _, _, pat) => {
844                 std::mem::discriminant(&ann).hash(&mut self.s);
845                 if let Some(pat) = pat {
846                     self.hash_pat(pat);
847                 }
848             },
849             PatKind::Box(pat) => self.hash_pat(pat),
850             PatKind::Lit(expr) => self.hash_expr(expr),
851             PatKind::Or(pats) => {
852                 for pat in pats {
853                     self.hash_pat(pat);
854                 }
855             },
856             PatKind::Path(ref qpath) => self.hash_qpath(qpath),
857             PatKind::Range(s, e, i) => {
858                 if let Some(s) = s {
859                     self.hash_expr(s);
860                 }
861                 if let Some(e) = e {
862                     self.hash_expr(e);
863                 }
864                 std::mem::discriminant(&i).hash(&mut self.s);
865             },
866             PatKind::Ref(pat, mu) => {
867                 self.hash_pat(pat);
868                 std::mem::discriminant(&mu).hash(&mut self.s);
869             },
870             PatKind::Slice(l, m, r) => {
871                 for pat in l {
872                     self.hash_pat(pat);
873                 }
874                 if let Some(pat) = m {
875                     self.hash_pat(pat);
876                 }
877                 for pat in r {
878                     self.hash_pat(pat);
879                 }
880             },
881             PatKind::Struct(ref qpath, fields, e) => {
882                 self.hash_qpath(qpath);
883                 for f in fields {
884                     self.hash_name(f.ident.name);
885                     self.hash_pat(f.pat);
886                 }
887                 e.hash(&mut self.s);
888             },
889             PatKind::Tuple(pats, e) => {
890                 for pat in pats {
891                     self.hash_pat(pat);
892                 }
893                 e.hash(&mut self.s);
894             },
895             PatKind::TupleStruct(ref qpath, pats, e) => {
896                 self.hash_qpath(qpath);
897                 for pat in pats {
898                     self.hash_pat(pat);
899                 }
900                 e.hash(&mut self.s);
901             },
902             PatKind::Wild => {},
903         }
904     }
905
906     pub fn hash_path(&mut self, path: &Path<'_>) {
907         match path.res {
908             // constant hash since equality is dependant on inter-expression context
909             // e.g. The expressions `if let Some(x) = foo() {}` and `if let Some(y) = foo() {}` are considered equal
910             // even though the binding names are different and they have different `HirId`s.
911             Res::Local(_) => 1_usize.hash(&mut self.s),
912             _ => {
913                 for seg in path.segments {
914                     self.hash_name(seg.ident.name);
915                     self.hash_generic_args(seg.args().args);
916                 }
917             },
918         }
919     }
920
921     pub fn hash_stmt(&mut self, b: &Stmt<'_>) {
922         std::mem::discriminant(&b.kind).hash(&mut self.s);
923
924         match &b.kind {
925             StmtKind::Local(local, ) => {
926                 self.hash_pat(local.pat);
927                 if let Some(init) = local.init {
928                     self.hash_expr(init);
929                 }
930                 if let Some(els) = local.els {
931                     self.hash_block(els);
932                 }
933             },
934             StmtKind::Item(..) => {},
935             StmtKind::Expr(expr) | StmtKind::Semi(expr) => {
936                 self.hash_expr(expr);
937             },
938         }
939     }
940
941     pub fn hash_guard(&mut self, g: &Guard<'_>) {
942         match g {
943             Guard::If(expr) | Guard::IfLet(Let { init: expr, .. }) => {
944                 self.hash_expr(expr);
945             },
946         }
947     }
948
949     pub fn hash_lifetime(&mut self, lifetime: Lifetime) {
950         std::mem::discriminant(&lifetime.name).hash(&mut self.s);
951         if let LifetimeName::Param(param_id, ref name) = lifetime.name {
952             std::mem::discriminant(name).hash(&mut self.s);
953             param_id.hash(&mut self.s);
954             match name {
955                 ParamName::Plain(ref ident) => {
956                     ident.name.hash(&mut self.s);
957                 },
958                 ParamName::Fresh | ParamName::Error => {},
959             }
960         }
961     }
962
963     pub fn hash_ty(&mut self, ty: &Ty<'_>) {
964         std::mem::discriminant(&ty.kind).hash(&mut self.s);
965         self.hash_tykind(&ty.kind);
966     }
967
968     pub fn hash_tykind(&mut self, ty: &TyKind<'_>) {
969         match ty {
970             TyKind::Slice(ty) => {
971                 self.hash_ty(ty);
972             },
973             &TyKind::Array(ty, len) => {
974                 self.hash_ty(ty);
975                 self.hash_array_length(len);
976             },
977             TyKind::Ptr(ref mut_ty) => {
978                 self.hash_ty(mut_ty.ty);
979                 mut_ty.mutbl.hash(&mut self.s);
980             },
981             TyKind::Rptr(lifetime, ref mut_ty) => {
982                 self.hash_lifetime(*lifetime);
983                 self.hash_ty(mut_ty.ty);
984                 mut_ty.mutbl.hash(&mut self.s);
985             },
986             TyKind::BareFn(bfn) => {
987                 bfn.unsafety.hash(&mut self.s);
988                 bfn.abi.hash(&mut self.s);
989                 for arg in bfn.decl.inputs {
990                     self.hash_ty(arg);
991                 }
992                 std::mem::discriminant(&bfn.decl.output).hash(&mut self.s);
993                 match bfn.decl.output {
994                     FnRetTy::DefaultReturn(_) => {},
995                     FnRetTy::Return(ty) => {
996                         self.hash_ty(ty);
997                     },
998                 }
999                 bfn.decl.c_variadic.hash(&mut self.s);
1000             },
1001             TyKind::Tup(ty_list) => {
1002                 for ty in *ty_list {
1003                     self.hash_ty(ty);
1004                 }
1005             },
1006             TyKind::Path(ref qpath) => self.hash_qpath(qpath),
1007             TyKind::OpaqueDef(_, arg_list) => {
1008                 self.hash_generic_args(arg_list);
1009             },
1010             TyKind::TraitObject(_, lifetime, _) => {
1011                 self.hash_lifetime(*lifetime);
1012             },
1013             TyKind::Typeof(anon_const) => {
1014                 self.hash_body(anon_const.body);
1015             },
1016             TyKind::Err | TyKind::Infer | TyKind::Never => {},
1017         }
1018     }
1019
1020     pub fn hash_array_length(&mut self, length: ArrayLen) {
1021         match length {
1022             ArrayLen::Infer(..) => {},
1023             ArrayLen::Body(anon_const) => self.hash_body(anon_const.body),
1024         }
1025     }
1026
1027     pub fn hash_body(&mut self, body_id: BodyId) {
1028         // swap out TypeckResults when hashing a body
1029         let old_maybe_typeck_results = self.maybe_typeck_results.replace(self.cx.tcx.typeck_body(body_id));
1030         self.hash_expr(&self.cx.tcx.hir().body(body_id).value);
1031         self.maybe_typeck_results = old_maybe_typeck_results;
1032     }
1033
1034     fn hash_generic_args(&mut self, arg_list: &[GenericArg<'_>]) {
1035         for arg in arg_list {
1036             match *arg {
1037                 GenericArg::Lifetime(l) => self.hash_lifetime(l),
1038                 GenericArg::Type(ref ty) => self.hash_ty(ty),
1039                 GenericArg::Const(ref ca) => self.hash_body(ca.value.body),
1040                 GenericArg::Infer(ref inf) => self.hash_ty(&inf.to_ty()),
1041             }
1042         }
1043     }
1044 }
1045
1046 pub fn hash_stmt(cx: &LateContext<'_>, s: &Stmt<'_>) -> u64 {
1047     let mut h = SpanlessHash::new(cx);
1048     h.hash_stmt(s);
1049     h.finish()
1050 }
1051
1052 pub fn hash_expr(cx: &LateContext<'_>, e: &Expr<'_>) -> u64 {
1053     let mut h = SpanlessHash::new(cx);
1054     h.hash_expr(e);
1055     h.finish()
1056 }