1 use if_chain::if_chain;
3 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
6 use crate::utils::{self, paths, span_lint};
9 /// Checks for the usage of negated comparison operators on types which only implement
10 /// `PartialOrd` (e.g. `f64`).
12 /// **Why is this bad?**
13 /// These operators make it easy to forget that the underlying types actually allow not only three
14 /// potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is
15 /// especially easy to miss if the operator based comparison result is negated.
17 /// **Known problems:** None.
22 /// use std::cmp::Ordering;
26 /// let b = std::f64::NAN;
28 /// let _not_less_or_equal = !(a <= b);
32 /// let b = std::f64::NAN;
34 /// let _not_less_or_equal = match a.partial_cmp(&b) {
35 /// None | Some(Ordering::Greater) => true,
39 declare_clippy_lint! {
40 pub NEG_CMP_OP_ON_PARTIAL_ORD,
42 "The use of negated comparison operators on partially ordered types may produce confusing code."
45 pub struct NoNegCompOpForPartialOrd;
47 impl LintPass for NoNegCompOpForPartialOrd {
48 fn get_lints(&self) -> LintArray {
49 lint_array!(NEG_CMP_OP_ON_PARTIAL_ORD)
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
54 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
57 if !in_external_macro(cx.sess(), expr.span);
58 if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.node;
59 if let ExprKind::Binary(ref op, ref left, _) = inner.node;
60 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
64 let ty = cx.tables.expr_ty(left);
66 let implements_ord = {
67 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
68 utils::implements_trait(cx, ty, id, &[])
74 let implements_partial_ord = {
75 if let Some(id) = utils::get_trait_def_id(cx, &paths::PARTIAL_ORD) {
76 utils::implements_trait(cx, ty, id, &[])
82 if implements_partial_ord && !implements_ord {
85 NEG_CMP_OP_ON_PARTIAL_ORD,
87 "The use of negated comparison operators on partially ordered \
88 types produces code that is hard to read and refactor. Please \
89 consider using the `partial_cmp` method instead, to make it \
90 clear that the two values could be incomparable."