1 use if_chain::if_chain;
2 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
3 use rustc_lint::{LateContext, LateLintPass, LintContext};
4 use rustc_middle::lint::in_external_macro;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use crate::utils::{self, paths, span_lint};
11 /// Checks for the usage of negated comparison operators on types which only implement
12 /// `PartialOrd` (e.g., `f64`).
14 /// **Why is this bad?**
15 /// These operators make it easy to forget that the underlying types actually allow not only three
16 /// potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is
17 /// especially easy to miss if the operator based comparison result is negated.
19 /// **Known problems:** None.
24 /// use std::cmp::Ordering;
30 /// let _not_less_or_equal = !(a <= b);
36 /// let _not_less_or_equal = match a.partial_cmp(&b) {
37 /// None | Some(Ordering::Greater) => true,
41 pub NEG_CMP_OP_ON_PARTIAL_ORD,
43 "The use of negated comparison operators on partially ordered types may produce confusing code."
46 declare_lint_pass!(NoNegCompOpForPartialOrd => [NEG_CMP_OP_ON_PARTIAL_ORD]);
48 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
49 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
52 if !in_external_macro(cx.sess(), expr.span);
53 if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.kind;
54 if let ExprKind::Binary(ref op, ref left, _) = inner.kind;
55 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
59 let ty = cx.tables.expr_ty(left);
61 let implements_ord = {
62 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
63 utils::implements_trait(cx, ty, id, &[])
69 let implements_partial_ord = {
70 if let Some(id) = cx.tcx.lang_items().partial_ord_trait() {
71 utils::implements_trait(cx, ty, id, &[])
77 if implements_partial_ord && !implements_ord {
80 NEG_CMP_OP_ON_PARTIAL_ORD,
82 "The use of negated comparison operators on partially ordered \
83 types produces code that is hard to read and refactor. Please \
84 consider using the `partial_cmp` method instead, to make it \
85 clear that the two values could be incomparable."