6 const ORD: [&str; 3] = ["core", "cmp", "Ord"];
7 const PARTIAL_ORD: [&str; 3] = ["core", "cmp", "PartialOrd"];
10 /// Checks for the usage of negated comparision operators on types which only implement
11 /// `PartialOrd` (e.g. `f64`).
13 /// **Why is this bad?**
14 /// These operators make it easy to forget that the underlying types actually allow not only three
15 /// potential Orderings (Less, Equal, Greater) but also a forth one (Uncomparable). Escpeccially if
16 /// the operator based comparision result is negated it is easy to miss that fact.
18 /// **Known problems:** None.
23 /// use core::cmp::Ordering;
27 /// let b = std::f64::NAN;
29 /// let _not_less_or_equal = !(a <= b);
33 /// let b = std::f64::NAN;
35 /// let _not_less_or_equal = match a.partial_cmp(&b) {
36 /// None | Some(Ordering::Greater) => true,
40 declare_clippy_lint! {
41 pub NEG_CMP_OP_ON_PARTIAL_ORD,
43 "The use of negated comparision operators on partially orded types may produce confusing code."
46 pub struct NoNegCompOpForPartialOrd;
48 impl LintPass for NoNegCompOpForPartialOrd {
49 fn get_lints(&self) -> LintArray {
50 lint_array!(NEG_CMP_OP_ON_PARTIAL_ORD)
54 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
56 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
59 if let Expr_::ExprUnary(UnOp::UnNot, ref inner) = expr.node;
60 if let Expr_::ExprBinary(ref op, ref left, _) = inner.node;
61 if let BinOp_::BiLe | BinOp_::BiGe | BinOp_::BiLt | BinOp_::BiGt = op.node;
65 let ty = cx.tables.expr_ty(left);
67 let implements_ord = {
68 if let Some(id) = utils::get_trait_def_id(cx, &ORD) {
69 utils::implements_trait(cx, ty, id, &[])
75 let implements_partial_ord = {
76 if let Some(id) = utils::get_trait_def_id(cx, &PARTIAL_ORD) {
77 utils::implements_trait(cx, ty, id, &[])
83 if implements_partial_ord && !implements_ord {
85 NEG_CMP_OP_ON_PARTIAL_ORD,
87 "The use of negated comparision operators on partially orded \
88 types produces code that is hard to read and refactor. Please \
89 consider to use the `partial_cmp` instead, to make it clear \
90 that the two values could be incomparable."