1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::ty::implements_trait;
3 use clippy_utils::{self, get_trait_def_id, paths};
4 use if_chain::if_chain;
5 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for the usage of negated comparison operators on types which only implement
13 /// `PartialOrd` (e.g., `f64`).
15 /// ### Why is this bad?
16 /// These operators make it easy to forget that the underlying types actually allow not only three
17 /// potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is
18 /// especially easy to miss if the operator based comparison result is negated.
25 /// let not_less_or_equal = !(a <= b);
30 /// use std::cmp::Ordering;
32 /// # let b = f64::NAN;
34 /// let _not_less_or_equal = match a.partial_cmp(&b) {
35 /// None | Some(Ordering::Greater) => true,
39 #[clippy::version = "pre 1.29.0"]
40 pub NEG_CMP_OP_ON_PARTIAL_ORD,
42 "The use of negated comparison operators on partially ordered types may produce confusing code."
45 declare_lint_pass!(NoNegCompOpForPartialOrd => [NEG_CMP_OP_ON_PARTIAL_ORD]);
47 impl<'tcx> LateLintPass<'tcx> for NoNegCompOpForPartialOrd {
48 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51 if !in_external_macro(cx.sess(), expr.span);
52 if let ExprKind::Unary(UnOp::Not, inner) = expr.kind;
53 if let ExprKind::Binary(ref op, left, _) = inner.kind;
54 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
58 let ty = cx.typeck_results().expr_ty(left);
60 let implements_ord = {
61 if let Some(id) = get_trait_def_id(cx, &paths::ORD) {
62 implements_trait(cx, ty, id, &[])
68 let implements_partial_ord = {
69 if let Some(id) = cx.tcx.lang_items().partial_ord_trait() {
70 implements_trait(cx, ty, id, &[])
76 if implements_partial_ord && !implements_ord {
79 NEG_CMP_OP_ON_PARTIAL_ORD,
81 "the use of negated comparison operators on partially ordered \
82 types produces code that is hard to read and refactor, please \
83 consider using the `partial_cmp` method instead, to make it \
84 clear that the two values could be incomparable"