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