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