]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_clamp.rs
Rollup merge of #102811 - the8472:bufread-memset, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / manual_clamp.rs
1 use itertools::Itertools;
2 use rustc_errors::Diagnostic;
3 use rustc_hir::{
4     def::Res, Arm, BinOpKind, Block, Expr, ExprKind, Guard, HirId, PatKind, PathSegment, PrimTy, QPath, StmtKind,
5 };
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::Ty;
8 use rustc_semver::RustcVersion;
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::{symbol::sym, Span};
11 use std::ops::Deref;
12
13 use clippy_utils::{
14     diagnostics::{span_lint_and_then, span_lint_hir_and_then},
15     eq_expr_value, get_trait_def_id,
16     higher::If,
17     is_diag_trait_item, is_trait_method, meets_msrv, msrvs, path_res, path_to_local_id, paths, peel_blocks,
18     peel_blocks_with_stmt,
19     sugg::Sugg,
20     ty::implements_trait,
21     visitors::is_const_evaluatable,
22     MaybePath,
23 };
24 use rustc_errors::Applicability;
25
26 declare_clippy_lint! {
27     /// ### What it does
28     /// Identifies good opportunities for a clamp function from std or core, and suggests using it.
29     ///
30     /// ### Why is this bad?
31     /// clamp is much shorter, easier to read, and doesn't use any control flow.
32     ///
33     /// ### Known issue(s)
34     /// If the clamped variable is NaN this suggestion will cause the code to propagate NaN
35     /// rather than returning either `max` or `min`.
36     ///
37     /// `clamp` functions will panic if `max < min`, `max.is_nan()`, or `min.is_nan()`.
38     /// Some may consider panicking in these situations to be desirable, but it also may
39     /// introduce panicking where there wasn't any before.
40     ///
41     /// ### Examples
42     /// ```rust
43     /// # let (input, min, max) = (0, -2, 1);
44     /// if input > max {
45     ///     max
46     /// } else if input < min {
47     ///     min
48     /// } else {
49     ///     input
50     /// }
51     /// # ;
52     /// ```
53     ///
54     /// ```rust
55     /// # let (input, min, max) = (0, -2, 1);
56     /// input.max(min).min(max)
57     /// # ;
58     /// ```
59     ///
60     /// ```rust
61     /// # let (input, min, max) = (0, -2, 1);
62     /// match input {
63     ///     x if x > max => max,
64     ///     x if x < min => min,
65     ///     x => x,
66     /// }
67     /// # ;
68     /// ```
69     ///
70     /// ```rust
71     /// # let (input, min, max) = (0, -2, 1);
72     /// let mut x = input;
73     /// if x < min { x = min; }
74     /// if x > max { x = max; }
75     /// ```
76     /// Use instead:
77     /// ```rust
78     /// # let (input, min, max) = (0, -2, 1);
79     /// input.clamp(min, max)
80     /// # ;
81     /// ```
82     #[clippy::version = "1.66.0"]
83     pub MANUAL_CLAMP,
84     complexity,
85     "using a clamp pattern instead of the clamp function"
86 }
87 impl_lint_pass!(ManualClamp => [MANUAL_CLAMP]);
88
89 pub struct ManualClamp {
90     msrv: Option<RustcVersion>,
91 }
92
93 impl ManualClamp {
94     pub fn new(msrv: Option<RustcVersion>) -> Self {
95         Self { msrv }
96     }
97 }
98
99 #[derive(Debug)]
100 struct ClampSuggestion<'tcx> {
101     params: InputMinMax<'tcx>,
102     span: Span,
103     make_assignment: Option<&'tcx Expr<'tcx>>,
104     hir_with_ignore_attr: Option<HirId>,
105 }
106
107 #[derive(Debug)]
108 struct InputMinMax<'tcx> {
109     input: &'tcx Expr<'tcx>,
110     min: &'tcx Expr<'tcx>,
111     max: &'tcx Expr<'tcx>,
112     is_float: bool,
113 }
114
115 impl<'tcx> LateLintPass<'tcx> for ManualClamp {
116     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
117         if !meets_msrv(self.msrv, msrvs::CLAMP) {
118             return;
119         }
120         if !expr.span.from_expansion() {
121             let suggestion = is_if_elseif_else_pattern(cx, expr)
122                 .or_else(|| is_max_min_pattern(cx, expr))
123                 .or_else(|| is_call_max_min_pattern(cx, expr))
124                 .or_else(|| is_match_pattern(cx, expr))
125                 .or_else(|| is_if_elseif_pattern(cx, expr));
126             if let Some(suggestion) = suggestion {
127                 emit_suggestion(cx, &suggestion);
128             }
129         }
130     }
131
132     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) {
133         if !meets_msrv(self.msrv, msrvs::CLAMP) {
134             return;
135         }
136         for suggestion in is_two_if_pattern(cx, block) {
137             emit_suggestion(cx, &suggestion);
138         }
139     }
140     extract_msrv_attr!(LateContext);
141 }
142
143 fn emit_suggestion<'tcx>(cx: &LateContext<'tcx>, suggestion: &ClampSuggestion<'tcx>) {
144     let ClampSuggestion {
145         params: InputMinMax {
146             input,
147             min,
148             max,
149             is_float,
150         },
151         span,
152         make_assignment,
153         hir_with_ignore_attr,
154     } = suggestion;
155     let input = Sugg::hir(cx, input, "..").maybe_par();
156     let min = Sugg::hir(cx, min, "..");
157     let max = Sugg::hir(cx, max, "..");
158     let semicolon = if make_assignment.is_some() { ";" } else { "" };
159     let assignment = if let Some(assignment) = make_assignment {
160         let assignment = Sugg::hir(cx, assignment, "..");
161         format!("{assignment} = ")
162     } else {
163         String::new()
164     };
165     let suggestion = format!("{assignment}{input}.clamp({min}, {max}){semicolon}");
166     let msg = "clamp-like pattern without using clamp function";
167     let lint_builder = |d: &mut Diagnostic| {
168         d.span_suggestion(*span, "replace with clamp", suggestion, Applicability::MaybeIncorrect);
169         if *is_float {
170             d.note("clamp will panic if max < min, min.is_nan(), or max.is_nan()")
171                 .note("clamp returns NaN if the input is NaN");
172         } else {
173             d.note("clamp will panic if max < min");
174         }
175     };
176     if let Some(hir_id) = hir_with_ignore_attr {
177         span_lint_hir_and_then(cx, MANUAL_CLAMP, *hir_id, *span, msg, lint_builder);
178     } else {
179         span_lint_and_then(cx, MANUAL_CLAMP, *span, msg, lint_builder);
180     }
181 }
182
183 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
184 enum TypeClampability {
185     Float,
186     Ord,
187 }
188
189 impl TypeClampability {
190     fn is_clampable<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<TypeClampability> {
191         if ty.is_floating_point() {
192             Some(TypeClampability::Float)
193         } else if get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])) {
194             Some(TypeClampability::Ord)
195         } else {
196             None
197         }
198     }
199
200     fn is_float(self) -> bool {
201         matches!(self, TypeClampability::Float)
202     }
203 }
204
205 /// Targets patterns like
206 ///
207 /// ```
208 /// # let (input, min, max) = (0, -3, 12);
209 ///
210 /// if input < min {
211 ///     min
212 /// } else if input > max {
213 ///     max
214 /// } else {
215 ///     input
216 /// }
217 /// # ;
218 /// ```
219 fn is_if_elseif_else_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
220     if let Some(If {
221         cond,
222         then,
223         r#else: Some(else_if),
224     }) = If::hir(expr)
225     && let Some(If {
226         cond: else_if_cond,
227         then: else_if_then,
228         r#else: Some(else_body),
229     }) = If::hir(peel_blocks(else_if))
230     {
231         let params = is_clamp_meta_pattern(
232             cx,
233             &BinaryOp::new(peel_blocks(cond))?,
234             &BinaryOp::new(peel_blocks(else_if_cond))?,
235             peel_blocks(then),
236             peel_blocks(else_if_then),
237             None,
238         )?;
239         // Contents of the else should be the resolved input.
240         if !eq_expr_value(cx, params.input, peel_blocks(else_body)) {
241             return None;
242         }
243         Some(ClampSuggestion {
244             params,
245             span: expr.span,
246             make_assignment: None,
247             hir_with_ignore_attr: None,
248         })
249     } else {
250         None
251     }
252 }
253
254 /// Targets patterns like
255 ///
256 /// ```
257 /// # let (input, min_value, max_value) = (0, -3, 12);
258 ///
259 /// input.max(min_value).min(max_value)
260 /// # ;
261 /// ```
262 fn is_max_min_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
263     if let ExprKind::MethodCall(seg_second, receiver, [arg_second], _) = &expr.kind
264         && (cx.typeck_results().expr_ty_adjusted(receiver).is_floating_point() || is_trait_method(cx, expr, sym::Ord))
265         && let ExprKind::MethodCall(seg_first, input, [arg_first], _) = &receiver.kind
266         && (cx.typeck_results().expr_ty_adjusted(input).is_floating_point() || is_trait_method(cx, receiver, sym::Ord))
267     {
268         let is_float = cx.typeck_results().expr_ty_adjusted(input).is_floating_point();
269         let (min, max) = match (seg_first.ident.as_str(), seg_second.ident.as_str()) {
270             ("min", "max") => (arg_second, arg_first),
271             ("max", "min") => (arg_first, arg_second),
272             _ => return None,
273         };
274         Some(ClampSuggestion {
275             params: InputMinMax { input, min, max, is_float },
276             span: expr.span,
277             make_assignment: None,
278             hir_with_ignore_attr: None,
279         })
280     } else {
281         None
282     }
283 }
284
285 /// Targets patterns like
286 ///
287 /// ```
288 /// # let (input, min_value, max_value) = (0, -3, 12);
289 /// # use std::cmp::{max, min};
290 /// min(max(input, min_value), max_value)
291 /// # ;
292 /// ```
293 fn is_call_max_min_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
294     fn segment<'tcx>(cx: &LateContext<'_>, func: &Expr<'tcx>) -> Option<FunctionType<'tcx>> {
295         match func.kind {
296             ExprKind::Path(QPath::Resolved(None, path)) => {
297                 let id = path.res.opt_def_id()?;
298                 match cx.tcx.get_diagnostic_name(id) {
299                     Some(sym::cmp_min) => Some(FunctionType::CmpMin),
300                     Some(sym::cmp_max) => Some(FunctionType::CmpMax),
301                     _ if is_diag_trait_item(cx, id, sym::Ord) => {
302                         Some(FunctionType::OrdOrFloat(path.segments.last().expect("infallible")))
303                     },
304                     _ => None,
305                 }
306             },
307             ExprKind::Path(QPath::TypeRelative(ty, seg)) => {
308                 matches!(path_res(cx, ty), Res::PrimTy(PrimTy::Float(_))).then(|| FunctionType::OrdOrFloat(seg))
309             },
310             _ => None,
311         }
312     }
313
314     enum FunctionType<'tcx> {
315         CmpMin,
316         CmpMax,
317         OrdOrFloat(&'tcx PathSegment<'tcx>),
318     }
319
320     fn check<'tcx>(
321         cx: &LateContext<'tcx>,
322         outer_fn: &'tcx Expr<'tcx>,
323         inner_call: &'tcx Expr<'tcx>,
324         outer_arg: &'tcx Expr<'tcx>,
325         span: Span,
326     ) -> Option<ClampSuggestion<'tcx>> {
327         if let ExprKind::Call(inner_fn, [first, second]) = &inner_call.kind
328             && let Some(inner_seg) = segment(cx, inner_fn)
329             && let Some(outer_seg) = segment(cx, outer_fn)
330         {
331             let (input, inner_arg) = match (is_const_evaluatable(cx, first), is_const_evaluatable(cx, second)) {
332                 (true, false) => (second, first),
333                 (false, true) => (first, second),
334                 _ => return None,
335             };
336             let is_float = cx.typeck_results().expr_ty_adjusted(input).is_floating_point();
337             let (min, max) = match (inner_seg, outer_seg) {
338                 (FunctionType::CmpMin, FunctionType::CmpMax) => (outer_arg, inner_arg),
339                 (FunctionType::CmpMax, FunctionType::CmpMin) => (inner_arg, outer_arg),
340                 (FunctionType::OrdOrFloat(first_segment), FunctionType::OrdOrFloat(second_segment)) => {
341                     match (first_segment.ident.as_str(), second_segment.ident.as_str()) {
342                         ("min", "max") => (outer_arg, inner_arg),
343                         ("max", "min") => (inner_arg, outer_arg),
344                         _ => return None,
345                     }
346                 }
347                 _ => return None,
348             };
349             Some(ClampSuggestion {
350                 params: InputMinMax { input, min, max, is_float },
351                 span,
352                 make_assignment: None,
353                 hir_with_ignore_attr: None,
354             })
355         } else {
356             None
357         }
358     }
359
360     if let ExprKind::Call(outer_fn, [first, second]) = &expr.kind {
361         check(cx, outer_fn, first, second, expr.span).or_else(|| check(cx, outer_fn, second, first, expr.span))
362     } else {
363         None
364     }
365 }
366
367 /// Targets patterns like
368 ///
369 /// ```
370 /// # let (input, min, max) = (0, -3, 12);
371 ///
372 /// match input {
373 ///     input if input > max => max,
374 ///     input if input < min => min,
375 ///     input => input,
376 /// }
377 /// # ;
378 /// ```
379 fn is_match_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
380     if let ExprKind::Match(value, [first_arm, second_arm, last_arm], rustc_hir::MatchSource::Normal) = &expr.kind {
381         // Find possible min/max branches
382         let minmax_values = |a: &'tcx Arm<'tcx>| {
383             if let PatKind::Binding(_, var_hir_id, _, None) = &a.pat.kind
384             && let Some(Guard::If(e)) = a.guard {
385                 Some((e, var_hir_id, a.body))
386             } else {
387                 None
388             }
389         };
390         let (first, first_hir_id, first_expr) = minmax_values(first_arm)?;
391         let (second, second_hir_id, second_expr) = minmax_values(second_arm)?;
392         let first = BinaryOp::new(first)?;
393         let second = BinaryOp::new(second)?;
394         if let PatKind::Binding(_, binding, _, None) = &last_arm.pat.kind
395             && path_to_local_id(peel_blocks_with_stmt(last_arm.body), *binding)
396             && last_arm.guard.is_none()
397         {
398             // Proceed as normal
399         } else {
400             return None;
401         }
402         if let Some(params) = is_clamp_meta_pattern(
403             cx,
404             &first,
405             &second,
406             first_expr,
407             second_expr,
408             Some((*first_hir_id, *second_hir_id)),
409         ) {
410             return Some(ClampSuggestion {
411                 params: InputMinMax {
412                     input: value,
413                     min: params.min,
414                     max: params.max,
415                     is_float: params.is_float,
416                 },
417                 span: expr.span,
418                 make_assignment: None,
419                 hir_with_ignore_attr: None,
420             });
421         }
422     }
423     None
424 }
425
426 /// Targets patterns like
427 ///
428 /// ```
429 /// # let (input, min, max) = (0, -3, 12);
430 ///
431 /// let mut x = input;
432 /// if x < min { x = min; }
433 /// if x > max { x = max; }
434 /// ```
435 fn is_two_if_pattern<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) -> Vec<ClampSuggestion<'tcx>> {
436     block_stmt_with_last(block)
437         .tuple_windows()
438         .filter_map(|(maybe_set_first, maybe_set_second)| {
439             if let StmtKind::Expr(first_expr) = *maybe_set_first
440                 && let StmtKind::Expr(second_expr) = *maybe_set_second
441                 && let Some(If { cond: first_cond, then: first_then, r#else: None }) = If::hir(first_expr)
442                 && let Some(If { cond: second_cond, then: second_then, r#else: None }) = If::hir(second_expr)
443                 && let ExprKind::Assign(
444                     maybe_input_first_path,
445                     maybe_min_max_first,
446                     _
447                 ) = peel_blocks_with_stmt(first_then).kind
448                 && let ExprKind::Assign(
449                     maybe_input_second_path,
450                     maybe_min_max_second,
451                     _
452                 ) = peel_blocks_with_stmt(second_then).kind
453                 && eq_expr_value(cx, maybe_input_first_path, maybe_input_second_path)
454                 && let Some(first_bin) = BinaryOp::new(first_cond)
455                 && let Some(second_bin) = BinaryOp::new(second_cond)
456                 && let Some(input_min_max) = is_clamp_meta_pattern(
457                     cx,
458                     &first_bin,
459                     &second_bin,
460                     maybe_min_max_first,
461                     maybe_min_max_second,
462                     None
463                 )
464             {
465                 Some(ClampSuggestion {
466                     params: InputMinMax {
467                         input: maybe_input_first_path,
468                         min: input_min_max.min,
469                         max: input_min_max.max,
470                         is_float: input_min_max.is_float,
471                     },
472                     span: first_expr.span.to(second_expr.span),
473                     make_assignment: Some(maybe_input_first_path),
474                     hir_with_ignore_attr: Some(first_expr.hir_id()),
475                 })
476             } else {
477                 None
478             }
479         })
480         .collect()
481 }
482
483 /// Targets patterns like
484 ///
485 /// ```
486 /// # let (mut input, min, max) = (0, -3, 12);
487 ///
488 /// if input < min {
489 ///     input = min;
490 /// } else if input > max {
491 ///     input = max;
492 /// }
493 /// ```
494 fn is_if_elseif_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
495     if let Some(If {
496         cond,
497         then,
498         r#else: Some(else_if),
499     }) = If::hir(expr)
500         && let Some(If {
501             cond: else_if_cond,
502             then: else_if_then,
503             r#else: None,
504         }) = If::hir(peel_blocks(else_if))
505         && let ExprKind::Assign(
506             maybe_input_first_path,
507             maybe_min_max_first,
508             _
509         ) = peel_blocks_with_stmt(then).kind
510         && let ExprKind::Assign(
511             maybe_input_second_path,
512             maybe_min_max_second,
513             _
514         ) = peel_blocks_with_stmt(else_if_then).kind
515     {
516         let params = is_clamp_meta_pattern(
517             cx,
518             &BinaryOp::new(peel_blocks(cond))?,
519             &BinaryOp::new(peel_blocks(else_if_cond))?,
520             peel_blocks(maybe_min_max_first),
521             peel_blocks(maybe_min_max_second),
522             None,
523         )?;
524         if !eq_expr_value(cx, maybe_input_first_path, maybe_input_second_path) {
525             return None;
526         }
527         Some(ClampSuggestion {
528             params,
529             span: expr.span,
530             make_assignment: Some(maybe_input_first_path),
531             hir_with_ignore_attr: None,
532         })
533     } else {
534         None
535     }
536 }
537
538 /// `ExprKind::Binary` but more narrowly typed
539 #[derive(Debug, Clone, Copy)]
540 struct BinaryOp<'tcx> {
541     op: BinOpKind,
542     left: &'tcx Expr<'tcx>,
543     right: &'tcx Expr<'tcx>,
544 }
545
546 impl<'tcx> BinaryOp<'tcx> {
547     fn new(e: &'tcx Expr<'tcx>) -> Option<BinaryOp<'tcx>> {
548         match &e.kind {
549             ExprKind::Binary(op, left, right) => Some(BinaryOp {
550                 op: op.node,
551                 left,
552                 right,
553             }),
554             _ => None,
555         }
556     }
557
558     fn flip(&self) -> Self {
559         Self {
560             op: match self.op {
561                 BinOpKind::Le => BinOpKind::Ge,
562                 BinOpKind::Lt => BinOpKind::Gt,
563                 BinOpKind::Ge => BinOpKind::Le,
564                 BinOpKind::Gt => BinOpKind::Lt,
565                 other => other,
566             },
567             left: self.right,
568             right: self.left,
569         }
570     }
571 }
572
573 /// The clamp meta pattern is a pattern shared between many (but not all) patterns.
574 /// In summary, this pattern consists of two if statements that meet many criteria,
575 /// - binary operators that are one of [`>`, `<`, `>=`, `<=`].
576 /// - Both binary statements must have a shared argument
577 ///     - Which can appear on the left or right side of either statement
578 ///     - The binary operators must define a finite range for the shared argument. To put this in
579 ///       the terms of Rust `std` library, the following ranges are acceptable
580 ///         - `Range`
581 ///         - `RangeInclusive`
582 ///       And all other range types are not accepted. For the purposes of `clamp` it's irrelevant
583 ///       whether the range is inclusive or not, the output is the same.
584 /// - The result of each if statement must be equal to the argument unique to that if statement. The
585 ///   result can not be the shared argument in either case.
586 fn is_clamp_meta_pattern<'tcx>(
587     cx: &LateContext<'tcx>,
588     first_bin: &BinaryOp<'tcx>,
589     second_bin: &BinaryOp<'tcx>,
590     first_expr: &'tcx Expr<'tcx>,
591     second_expr: &'tcx Expr<'tcx>,
592     // This parameters is exclusively for the match pattern.
593     // It exists because the variable bindings used in that pattern
594     // refer to the variable bound in the match arm, not the variable
595     // bound outside of it. Fortunately due to context we know this has to
596     // be the input variable, not the min or max.
597     input_hir_ids: Option<(HirId, HirId)>,
598 ) -> Option<InputMinMax<'tcx>> {
599     fn check<'tcx>(
600         cx: &LateContext<'tcx>,
601         first_bin: &BinaryOp<'tcx>,
602         second_bin: &BinaryOp<'tcx>,
603         first_expr: &'tcx Expr<'tcx>,
604         second_expr: &'tcx Expr<'tcx>,
605         input_hir_ids: Option<(HirId, HirId)>,
606         is_float: bool,
607     ) -> Option<InputMinMax<'tcx>> {
608         match (&first_bin.op, &second_bin.op) {
609             (BinOpKind::Ge | BinOpKind::Gt, BinOpKind::Le | BinOpKind::Lt) => {
610                 let (min, max) = (second_expr, first_expr);
611                 let refers_to_input = match input_hir_ids {
612                     Some((first_hir_id, second_hir_id)) => {
613                         path_to_local_id(peel_blocks(first_bin.left), first_hir_id)
614                             && path_to_local_id(peel_blocks(second_bin.left), second_hir_id)
615                     },
616                     None => eq_expr_value(cx, first_bin.left, second_bin.left),
617                 };
618                 (refers_to_input
619                     && eq_expr_value(cx, first_bin.right, first_expr)
620                     && eq_expr_value(cx, second_bin.right, second_expr))
621                 .then_some(InputMinMax {
622                     input: first_bin.left,
623                     min,
624                     max,
625                     is_float,
626                 })
627             },
628             _ => None,
629         }
630     }
631     // First filter out any expressions with side effects
632     let exprs = [
633         first_bin.left,
634         first_bin.right,
635         second_bin.left,
636         second_bin.right,
637         first_expr,
638         second_expr,
639     ];
640     let clampability = TypeClampability::is_clampable(cx, cx.typeck_results().expr_ty(first_expr))?;
641     let is_float = clampability.is_float();
642     if exprs.iter().any(|e| peel_blocks(e).can_have_side_effects()) {
643         return None;
644     }
645     if !(is_ord_op(first_bin.op) && is_ord_op(second_bin.op)) {
646         return None;
647     }
648     let cases = [
649         (*first_bin, *second_bin),
650         (first_bin.flip(), second_bin.flip()),
651         (first_bin.flip(), *second_bin),
652         (*first_bin, second_bin.flip()),
653     ];
654
655     cases.into_iter().find_map(|(first, second)| {
656         check(cx, &first, &second, first_expr, second_expr, input_hir_ids, is_float).or_else(|| {
657             check(
658                 cx,
659                 &second,
660                 &first,
661                 second_expr,
662                 first_expr,
663                 input_hir_ids.map(|(l, r)| (r, l)),
664                 is_float,
665             )
666         })
667     })
668 }
669
670 fn block_stmt_with_last<'tcx>(block: &'tcx Block<'tcx>) -> impl Iterator<Item = MaybeBorrowedStmtKind<'tcx>> {
671     block
672         .stmts
673         .iter()
674         .map(|s| MaybeBorrowedStmtKind::Borrowed(&s.kind))
675         .chain(
676             block
677                 .expr
678                 .as_ref()
679                 .map(|e| MaybeBorrowedStmtKind::Owned(StmtKind::Expr(e))),
680         )
681 }
682
683 fn is_ord_op(op: BinOpKind) -> bool {
684     matches!(op, BinOpKind::Ge | BinOpKind::Gt | BinOpKind::Le | BinOpKind::Lt)
685 }
686
687 /// Really similar to Cow, but doesn't have a `Clone` requirement.
688 #[derive(Debug)]
689 enum MaybeBorrowedStmtKind<'a> {
690     Borrowed(&'a StmtKind<'a>),
691     Owned(StmtKind<'a>),
692 }
693
694 impl<'a> Clone for MaybeBorrowedStmtKind<'a> {
695     fn clone(&self) -> Self {
696         match self {
697             Self::Borrowed(t) => Self::Borrowed(t),
698             Self::Owned(StmtKind::Expr(e)) => Self::Owned(StmtKind::Expr(e)),
699             Self::Owned(_) => unreachable!("Owned should only ever contain a StmtKind::Expr."),
700         }
701     }
702 }
703
704 impl<'a> Deref for MaybeBorrowedStmtKind<'a> {
705     type Target = StmtKind<'a>;
706
707     fn deref(&self) -> &Self::Target {
708         match self {
709             Self::Borrowed(t) => t,
710             Self::Owned(t) => t,
711         }
712     }
713 }