1 use itertools::Itertools;
2 use rustc_errors::Diagnostic;
4 def::Res, Arm, BinOpKind, Block, Expr, ExprKind, Guard, HirId, PatKind, PathSegment, PrimTy, QPath, StmtKind,
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};
14 diagnostics::{span_lint_and_then, span_lint_hir_and_then},
15 eq_expr_value, get_trait_def_id,
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,
21 visitors::is_const_evaluatable,
24 use rustc_errors::Applicability;
26 declare_clippy_lint! {
28 /// Identifies good opportunities for a clamp function from std or core, and suggests using it.
30 /// ### Why is this bad?
31 /// clamp is much shorter, easier to read, and doesn't use any control flow.
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`.
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.
43 /// # let (input, min, max) = (0, -2, 1);
46 /// } else if input < min {
55 /// # let (input, min, max) = (0, -2, 1);
56 /// input.max(min).min(max)
61 /// # let (input, min, max) = (0, -2, 1);
63 /// x if x > max => max,
64 /// x if x < min => min,
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; }
78 /// # let (input, min, max) = (0, -2, 1);
79 /// input.clamp(min, max)
82 #[clippy::version = "1.66.0"]
85 "using a clamp pattern instead of the clamp function"
87 impl_lint_pass!(ManualClamp => [MANUAL_CLAMP]);
89 pub struct ManualClamp {
90 msrv: Option<RustcVersion>,
94 pub fn new(msrv: Option<RustcVersion>) -> Self {
100 struct ClampSuggestion<'tcx> {
101 params: InputMinMax<'tcx>,
103 make_assignment: Option<&'tcx Expr<'tcx>>,
104 hir_with_ignore_attr: Option<HirId>,
108 struct InputMinMax<'tcx> {
109 input: &'tcx Expr<'tcx>,
110 min: &'tcx Expr<'tcx>,
111 max: &'tcx Expr<'tcx>,
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) {
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);
132 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) {
133 if !meets_msrv(self.msrv, msrvs::CLAMP) {
136 for suggestion in is_two_if_pattern(cx, block) {
137 emit_suggestion(cx, &suggestion);
140 extract_msrv_attr!(LateContext);
143 fn emit_suggestion<'tcx>(cx: &LateContext<'tcx>, suggestion: &ClampSuggestion<'tcx>) {
144 let ClampSuggestion {
145 params: InputMinMax {
153 hir_with_ignore_attr,
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} = ")
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);
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");
173 d.note("clamp will panic if max < min");
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);
179 span_lint_and_then(cx, MANUAL_CLAMP, *span, msg, lint_builder);
183 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
184 enum TypeClampability {
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)
200 fn is_float(self) -> bool {
201 matches!(self, TypeClampability::Float)
205 /// Targets patterns like
208 /// # let (input, min, max) = (0, -3, 12);
212 /// } else if input > max {
219 fn is_if_elseif_else_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
223 r#else: Some(else_if),
228 r#else: Some(else_body),
229 }) = If::hir(peel_blocks(else_if))
231 let params = is_clamp_meta_pattern(
233 &BinaryOp::new(peel_blocks(cond))?,
234 &BinaryOp::new(peel_blocks(else_if_cond))?,
236 peel_blocks(else_if_then),
239 // Contents of the else should be the resolved input.
240 if !eq_expr_value(cx, params.input, peel_blocks(else_body)) {
243 Some(ClampSuggestion {
246 make_assignment: None,
247 hir_with_ignore_attr: None,
254 /// Targets patterns like
257 /// # let (input, min_value, max_value) = (0, -3, 12);
259 /// input.max(min_value).min(max_value)
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))
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),
274 Some(ClampSuggestion {
275 params: InputMinMax { input, min, max, is_float },
277 make_assignment: None,
278 hir_with_ignore_attr: None,
285 /// Targets patterns like
288 /// # let (input, min_value, max_value) = (0, -3, 12);
289 /// # use std::cmp::{max, min};
290 /// min(max(input, min_value), max_value)
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>> {
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")))
307 ExprKind::Path(QPath::TypeRelative(ty, seg)) => {
308 matches!(path_res(cx, ty), Res::PrimTy(PrimTy::Float(_))).then(|| FunctionType::OrdOrFloat(seg))
314 enum FunctionType<'tcx> {
317 OrdOrFloat(&'tcx PathSegment<'tcx>),
321 cx: &LateContext<'tcx>,
322 outer_fn: &'tcx Expr<'tcx>,
323 inner_call: &'tcx Expr<'tcx>,
324 outer_arg: &'tcx Expr<'tcx>,
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)
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),
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),
349 Some(ClampSuggestion {
350 params: InputMinMax { input, min, max, is_float },
352 make_assignment: None,
353 hir_with_ignore_attr: None,
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))
367 /// Targets patterns like
370 /// # let (input, min, max) = (0, -3, 12);
373 /// input if input > max => max,
374 /// input if input < min => min,
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))
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()
402 if let Some(params) = is_clamp_meta_pattern(
408 Some((*first_hir_id, *second_hir_id)),
410 return Some(ClampSuggestion {
411 params: InputMinMax {
415 is_float: params.is_float,
418 make_assignment: None,
419 hir_with_ignore_attr: None,
426 /// Targets patterns like
429 /// # let (input, min, max) = (0, -3, 12);
431 /// let mut x = input;
432 /// if x < min { x = min; }
433 /// if x > max { x = max; }
435 fn is_two_if_pattern<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) -> Vec<ClampSuggestion<'tcx>> {
436 block_stmt_with_last(block)
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,
447 ) = peel_blocks_with_stmt(first_then).kind
448 && let ExprKind::Assign(
449 maybe_input_second_path,
450 maybe_min_max_second,
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(
461 maybe_min_max_second,
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,
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()),
483 /// Targets patterns like
486 /// # let (mut input, min, max) = (0, -3, 12);
490 /// } else if input > max {
494 fn is_if_elseif_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<ClampSuggestion<'tcx>> {
498 r#else: Some(else_if),
504 }) = If::hir(peel_blocks(else_if))
505 && let ExprKind::Assign(
506 maybe_input_first_path,
509 ) = peel_blocks_with_stmt(then).kind
510 && let ExprKind::Assign(
511 maybe_input_second_path,
512 maybe_min_max_second,
514 ) = peel_blocks_with_stmt(else_if_then).kind
516 let params = is_clamp_meta_pattern(
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),
524 if !eq_expr_value(cx, maybe_input_first_path, maybe_input_second_path) {
527 Some(ClampSuggestion {
530 make_assignment: Some(maybe_input_first_path),
531 hir_with_ignore_attr: None,
538 /// `ExprKind::Binary` but more narrowly typed
539 #[derive(Debug, Clone, Copy)]
540 struct BinaryOp<'tcx> {
542 left: &'tcx Expr<'tcx>,
543 right: &'tcx Expr<'tcx>,
546 impl<'tcx> BinaryOp<'tcx> {
547 fn new(e: &'tcx Expr<'tcx>) -> Option<BinaryOp<'tcx>> {
549 ExprKind::Binary(op, left, right) => Some(BinaryOp {
558 fn flip(&self) -> Self {
561 BinOpKind::Le => BinOpKind::Ge,
562 BinOpKind::Lt => BinOpKind::Gt,
563 BinOpKind::Ge => BinOpKind::Le,
564 BinOpKind::Gt => BinOpKind::Lt,
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
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>> {
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)>,
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)
616 None => eq_expr_value(cx, first_bin.left, second_bin.left),
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,
631 // First filter out any expressions with side effects
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()) {
645 if !(is_ord_op(first_bin.op) && is_ord_op(second_bin.op)) {
649 (*first_bin, *second_bin),
650 (first_bin.flip(), second_bin.flip()),
651 (first_bin.flip(), *second_bin),
652 (*first_bin, second_bin.flip()),
655 cases.into_iter().find_map(|(first, second)| {
656 check(cx, &first, &second, first_expr, second_expr, input_hir_ids, is_float).or_else(|| {
663 input_hir_ids.map(|(l, r)| (r, l)),
670 fn block_stmt_with_last<'tcx>(block: &'tcx Block<'tcx>) -> impl Iterator<Item = MaybeBorrowedStmtKind<'tcx>> {
674 .map(|s| MaybeBorrowedStmtKind::Borrowed(&s.kind))
679 .map(|e| MaybeBorrowedStmtKind::Owned(StmtKind::Expr(e))),
683 fn is_ord_op(op: BinOpKind) -> bool {
684 matches!(op, BinOpKind::Ge | BinOpKind::Gt | BinOpKind::Le | BinOpKind::Lt)
687 /// Really similar to Cow, but doesn't have a `Clone` requirement.
689 enum MaybeBorrowedStmtKind<'a> {
690 Borrowed(&'a StmtKind<'a>),
694 impl<'a> Clone for MaybeBorrowedStmtKind<'a> {
695 fn clone(&self) -> 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."),
704 impl<'a> Deref for MaybeBorrowedStmtKind<'a> {
705 type Target = StmtKind<'a>;
707 fn deref(&self) -> &Self::Target {
709 Self::Borrowed(t) => t,