-use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
-use rustc::hir::*;
-use rustc::hir::intravisit::*;
-use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
-use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
-use syntax::util::ThinVec;
-use utils::{in_macro, snippet_opt, span_lint_and_then, SpanlessEq};
+use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
+use crate::rustc::{declare_tool_lint, lint_array};
+use crate::rustc::hir::*;
+use crate::rustc::hir::intravisit::*;
+use crate::syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
+use crate::syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
+use crate::rustc_data_structures::thin_vec::ThinVec;
+use crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
+use crate::rustc_errors::Applicability;
/// **What it does:** Checks for boolean expressions that can be written more
/// concisely.
/// if a && true // should be: if a
/// if !(a == b) // should be: if a != b
/// ```
-declare_lint! {
+declare_clippy_lint! {
pub NONMINIMAL_BOOL,
- Allow,
+ complexity,
"boolean expressions that can be written more concisely"
}
/// if a && b || a { ... }
/// ```
/// The `b` is unnecessary, the expression is equivalent to `if a`.
-declare_lint! {
+declare_clippy_lint! {
pub LOGIC_BUG,
- Warn,
+ correctness,
"boolean expressions that contain terminals which can be eliminated"
}
_: Span,
_: NodeId,
) {
- NonminimalBoolVisitor { cx: cx }.visit_body(body)
+ NonminimalBoolVisitor { cx }.visit_body(body)
}
}
}
impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
- fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
+ fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
for a in a {
- if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
+ if let ExprKind::Binary(binop, ref lhs, ref rhs) = a.node {
if binop.node == op {
v = self.extract(op, &[lhs, rhs], v)?;
continue;
// prevent folding of `cfg!` macros and the like
if !in_macro(e.span) {
match e.node {
- ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
- ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
- BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
- BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
+ ExprKind::Unary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
+ ExprKind::Binary(binop, ref lhs, ref rhs) => match binop.node {
+ BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
+ BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
_ => (),
},
- ExprLit(ref lit) => match lit.node {
+ ExprKind::Lit(ref lit) => match lit.node {
LitKind::Bool(true) => return Ok(Bool::True),
LitKind::Bool(false) => return Ok(Bool::False),
_ => (),
}
for (n, expr) in self.terminals.iter().enumerate() {
if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
- #[allow(cast_possible_truncation)]
+ #[allow(clippy::cast_possible_truncation)]
return Ok(Bool::Term(n as u8));
}
let negated = match e.node {
- ExprBinary(binop, ref lhs, ref rhs) => {
+ ExprKind::Binary(binop, ref lhs, ref rhs) => {
+
+ if !implements_ord(self.cx, lhs) {
+ continue;
+ }
+
let mk_expr = |op| {
Expr {
id: DUMMY_NODE_ID,
hir_id: DUMMY_HIR_ID,
span: DUMMY_SP,
attrs: ThinVec::new(),
- node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
+ node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
}
};
match binop.node {
- BiEq => mk_expr(BiNe),
- BiNe => mk_expr(BiEq),
- BiGt => mk_expr(BiLe),
- BiGe => mk_expr(BiLt),
- BiLt => mk_expr(BiGe),
- BiLe => mk_expr(BiGt),
+ BinOpKind::Eq => mk_expr(BinOpKind::Ne),
+ BinOpKind::Ne => mk_expr(BinOpKind::Eq),
+ BinOpKind::Gt => mk_expr(BinOpKind::Le),
+ BinOpKind::Ge => mk_expr(BinOpKind::Lt),
+ BinOpKind::Lt => mk_expr(BinOpKind::Ge),
+ BinOpKind::Le => mk_expr(BinOpKind::Gt),
_ => continue,
}
},
_ => continue,
};
if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
- #[allow(cast_possible_truncation)]
+ #[allow(clippy::cast_possible_truncation)]
return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
}
}
let n = self.terminals.len();
self.terminals.push(e);
if n < 32 {
- #[allow(cast_possible_truncation)]
+ #[allow(clippy::cast_possible_truncation)]
Ok(Bool::Term(n as u8))
} else {
Err("too many literals".to_owned())
}
impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
- fn snip(&self, e: &Expr) -> String {
- snippet_opt(self.cx, e.span).expect("don't try to improve booleans created by macros")
+ fn snip(&self, e: &Expr) -> Option<String> {
+ snippet_opt(self.cx, e.span)
}
fn simplify_not(&self, expr: &Expr) -> Option<String> {
match expr.node {
- ExprBinary(binop, ref lhs, ref rhs) => {
+ ExprKind::Binary(binop, ref lhs, ref rhs) => {
+
+ if !implements_ord(self.cx, lhs) {
+ return None;
+ }
+
match binop.node {
- BiEq => Some(" != "),
- BiNe => Some(" == "),
- BiLt => Some(" >= "),
- BiGt => Some(" <= "),
- BiLe => Some(" > "),
- BiGe => Some(" < "),
+ BinOpKind::Eq => Some(" != "),
+ BinOpKind::Ne => Some(" == "),
+ BinOpKind::Lt => Some(" >= "),
+ BinOpKind::Gt => Some(" <= "),
+ BinOpKind::Le => Some(" > "),
+ BinOpKind::Ge => Some(" < "),
_ => None,
- }.map(|op| format!("{}{}{}", self.snip(lhs), op, self.snip(rhs)))
+ }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
},
- ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
+ ExprKind::MethodCall(ref path, _, ref args) if args.len() == 1 => {
+ let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
+ if !match_type(self.cx, type_of_receiver, &paths::OPTION) &&
+ !match_type(self.cx, type_of_receiver, &paths::RESULT) {
+ return None;
+ }
METHODS_WITH_NEGATION
.iter().cloned()
.flat_map(|(a, b)| vec![(a, b), (b, a)])
- .find(|&(a, _)| a == path.name.as_str())
- .map(|(_, neg_method)| format!("{}.{}()", self.snip(&args[0]), neg_method))
+ .find(|&(a, _)| a == path.ident.as_str())
+ .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
},
_ => None,
}
}
- fn recurse(&mut self, brackets: bool, suggestion: &Bool) {
+ fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
use quine_mc_cluskey::Bool::*;
match *suggestion {
True => {
Not(ref inner) => match **inner {
And(_) | Or(_) => {
self.output.push('!');
- self.recurse(true, inner)
+ self.output.push('(');
+ self.recurse(inner);
+ self.output.push(')');
},
Term(n) => {
- if let Some(str) = self.simplify_not(self.terminals[n as usize]) {
+ let terminal = self.terminals[n as usize];
+ if let Some(str) = self.simplify_not(terminal) {
self.simplified = true;
self.output.push_str(&str)
} else {
self.output.push('!');
- self.recurse(false, inner)
+ let snip = self.snip(terminal)?;
+ self.output.push_str(&snip);
}
},
True | False | Not(_) => {
self.output.push('!');
- self.recurse(false, inner)
+ self.recurse(inner)?;
},
},
And(ref v) => {
- if brackets {
- self.output.push('(');
- }
for (index, inner) in v.iter().enumerate() {
if index > 0 {
self.output.push_str(" && ");
}
if let Or(_) = *inner {
- self.recurse(true, inner);
+ self.output.push('(');
+ self.recurse(inner);
+ self.output.push(')');
} else {
- self.recurse(false, inner);
+ self.recurse(inner);
}
}
- if brackets {
- self.output.push(')');
- }
},
Or(ref v) => {
- if brackets {
- self.output.push('(');
- }
for (index, inner) in v.iter().enumerate() {
if index > 0 {
self.output.push_str(" || ");
}
- self.recurse(false, inner);
- }
- if brackets {
- self.output.push(')');
+ self.recurse(inner);
}
},
Term(n) => {
- let brackets = brackets && match self.terminals[n as usize].node {
- ExprBinary(..) => true,
- _ => false,
- };
- if brackets {
- self.output.push('(');
- }
- let snip = self.snip(self.terminals[n as usize]);
+ let snip = self.snip(self.terminals[n as usize])?;
self.output.push_str(&snip);
- if brackets {
- self.output.push(')');
- }
},
}
+ Some(())
}
}
// The boolean part of the return indicates whether some simplifications have been applied.
-fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
+fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
let mut suggest_context = SuggestContext {
- terminals: terminals,
- cx: cx,
+ terminals,
+ cx,
output: String::new(),
simplified: false,
};
- suggest_context.recurse(false, suggestion);
+ suggest_context.recurse(suggestion);
(suggest_context.output, suggest_context.simplified)
}
"this expression can be optimized out by applying boolean operations to the \
outer expression",
);
- db.span_suggestion(
+ db.span_suggestion_with_applicability(
e.span,
"it would look like the following",
suggest(self.cx, suggestion, &h2q.terminals).0,
+ Applicability::Unspecified,
);
},
);
return;
}
match e.node {
- ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
- ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
+ ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => self.bool_expr(e),
+ ExprKind::Unary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
self.bool_expr(e);
} else {
walk_expr(self, e);
NestedVisitorMap::None
}
}
+
+
+fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
+ let ty = cx.tables.expr_ty(expr);
+ get_trait_def_id(cx, &paths::ORD)
+ .map_or(false, |id| implements_trait(cx, ty, id, &[]))
+}