4 use crate::utils::{self, paths, span_lint, in_external_macro};
7 /// Checks for the usage of negated comparision operators on types which only implement
8 /// `PartialOrd` (e.g. `f64`).
10 /// **Why is this bad?**
11 /// These operators make it easy to forget that the underlying types actually allow not only three
12 /// potential Orderings (Less, Equal, Greater) but also a forth one (Uncomparable). Escpeccially if
13 /// the operator based comparision result is negated it is easy to miss that fact.
15 /// **Known problems:** None.
20 /// use core::cmp::Ordering;
24 /// let b = std::f64::NAN;
26 /// let _not_less_or_equal = !(a <= b);
30 /// let b = std::f64::NAN;
32 /// let _not_less_or_equal = match a.partial_cmp(&b) {
33 /// None | Some(Ordering::Greater) => true,
37 declare_clippy_lint! {
38 pub NEG_CMP_OP_ON_PARTIAL_ORD,
40 "The use of negated comparision operators on partially orded types may produce confusing code."
43 pub struct NoNegCompOpForPartialOrd;
45 impl LintPass for NoNegCompOpForPartialOrd {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(NEG_CMP_OP_ON_PARTIAL_ORD)
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
53 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
56 if !in_external_macro(cx, expr.span);
57 if let Expr_::ExprUnary(UnOp::UnNot, ref inner) = expr.node;
58 if let Expr_::ExprBinary(ref op, ref left, _) = inner.node;
59 if let BinOp_::BiLe | BinOp_::BiGe | BinOp_::BiLt | BinOp_::BiGt = op.node;
63 let ty = cx.tables.expr_ty(left);
65 let implements_ord = {
66 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
67 utils::implements_trait(cx, ty, id, &[])
73 let implements_partial_ord = {
74 if let Some(id) = utils::get_trait_def_id(cx, &paths::PARTIAL_ORD) {
75 utils::implements_trait(cx, ty, id, &[])
81 if implements_partial_ord && !implements_ord {
84 NEG_CMP_OP_ON_PARTIAL_ORD,
86 "The use of negated comparision operators on partially orded \
87 types produces code that is hard to read and refactor. Please \
88 consider to use the `partial_cmp` instead, to make it clear \
89 that the two values could be incomparable."