1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
15 use crate::utils::{self, paths, span_lint};
18 /// Checks for the usage of negated comparison operators on types which only implement
19 /// `PartialOrd` (e.g. `f64`).
21 /// **Why is this bad?**
22 /// These operators make it easy to forget that the underlying types actually allow not only three
23 /// potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is
24 /// especially easy to miss if the operator based comparison result is negated.
26 /// **Known problems:** None.
31 /// use std::cmp::Ordering;
35 /// let b = std::f64::NAN;
37 /// let _not_less_or_equal = !(a <= b);
41 /// let b = std::f64::NAN;
43 /// let _not_less_or_equal = match a.partial_cmp(&b) {
44 /// None | Some(Ordering::Greater) => true,
48 declare_clippy_lint! {
49 pub NEG_CMP_OP_ON_PARTIAL_ORD,
51 "The use of negated comparison operators on partially ordered types may produce confusing code."
54 pub struct NoNegCompOpForPartialOrd;
56 impl LintPass for NoNegCompOpForPartialOrd {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(NEG_CMP_OP_ON_PARTIAL_ORD)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
63 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
66 if !in_external_macro(cx.sess(), expr.span);
67 if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.node;
68 if let ExprKind::Binary(ref op, ref left, _) = inner.node;
69 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
73 let ty = cx.tables.expr_ty(left);
75 let implements_ord = {
76 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
77 utils::implements_trait(cx, ty, id, &[])
83 let implements_partial_ord = {
84 if let Some(id) = utils::get_trait_def_id(cx, &paths::PARTIAL_ORD) {
85 utils::implements_trait(cx, ty, id, &[])
91 if implements_partial_ord && !implements_ord {
94 NEG_CMP_OP_ON_PARTIAL_ORD,
96 "The use of negated comparison operators on partially ordered \
97 types produces code that is hard to read and refactor. Please \
98 consider using the `partial_cmp` method instead, to make it \
99 clear that the two values could be incomparable."