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