1 use if_chain::if_chain;
3 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
6 use crate::utils::{self, paths, span_lint};
10 /// Checks for the usage of negated comparison 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 fourth one (Uncomparable). This is
16 /// especially easy to miss if the operator based comparison result is negated.
18 /// **Known problems:** None.
23 /// use std::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 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<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
48 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
51 if !in_external_macro(cx.sess(), expr.span);
52 if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.kind;
53 if let ExprKind::Binary(ref op, ref left, _) = inner.kind;
54 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
58 let ty = cx.tables.expr_ty(left);
60 let implements_ord = {
61 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
62 utils::implements_trait(cx, ty, id, &[])
68 let implements_partial_ord = {
69 if let Some(id) = utils::get_trait_def_id(cx, &paths::PARTIAL_ORD) {
70 utils::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."