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