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.
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, LintContext};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use if_chain::if_chain;
16 use crate::utils::{self, paths, span_lint};
19 /// Checks for the usage of negated comparison operators on types which only implement
20 /// `PartialOrd` (e.g. `f64`).
22 /// **Why is this bad?**
23 /// These operators make it easy to forget that the underlying types actually allow not only three
24 /// potential Orderings (Less, Equal, Greater) but also a fourth one (Uncomparable). This is
25 /// especially easy to miss if the operator based comparison result is negated.
27 /// **Known problems:** None.
32 /// use std::cmp::Ordering;
36 /// let b = std::f64::NAN;
38 /// let _not_less_or_equal = !(a <= b);
42 /// let b = std::f64::NAN;
44 /// let _not_less_or_equal = match a.partial_cmp(&b) {
45 /// None | Some(Ordering::Greater) => true,
49 declare_clippy_lint! {
50 pub NEG_CMP_OP_ON_PARTIAL_ORD,
52 "The use of negated comparison operators on partially ordered types may produce confusing code."
55 pub struct NoNegCompOpForPartialOrd;
57 impl LintPass for NoNegCompOpForPartialOrd {
58 fn get_lints(&self) -> LintArray {
59 lint_array!(NEG_CMP_OP_ON_PARTIAL_ORD)
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd {
65 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
68 if !in_external_macro(cx.sess(), expr.span);
69 if let ExprKind::Unary(UnOp::UnNot, ref inner) = expr.node;
70 if let ExprKind::Binary(ref op, ref left, _) = inner.node;
71 if let BinOpKind::Le | BinOpKind::Ge | BinOpKind::Lt | BinOpKind::Gt = op.node;
75 let ty = cx.tables.expr_ty(left);
77 let implements_ord = {
78 if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) {
79 utils::implements_trait(cx, ty, id, &[])
85 let implements_partial_ord = {
86 if let Some(id) = utils::get_trait_def_id(cx, &paths::PARTIAL_ORD) {
87 utils::implements_trait(cx, ty, id, &[])
93 if implements_partial_ord && !implements_ord {
96 NEG_CMP_OP_ON_PARTIAL_ORD,
98 "The use of negated comparison operators on partially ordered \
99 types produces code that is hard to read and refactor. Please \
100 consider using the `partial_cmp` method instead, to make it \
101 clear that the two values could be incomparable."