1
Fork 0

Run nightly rustfmt

This commit is contained in:
Oliver Schneider 2017-09-05 11:33:04 +02:00
parent c710ac839f
commit e4524ac4de
No known key found for this signature in database
GPG key ID: A69F8D225B3AD7D9
99 changed files with 1792 additions and 2049 deletions

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use std::f64::consts as f64; use std::f64::consts as f64;
use syntax::ast::{Lit, LitKind, FloatTy}; use syntax::ast::{FloatTy, Lit, LitKind};
use syntax::symbol; use syntax::symbol;
use utils::span_lint; use utils::span_lint;

View file

@ -55,8 +55,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic {
match expr.node { match expr.node {
hir::ExprBinary(ref op, ref l, ref r) => { hir::ExprBinary(ref op, ref l, ref r) => {
match op.node { match op.node {
hir::BiAnd | hir::BiOr | hir::BiBitAnd | hir::BiBitOr | hir::BiBitXor | hir::BiShl | hir::BiAnd |
hir::BiShr | hir::BiEq | hir::BiLt | hir::BiLe | hir::BiNe | hir::BiGe | hir::BiGt => return, hir::BiOr |
hir::BiBitAnd |
hir::BiBitOr |
hir::BiBitXor |
hir::BiShl |
hir::BiShr |
hir::BiEq |
hir::BiLt |
hir::BiLe |
hir::BiNe |
hir::BiGe |
hir::BiGt => return,
_ => (), _ => (),
} }
let (l_ty, r_ty) = (cx.tables.expr_ty(l), cx.tables.expr_ty(r)); let (l_ty, r_ty) = (cx.tables.expr_ty(l), cx.tables.expr_ty(r));

View file

@ -3,7 +3,7 @@ use rustc::middle::const_val::ConstVal;
use rustc::ty; use rustc::ty;
use rustc::ty::subst::Substs; use rustc::ty::subst::Substs;
use rustc_const_eval::ConstContext; use rustc_const_eval::ConstContext;
use rustc_const_math::{ConstUsize, ConstIsize, ConstInt}; use rustc_const_math::{ConstInt, ConstIsize, ConstUsize};
use rustc::hir; use rustc::hir;
use syntax::ast::RangeLimits; use syntax::ast::RangeLimits;
use utils::{self, higher}; use utils::{self, higher};
@ -124,8 +124,7 @@ fn to_const_range(
}; };
let end = match *end { let end = match *end {
Some(Some(ConstVal::Integral(x))) => { Some(Some(ConstVal::Integral(x))) => if limits == RangeLimits::Closed {
if limits == RangeLimits::Closed {
match x { match x {
ConstInt::U8(_) => (x + ConstInt::U8(1)), ConstInt::U8(_) => (x + ConstInt::U8(1)),
ConstInt::U16(_) => (x + ConstInt::U16(1)), ConstInt::U16(_) => (x + ConstInt::U16(1)),
@ -146,7 +145,6 @@ fn to_const_range(
}.expect("such a big array is not realistic") }.expect("such a big array is not realistic")
} else { } else {
x x
}
}, },
Some(_) => return None, Some(_) => return None,
None => array_size, None => array_size,

View file

@ -1,7 +1,7 @@
use rustc::hir; use rustc::hir;
use rustc::lint::*; use rustc::lint::*;
use syntax::ast; use syntax::ast;
use utils::{span_lint_and_then, snippet_opt, SpanlessEq, get_trait_def_id, implements_trait}; use utils::{get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, SpanlessEq};
use utils::{higher, sugg}; use utils::{higher, sugg};
/// **What it does:** Checks for compound assignment operations (`+=` and /// **What it does:** Checks for compound assignment operations (`+=` and
@ -88,19 +88,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
if let hir::ExprBinary(binop, ref l, ref r) = rhs.node { if let hir::ExprBinary(binop, ref l, ref r) = rhs.node {
if op.node == binop.node { if op.node == binop.node {
let lint = |assignee: &hir::Expr, rhs: &hir::Expr| { let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
span_lint_and_then(cx, span_lint_and_then(
cx,
MISREFACTORED_ASSIGN_OP, MISREFACTORED_ASSIGN_OP,
expr.span, expr.span,
"variable appears on both sides of an assignment operation", "variable appears on both sides of an assignment operation",
|db| if let (Some(snip_a), Some(snip_r)) = |db| if let (Some(snip_a), Some(snip_r)) =
(snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) { (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
db.span_suggestion(expr.span, {
db.span_suggestion(
expr.span,
"replace it with", "replace it with",
format!("{} {}= {}", format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
snip_a, );
op.node.as_str(), },
snip_r)); );
});
}; };
// lhs op= l op r // lhs op= l op r
if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) { if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
@ -167,8 +169,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
BitXor: BiBitXor, BitXor: BiBitXor,
Shr: BiShr, Shr: BiShr,
Shl: BiShl Shl: BiShl
) ) {
{
span_lint_and_then( span_lint_and_then(
cx, cx,
ASSIGN_OP_PATTERN, ASSIGN_OP_PATTERN,
@ -193,7 +194,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
// a = b commutative_op a // a = b commutative_op a
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) { if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
match op.node { match op.node {
hir::BiAdd | hir::BiMul | hir::BiAnd | hir::BiOr | hir::BiBitXor | hir::BiBitAnd | hir::BiAdd |
hir::BiMul |
hir::BiAnd |
hir::BiOr |
hir::BiBitXor |
hir::BiBitAnd |
hir::BiBitOr => { hir::BiBitOr => {
lint(assignee, l); lint(assignee, l);
}, },

View file

@ -7,7 +7,7 @@ use rustc::ty::{self, TyCtxt};
use semver::Version; use semver::Version;
use syntax::ast::{Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind}; use syntax::ast::{Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{in_macro, match_def_path, paths, span_lint, span_lint_and_then, snippet_opt}; use utils::{in_macro, match_def_path, paths, snippet_opt, span_lint, span_lint_and_then};
/// **What it does:** Checks for items annotated with `#[inline(always)]`, /// **What it does:** Checks for items annotated with `#[inline(always)]`,
/// unless the annotated function is empty or simply panics. /// unless the annotated function is empty or simply panics.
@ -110,8 +110,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
check_attrs(cx, item.span, &item.name, &item.attrs) check_attrs(cx, item.span, &item.name, &item.attrs)
} }
match item.node { match item.node {
ItemExternCrate(_) | ItemExternCrate(_) | ItemUse(_, _) => {
ItemUse(_, _) => {
for attr in &item.attrs { for attr in &item.attrs {
if let Some(ref lint_list) = attr.meta_item_list() { if let Some(ref lint_list) = attr.meta_item_list() {
if let Some(name) = attr.name() { if let Some(name) = attr.name() {
@ -196,14 +195,13 @@ fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> b
if let Some(stmt) = block.stmts.first() { if let Some(stmt) = block.stmts.first() {
match stmt.node { match stmt.node {
StmtDecl(_, _) => true, StmtDecl(_, _) => true,
StmtExpr(ref expr, _) | StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
} }
} else { } else {
block.expr.as_ref().map_or( block
false, .expr
|e| is_relevant_expr(tcx, tables, e), .as_ref()
) .map_or(false, |e| is_relevant_expr(tcx, tables, e))
} }
} }
@ -211,15 +209,12 @@ fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool
match expr.node { match expr.node {
ExprBlock(ref block) => is_relevant_block(tcx, tables, block), ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e), ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
ExprRet(None) | ExprRet(None) | ExprBreak(_, None) => false,
ExprBreak(_, None) => false, ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
ExprCall(ref path_expr, _) => {
if let ExprPath(ref qpath) = path_expr.node {
let fun_id = tables.qpath_def(qpath, path_expr.hir_id).def_id(); let fun_id = tables.qpath_def(qpath, path_expr.hir_id).def_id();
!match_def_path(tcx, fun_id, &paths::BEGIN_PANIC) !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
} else { } else {
true true
}
}, },
_ => true, _ => true,
} }

View file

@ -158,10 +158,8 @@ fn check_compare(cx: &LateContext, bit_op: &Expr, cmp_op: BinOp_, cmp_value: u12
fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value: u128, cmp_value: u128, span: &Span) { fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value: u128, cmp_value: u128, span: &Span) {
match cmp_op { match cmp_op {
BiEq | BiNe => { BiEq | BiNe => match bit_op {
match bit_op { BiBitAnd => if mask_value & cmp_value != cmp_value {
BiBitAnd => {
if mask_value & cmp_value != cmp_value {
if cmp_value != 0 { if cmp_value != 0 {
span_lint( span_lint(
cx, cx,
@ -176,10 +174,8 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
} }
} else if mask_value == 0 { } else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero"); span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
}, },
BiBitOr => { BiBitOr => if mask_value | cmp_value != cmp_value {
if mask_value | cmp_value != cmp_value {
span_lint( span_lint(
cx, cx,
BAD_BIT_MASK, BAD_BIT_MASK,
@ -190,15 +186,11 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
cmp_value cmp_value
), ),
); );
}
}, },
_ => (), _ => (),
}
}, },
BiLt | BiGe => { BiLt | BiGe => match bit_op {
match bit_op { BiBitAnd => if mask_value < cmp_value {
BiBitAnd => {
if mask_value < cmp_value {
span_lint( span_lint(
cx, cx,
BAD_BIT_MASK, BAD_BIT_MASK,
@ -211,10 +203,8 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
); );
} else if mask_value == 0 { } else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero"); span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
}, },
BiBitOr => { BiBitOr => if mask_value >= cmp_value {
if mask_value >= cmp_value {
span_lint( span_lint(
cx, cx,
BAD_BIT_MASK, BAD_BIT_MASK,
@ -227,16 +217,12 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
); );
} else { } else {
check_ineffective_lt(cx, *span, mask_value, cmp_value, "|"); check_ineffective_lt(cx, *span, mask_value, cmp_value, "|");
}
}, },
BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"), BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"),
_ => (), _ => (),
}
}, },
BiLe | BiGt => { BiLe | BiGt => match bit_op {
match bit_op { BiBitAnd => if mask_value <= cmp_value {
BiBitAnd => {
if mask_value <= cmp_value {
span_lint( span_lint(
cx, cx,
BAD_BIT_MASK, BAD_BIT_MASK,
@ -249,10 +235,8 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
); );
} else if mask_value == 0 { } else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero"); span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
}, },
BiBitOr => { BiBitOr => if mask_value > cmp_value {
if mask_value > cmp_value {
span_lint( span_lint(
cx, cx,
BAD_BIT_MASK, BAD_BIT_MASK,
@ -265,11 +249,9 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
); );
} else { } else {
check_ineffective_gt(cx, *span, mask_value, cmp_value, "|"); check_ineffective_gt(cx, *span, mask_value, cmp_value, "|");
}
}, },
BiBitXor => check_ineffective_gt(cx, *span, mask_value, cmp_value, "^"), BiBitXor => check_ineffective_gt(cx, *span, mask_value, cmp_value, "^"),
_ => (), _ => (),
}
}, },
_ => (), _ => (),
} }

View file

@ -27,7 +27,9 @@ pub struct BlackListedName {
impl BlackListedName { impl BlackListedName {
pub fn new(blacklist: Vec<String>) -> Self { pub fn new(blacklist: Vec<String>) -> Self {
Self { blacklist: blacklist } Self {
blacklist: blacklist,
}
} }
} }

View file

@ -1,6 +1,6 @@
use rustc::lint::{LateLintPass, LateContext, LintArray, LintPass}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use utils::*; use utils::*;
/// **What it does:** Checks for `if` conditions that use blocks to contain an /// **What it does:** Checks for `if` conditions that use blocks to contain an
@ -98,10 +98,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BlockInIfCondition {
); );
} }
} else { } else {
let span = block.expr.as_ref().map_or_else( let span = block
|| block.stmts[0].span, .expr
|e| e.span, .as_ref()
); .map_or_else(|| block.stmts[0].span, |e| e.span);
if in_macro(span) || differing_macro_contexts(expr.span, span) { if in_macro(span) || differing_macro_contexts(expr.span, span) {
return; return;
} }

View file

@ -1,10 +1,10 @@
use rustc::lint::{LintArray, LateLintPass, LateContext, LintPass}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::*; use rustc::hir::intravisit::*;
use syntax::ast::{LitKind, DUMMY_NODE_ID, NodeId}; use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
use syntax::codemap::{DUMMY_SP, dummy_spanned, Span}; use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
use syntax::util::ThinVec; use syntax::util::ThinVec;
use utils::{span_lint_and_then, in_macro, snippet_opt, SpanlessEq}; use utils::{in_macro, snippet_opt, span_lint_and_then, SpanlessEq};
/// **What it does:** Checks for boolean expressions that can be written more /// **What it does:** Checks for boolean expressions that can be written more
/// concisely. /// concisely.
@ -96,26 +96,23 @@ impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
if !in_macro(e.span) { if !in_macro(e.span) {
match e.node { match e.node {
ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)), ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
ExprBinary(binop, ref lhs, ref rhs) => { ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
match binop.node {
BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)), BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)), BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
_ => (), _ => (),
}
}, },
ExprLit(ref lit) => { ExprLit(ref lit) => match lit.node {
match lit.node {
LitKind::Bool(true) => return Ok(Bool::True), LitKind::Bool(true) => return Ok(Bool::True),
LitKind::Bool(false) => return Ok(Bool::False), LitKind::Bool(false) => return Ok(Bool::False),
_ => (), _ => (),
}
}, },
_ => (), _ => (),
} }
} }
for (n, expr) in self.terminals.iter().enumerate() { for (n, expr) in self.terminals.iter().enumerate() {
if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) { if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
#[allow(cast_possible_truncation)] return Ok(Bool::Term(n as u8)); #[allow(cast_possible_truncation)]
return Ok(Bool::Term(n as u8));
} }
let negated = match e.node { let negated = match e.node {
ExprBinary(binop, ref lhs, ref rhs) => { ExprBinary(binop, ref lhs, ref rhs) => {
@ -141,13 +138,15 @@ impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
_ => continue, _ => continue,
}; };
if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) { if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
#[allow(cast_possible_truncation)] return Ok(Bool::Not(Box::new(Bool::Term(n as u8)))); #[allow(cast_possible_truncation)]
return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
} }
} }
let n = self.terminals.len(); let n = self.terminals.len();
self.terminals.push(e); self.terminals.push(e);
if n < 32 { if n < 32 {
#[allow(cast_possible_truncation)] Ok(Bool::Term(n as u8)) #[allow(cast_possible_truncation)]
Ok(Bool::Term(n as u8))
} else { } else {
Err("too many literals".to_owned()) Err("too many literals".to_owned())
} }
@ -167,14 +166,12 @@ fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
s.push_str("false"); s.push_str("false");
s s
}, },
Not(ref inner) => { Not(ref inner) => match **inner {
match **inner {
And(_) | Or(_) => { And(_) | Or(_) => {
s.push('!'); s.push('!');
recurse(true, cx, inner, terminals, s) recurse(true, cx, inner, terminals, s)
}, },
Term(n) => { Term(n) => if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
let op = match binop.node { let op = match binop.node {
BiEq => " != ", BiEq => " != ",
BiNe => " == ", BiNe => " == ",
@ -194,13 +191,11 @@ fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
} else { } else {
s.push('!'); s.push('!');
recurse(false, cx, inner, terminals, s) recurse(false, cx, inner, terminals, s)
}
}, },
_ => { _ => {
s.push('!'); s.push('!');
recurse(false, cx, inner, terminals, s) recurse(false, cx, inner, terminals, s)
}, },
}
}, },
And(ref v) => { And(ref v) => {
if brackets { if brackets {
@ -319,7 +314,6 @@ impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
cx: self.cx, cx: self.cx,
}; };
if let Ok(expr) = h2q.run(e) { if let Ok(expr) = h2q.run(e) {
if h2q.terminals.len() > 8 { if h2q.terminals.len() > 8 {
// QMC has exponentially slow behavior as the number of terminals increases // QMC has exponentially slow behavior as the number of terminals increases
// 8 is reasonable, it takes approximately 0.2 seconds. // 8 is reasonable, it takes approximately 0.2 seconds.
@ -411,12 +405,10 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
} }
match e.node { match e.node {
ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e), ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
ExprUnary(UnNot, ref inner) => { ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
if self.cx.tables.node_types()[inner.hir_id].is_bool() {
self.bool_expr(e); self.bool_expr(e);
} else { } else {
walk_expr(self, e); walk_expr(self, e);
}
}, },
_ => walk_expr(self, e), _ => walk_expr(self, e),
} }

View file

@ -97,23 +97,18 @@ fn get_pat_name(pat: &Pat) -> Option<Name> {
match pat.node { match pat.node {
PatKind::Binding(_, _, ref spname, _) => Some(spname.node), PatKind::Binding(_, _, ref spname, _) => Some(spname.node),
PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.name), PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
PatKind::Box(ref p) | PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
PatKind::Ref(ref p, _) => get_pat_name(&*p),
_ => None, _ => None,
} }
} }
fn get_path_name(expr: &Expr) -> Option<Name> { fn get_path_name(expr: &Expr) -> Option<Name> {
match expr.node { match expr.node {
ExprBox(ref e) | ExprBox(ref e) | ExprAddrOf(_, ref e) | ExprUnary(UnOp::UnDeref, ref e) => get_path_name(e),
ExprAddrOf(_, ref e) | ExprBlock(ref b) => if b.stmts.is_empty() {
ExprUnary(UnOp::UnDeref, ref e) => get_path_name(e),
ExprBlock(ref b) => {
if b.stmts.is_empty() {
b.expr.as_ref().and_then(|p| get_path_name(p)) b.expr.as_ref().and_then(|p| get_path_name(p))
} else { } else {
None None
}
}, },
ExprPath(ref qpath) => single_segment_path(qpath).map(|ps| ps.name), ExprPath(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
_ => None, _ => None,

View file

@ -15,7 +15,7 @@
use rustc::lint::*; use rustc::lint::*;
use syntax::ast; use syntax::ast;
use utils::{in_macro, snippet_block, span_lint_and_then, span_lint_and_sugg}; use utils::{in_macro, snippet_block, span_lint_and_sugg, span_lint_and_then};
use utils::sugg::Sugg; use utils::sugg::Sugg;
/// **What it does:** Checks for nested `if` statements which can be collapsed /// **What it does:** Checks for nested `if` statements which can be collapsed
@ -87,12 +87,10 @@ impl EarlyLintPass for CollapsibleIf {
fn check_if(cx: &EarlyContext, expr: &ast::Expr) { fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
match expr.node { match expr.node {
ast::ExprKind::If(ref check, ref then, ref else_) => { ast::ExprKind::If(ref check, ref then, ref else_) => if let Some(ref else_) = *else_ {
if let Some(ref else_) = *else_ {
check_collapsible_maybe_if_let(cx, else_); check_collapsible_maybe_if_let(cx, else_);
} else { } else {
check_collapsible_no_if_let(cx, expr, check, then); check_collapsible_no_if_let(cx, expr, check, then);
}
}, },
ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => { ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
check_collapsible_maybe_if_let(cx, else_); check_collapsible_maybe_if_let(cx, else_);
@ -147,8 +145,7 @@ fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
if let (Some(stmt), None) = (it.next(), it.next()) { if let (Some(stmt), None) = (it.next(), it.next()) {
match stmt.node { match stmt.node {
ast::StmtKind::Expr(ref expr) | ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
ast::StmtKind::Semi(ref expr) => Some(expr),
_ => None, _ => None,
} }
} else { } else {

View file

@ -5,8 +5,8 @@ use rustc::hir::def::Def;
use rustc_const_eval::lookup_const_by_id; use rustc_const_eval::lookup_const_by_id;
use rustc_const_math::ConstInt; use rustc_const_math::ConstInt;
use rustc::hir::*; use rustc::hir::*;
use rustc::ty::{self, TyCtxt, Ty}; use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::{Substs, Subst}; use rustc::ty::subst::{Subst, Substs};
use std::cmp::Ordering::{self, Equal}; use std::cmp::Ordering::{self, Equal};
use std::cmp::PartialOrd; use std::cmp::PartialOrd;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
@ -76,7 +76,7 @@ impl PartialEq for Constant {
(&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r, (&Constant::Vec(ref l), &Constant::Vec(ref r)) => l == r,
(&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv, (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => ls == rs && lv == rv,
(&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r, (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) => l == r,
_ => false, //TODO: Are there inter-type equalities? _ => false, // TODO: Are there inter-type equalities?
} }
} }
} }
@ -110,8 +110,7 @@ impl Hash for Constant {
Constant::Bool(b) => { Constant::Bool(b) => {
b.hash(state); b.hash(state);
}, },
Constant::Vec(ref v) | Constant::Vec(ref v) | Constant::Tuple(ref v) => {
Constant::Tuple(ref v) => {
v.hash(state); v.hash(state);
}, },
Constant::Repeat(ref c, l) => { Constant::Repeat(ref c, l) => {
@ -125,12 +124,10 @@ impl Hash for Constant {
impl PartialOrd for Constant { impl PartialOrd for Constant {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) { match (self, other) {
(&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => { (&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => if l_sty == r_sty {
if l_sty == r_sty {
Some(ls.cmp(rs)) Some(ls.cmp(rs))
} else { } else {
None None
}
}, },
(&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)), (&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
(&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)), (&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
@ -147,15 +144,14 @@ impl PartialOrd for Constant {
} }
}, },
(&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)), (&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
(&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
(&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r), l.partial_cmp(r)
(&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => { },
match lv.partial_cmp(rv) { (&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
Some(Equal) => Some(ls.cmp(rs)), Some(Equal) => Some(ls.cmp(rs)),
x => x, x => x,
}
}, },
_ => None, //TODO: Are there any useful inter-type orderings? _ => None, // TODO: Are there any useful inter-type orderings?
} }
} }
} }
@ -177,18 +173,14 @@ pub fn lit_to_constant<'a, 'tcx>(lit: &LitKind, tcx: TyCtxt<'a, 'tcx, 'tcx>, mut
LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)), LitKind::Byte(b) => Constant::Int(ConstInt::U8(b)),
LitKind::ByteStr(ref s) => Constant::Binary(s.clone()), LitKind::ByteStr(ref s) => Constant::Binary(s.clone()),
LitKind::Char(c) => Constant::Char(c), LitKind::Char(c) => Constant::Char(c),
LitKind::Int(n, hint) => { LitKind::Int(n, hint) => match (&ty.sty, hint) {
match (&ty.sty, hint) { (&ty::TyInt(ity), _) | (_, Signed(ity)) => {
(&ty::TyInt(ity), _) |
(_, Signed(ity)) => {
Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.int_type)) Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.int_type))
}, },
(&ty::TyUint(uty), _) | (&ty::TyUint(uty), _) | (_, Unsigned(uty)) => {
(_, Unsigned(uty)) => {
Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type)) Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type))
}, },
_ => bug!(), _ => bug!(),
}
}, },
LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()), LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any), LitKind::FloatUnsuffixed(ref is) => Constant::Float(is.to_string(), FloatWidth::Any),
@ -262,13 +254,11 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
}; };
self.expr(value).map(|v| Constant::Repeat(Box::new(v), n)) self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
}, },
ExprUnary(op, ref operand) => { ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
self.expr(operand).and_then(|o| match op {
UnNot => constant_not(&o), UnNot => constant_not(&o),
UnNeg => constant_negate(o), UnNeg => constant_negate(o),
UnDeref => Some(o), UnDeref => Some(o),
}) }),
},
ExprBinary(op, ref left, ref right) => self.binop(op, left, right), ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
// TODO: add other expressions // TODO: add other expressions
_ => None, _ => None,
@ -287,8 +277,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> { fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
let def = self.tables.qpath_def(qpath, id); let def = self.tables.qpath_def(qpath, id);
match def { match def {
Def::Const(def_id) | Def::Const(def_id) | Def::AssociatedConst(def_id) => {
Def::AssociatedConst(def_id) => {
let substs = self.tables.node_substs(id); let substs = self.tables.node_substs(id);
let substs = if self.substs.is_empty() { let substs = if self.substs.is_empty() {
substs substs
@ -358,8 +347,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
(BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int), (BiRem, Constant::Int(l), Some(Constant::Int(r))) => (l % r).ok().map(Constant::Int),
(BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)), (BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
(BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)), (BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
(BiAnd, Constant::Bool(true), Some(r)) | (BiAnd, Constant::Bool(true), Some(r)) | (BiOr, Constant::Bool(false), Some(r)) => Some(r),
(BiOr, Constant::Bool(false), Some(r)) => Some(r),
(BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)), (BiBitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
(BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int), (BiBitXor, Constant::Int(l), Some(Constant::Int(r))) => (l ^ r).ok().map(Constant::Int),
(BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)), (BiBitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),

View file

@ -6,7 +6,7 @@ use std::collections::hash_map::Entry;
use syntax::symbol::InternedString; use syntax::symbol::InternedString;
use syntax::util::small_vector::SmallVector; use syntax::util::small_vector::SmallVector;
use utils::{SpanlessEq, SpanlessHash}; use utils::{SpanlessEq, SpanlessHash};
use utils::{get_parent_expr, in_macro, span_lint_and_then, span_note_and_lint, snippet}; use utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
/// **What it does:** Checks for consecutive `if`s with the same condition. /// **What it does:** Checks for consecutive `if`s with the same condition.
/// ///
@ -114,7 +114,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if !in_macro(expr.span) { if !in_macro(expr.span) {
// skip ifs directly in else, it will be checked in the parent if // skip ifs directly in else, it will be checked in the parent if
if let Some(&Expr { node: ExprIf(_, _, Some(ref else_expr)), .. }) = get_parent_expr(cx, expr) { if let Some(&Expr {
node: ExprIf(_, _, Some(ref else_expr)),
..
}) = get_parent_expr(cx, expr)
{
if else_expr.id == expr.id { if else_expr.id == expr.id {
return; return;
} }
@ -267,12 +271,9 @@ fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, Ty<'tcx>> { fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, Ty<'tcx>> {
fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, Ty<'tcx>>) { fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, Ty<'tcx>>) {
match pat.node { match pat.node {
PatKind::Box(ref pat) | PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map), PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
PatKind::TupleStruct(_, ref pats, _) => {
for pat in pats {
bindings_impl(cx, pat, map); bindings_impl(cx, pat, map);
}
}, },
PatKind::Binding(_, _, ref ident, ref as_pat) => { PatKind::Binding(_, _, ref ident, ref as_pat) => {
if let Entry::Vacant(v) = map.entry(ident.node.as_str()) { if let Entry::Vacant(v) = map.entry(ident.node.as_str()) {
@ -282,15 +283,11 @@ fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<Interned
bindings_impl(cx, as_pat, map); bindings_impl(cx, as_pat, map);
} }
}, },
PatKind::Struct(_, ref fields, _) => { PatKind::Struct(_, ref fields, _) => for pat in fields {
for pat in fields {
bindings_impl(cx, &pat.node.pat, map); bindings_impl(cx, &pat.node.pat, map);
}
}, },
PatKind::Tuple(ref fields, _) => { PatKind::Tuple(ref fields, _) => for pat in fields {
for pat in fields {
bindings_impl(cx, pat, map); bindings_impl(cx, pat, map);
}
}, },
PatKind::Slice(ref lhs, ref mid, ref rhs) => { PatKind::Slice(ref lhs, ref mid, ref rhs) => {
for pat in lhs { for pat in lhs {
@ -303,10 +300,7 @@ fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<Interned
bindings_impl(cx, pat, map); bindings_impl(cx, pat, map);
} }
}, },
PatKind::Lit(..) | PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
PatKind::Range(..) |
PatKind::Wild |
PatKind::Path(..) => (),
} }
} }
@ -335,12 +329,10 @@ where
for expr in exprs { for expr in exprs {
match map.entry(hash(expr)) { match map.entry(hash(expr)) {
Entry::Occupied(o) => { Entry::Occupied(o) => for o in o.get() {
for o in o.get() {
if eq(o, expr) { if eq(o, expr) {
return Some((o, expr)); return Some((o, expr));
} }
}
}, },
Entry::Vacant(v) => { Entry::Vacant(v) => {
v.insert(vec![expr]); v.insert(vec![expr]);

View file

@ -4,11 +4,11 @@ use rustc::cfg::CFG;
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::ty; use rustc::ty;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use syntax::ast::{Attribute, NodeId}; use syntax::ast::{Attribute, NodeId};
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{in_macro, LimitStack, span_help_and_lint, paths, match_type, is_allowed}; use utils::{in_macro, is_allowed, match_type, paths, span_help_and_lint, LimitStack};
/// **What it does:** Checks for methods with high cyclomatic complexity. /// **What it does:** Checks for methods with high cyclomatic complexity.
/// ///
@ -31,7 +31,9 @@ pub struct CyclomaticComplexity {
impl CyclomaticComplexity { impl CyclomaticComplexity {
pub fn new(limit: u64) -> Self { pub fn new(limit: u64) -> Self {
Self { limit: LimitStack::new(limit) } Self {
limit: LimitStack::new(limit),
}
} }
} }
@ -125,18 +127,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
} }
fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) { fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
self.limit.push_attrs( self.limit
cx.sess(), .push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
attrs,
"cyclomatic_complexity",
);
} }
fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) { fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
self.limit.pop_attrs( self.limit
cx.sess(), .pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
attrs,
"cyclomatic_complexity",
);
} }
} }

View file

@ -3,7 +3,7 @@ use rustc::ty::{self, Ty};
use rustc::hir::*; use rustc::hir::*;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::paths; use utils::paths;
use utils::{is_automatically_derived, span_lint_and_then, match_path, is_copy}; use utils::{is_automatically_derived, is_copy, match_path, span_lint_and_then};
/// **What it does:** Checks for deriving `Hash` but implementing `PartialEq` /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
/// explicitly. /// explicitly.
@ -141,8 +141,7 @@ fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref
ty::TyAdt(def, _) if def.is_union() => return, ty::TyAdt(def, _) if def.is_union() => return,
// Some types are not Clone by default but could be cloned “by hand” if necessary // Some types are not Clone by default but could be cloned “by hand” if necessary
ty::TyAdt(def, substs) => { ty::TyAdt(def, substs) => for variant in &def.variants {
for variant in &def.variants {
for field in &variant.fields { for field in &variant.fields {
match field.ty(cx.tcx, substs).sty { match field.ty(cx.tcx, substs).sty {
ty::TyArray(_, size) if size > 32 => { ty::TyArray(_, size) if size > 32 => {
@ -157,15 +156,16 @@ fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref
_ => (), _ => (),
} }
} }
}
}, },
_ => (), _ => (),
} }
span_lint_and_then(cx, span_lint_and_then(
cx,
EXPL_IMPL_CLONE_ON_COPY, EXPL_IMPL_CLONE_ON_COPY,
item.span, item.span,
"you are implementing `Clone` explicitly on a `Copy` type", "you are implementing `Clone` explicitly on a `Copy` type",
|db| { db.span_note(item.span, "consider deriving `Clone` or removing `Copy`"); }); |db| { db.span_note(item.span, "consider deriving `Clone` or removing `Copy`"); },
);
} }
} }

View file

@ -2,7 +2,7 @@ use itertools::Itertools;
use pulldown_cmark; use pulldown_cmark;
use rustc::lint::*; use rustc::lint::*;
use syntax::ast; use syntax::ast;
use syntax::codemap::{Span, BytePos}; use syntax::codemap::{BytePos, Span};
use syntax_pos::Pos; use syntax_pos::Pos;
use utils::span_lint; use utils::span_lint;
@ -37,7 +37,9 @@ pub struct Doc {
impl Doc { impl Doc {
pub fn new(valid_idents: Vec<String>) -> Self { pub fn new(valid_idents: Vec<String>) -> Self {
Self { valid_idents: valid_idents } Self {
valid_idents: valid_idents,
}
} }
} }
@ -196,17 +198,13 @@ fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
for (offset, event) in docs { for (offset, event) in docs {
match event { match event {
Start(CodeBlock(_)) | Start(CodeBlock(_)) | Start(Code) => in_code = true,
Start(Code) => in_code = true, End(CodeBlock(_)) | End(Code) => in_code = false,
End(CodeBlock(_)) |
End(Code) => in_code = false,
Start(_tag) | End(_tag) => (), // We don't care about other tags Start(_tag) | End(_tag) => (), // We don't care about other tags
Html(_html) | Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
InlineHtml(_html) => (), // HTML is weird, just ignore it
SoftBreak => (), SoftBreak => (),
HardBreak => (), HardBreak => (),
FootnoteReference(text) | FootnoteReference(text) | Text(text) => {
Text(text) => {
if !in_code { if !in_code {
let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) { let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
Ok(o) => o, Ok(o) => o,

View file

@ -1,5 +1,5 @@
use syntax::ast::*; use syntax::ast::*;
use rustc::lint::{EarlyContext, LintContext, LintArray, LintPass, EarlyLintPass}; use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
/// **What it does:** Checks for unnecessary double parentheses. /// **What it does:** Checks for unnecessary double parentheses.
/// ///
@ -31,30 +31,23 @@ impl LintPass for DoubleParens {
impl EarlyLintPass for DoubleParens { impl EarlyLintPass for DoubleParens {
fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) { fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
match expr.node { match expr.node {
ExprKind::Paren(ref in_paren) => { ExprKind::Paren(ref in_paren) => match in_paren.node {
match in_paren.node { ExprKind::Paren(_) | ExprKind::Tup(_) => {
ExprKind::Paren(_) |
ExprKind::Tup(_) => {
cx.span_lint(DOUBLE_PARENS, expr.span, "Consider removing unnecessary double parentheses"); cx.span_lint(DOUBLE_PARENS, expr.span, "Consider removing unnecessary double parentheses");
}, },
_ => {}, _ => {},
}
}, },
ExprKind::Call(_, ref params) => { ExprKind::Call(_, ref params) => if params.len() == 1 {
if params.len() == 1 {
let param = &params[0]; let param = &params[0];
if let ExprKind::Paren(_) = param.node { if let ExprKind::Paren(_) = param.node {
cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses"); cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses");
} }
}
}, },
ExprKind::MethodCall(_, ref params) => { ExprKind::MethodCall(_, ref params) => if params.len() == 2 {
if params.len() == 2 {
let param = &params[1]; let param = &params[1];
if let ExprKind::Paren(_) = param.node { if let ExprKind::Paren(_) = param.node {
cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses"); cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses");
} }
}
}, },
_ => {}, _ => {},
} }

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::ty; use rustc::ty;
use rustc::hir::*; use rustc::hir::*;
use utils::{match_def_path, paths, span_note_and_lint, is_copy}; use utils::{is_copy, match_def_path, paths, span_note_and_lint};
/// **What it does:** Checks for calls to `std::mem::drop` with a reference /// **What it does:** Checks for calls to `std::mem::drop` with a reference
/// instead of an owned value. /// instead of an owned value.

View file

@ -36,9 +36,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EmptyEnum {
let did = cx.tcx.hir.local_def_id(item.id); let did = cx.tcx.hir.local_def_id(item.id);
if let ItemEnum(..) = item.node { if let ItemEnum(..) = item.node {
let ty = cx.tcx.type_of(did); let ty = cx.tcx.type_of(did);
let adt = ty.ty_adt_def().expect( let adt = ty.ty_adt_def()
"already checked whether this is an enum", .expect("already checked whether this is an enum");
);
if adt.variants.is_empty() { if adt.variants.is_empty() {
span_lint_and_then(cx, EMPTY_ENUM, item.span, "enum with no variants", |db| { span_lint_and_then(cx, EMPTY_ENUM, item.span, "enum with no variants", |db| {
db.span_help(item.span, "consider using the uninhabited type `!` or a wrapper around it"); db.span_help(item.span, "consider using the uninhabited type `!` or a wrapper around it");

View file

@ -1,5 +1,5 @@
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc::lint::*; use rustc::lint::*;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::SpanlessEq; use utils::SpanlessEq;
@ -47,8 +47,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapLint {
// in case of `if !m.contains_key(&k) { m.insert(k, v); }` // in case of `if !m.contains_key(&k) { m.insert(k, v); }`
// we can give a better error message // we can give a better error message
let sole_expr = { let sole_expr = {
else_block.is_none() && else_block.is_none() && if let ExprBlock(ref then_block) = then_block.node {
if let ExprBlock(ref then_block) = then_block.node {
(then_block.expr.is_some() as usize) + then_block.stmts.len() == 1 (then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
} else { } else {
true true

View file

@ -51,9 +51,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
let did = cx.tcx.hir.body_owner_def_id(body_id); let did = cx.tcx.hir.body_owner_def_id(body_id);
let param_env = ty::ParamEnv::empty(Reveal::UserFacing); let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did); let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did);
let bad = match cx.tcx.at(expr.span).const_eval( let bad = match cx.tcx
param_env.and((did, substs)), .at(expr.span)
) { .const_eval(param_env.and((did, substs)))
{
Ok(ConstVal::Integral(Usize(Us64(i)))) => u64::from(i as u32) != i, Ok(ConstVal::Integral(Usize(Us64(i)))) => u64::from(i as u32) != i,
Ok(ConstVal::Integral(Isize(Is64(i)))) => i64::from(i as i32) != i, Ok(ConstVal::Integral(Isize(Is64(i)))) => i64::from(i as i32) != i,
_ => false, _ => false,

View file

@ -1,7 +1,7 @@
//! lint on `use`ing all variants of an enum //! lint on `use`ing all variants of an enum
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::{LateLintPass, LintPass, LateContext, LintArray}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use syntax::ast::NodeId; use syntax::ast::NodeId;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::span_lint; use utils::span_lint;

View file

@ -1,6 +1,6 @@
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::*; use rustc::lint::*;
use utils::{SpanlessEq, span_lint, span_lint_and_then, multispan_sugg, snippet, implements_trait, is_copy}; use utils::{implements_trait, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then, SpanlessEq};
/// **What it does:** Checks for equal operands to comparison, logical and /// **What it does:** Checks for equal operands to comparison, logical and
/// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`, /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
@ -82,8 +82,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp {
#[allow(match_same_arms)] #[allow(match_same_arms)]
match (&left.node, &right.node) { match (&left.node, &right.node) {
// do not suggest to dereference literals // do not suggest to dereference literals
(&ExprLit(..), _) | (&ExprLit(..), _) | (_, &ExprLit(..)) => {},
(_, &ExprLit(..)) => {},
// &foo == &bar // &foo == &bar
(&ExprAddrOf(_, ref l), &ExprAddrOf(_, ref r)) => { (&ExprAddrOf(_, ref l), &ExprAddrOf(_, ref r)) => {
let lty = cx.tables.expr_ty(l); let lty = cx.tables.expr_ty(l);

View file

@ -133,7 +133,6 @@ impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
self.set.remove(&lid); self.set.remove(&lid);
} }
} }
} }
fn borrow(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, loan_cause: LoanCause) { fn borrow(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, loan_cause: LoanCause) {
if let Categorization::Local(lid) = cmt.cat { if let Categorization::Local(lid) = cmt.cat {

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::ty; use rustc::ty;
use rustc::hir::*; use rustc::hir::*;
use utils::{snippet_opt, span_lint_and_then, is_adjusted, iter_input_pats}; use utils::{is_adjusted, iter_input_pats, snippet_opt, span_lint_and_then};
#[allow(missing_copy_implementations)] #[allow(missing_copy_implementations)]
pub struct EtaPass; pub struct EtaPass;
@ -37,11 +37,8 @@ impl LintPass for EtaPass {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaPass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
match expr.node { match expr.node {
ExprCall(_, ref args) | ExprCall(_, ref args) | ExprMethodCall(_, _, ref args) => for arg in args {
ExprMethodCall(_, _, ref args) => {
for arg in args {
check_closure(cx, arg) check_closure(cx, arg)
}
}, },
_ => (), _ => (),
} }

View file

@ -1,9 +1,9 @@
use rustc::hir::def_id::DefId; use rustc::hir::def_id::DefId;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc::hir::*; use rustc::hir::*;
use rustc::ty; use rustc::ty;
use rustc::lint::*; use rustc::lint::*;
use utils::{get_parent_expr, span_note_and_lint, span_lint}; use utils::{get_parent_expr, span_lint, span_note_and_lint};
/// **What it does:** Checks for a read and a write to the same variable where /// **What it does:** Checks for a read and a write to the same variable where
/// whether the read occurs before or after the write depends on the evaluation /// whether the read occurs before or after the write depends on the evaluation
@ -62,9 +62,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
// Find a write to a local variable. // Find a write to a local variable.
match expr.node { match expr.node {
ExprAssign(ref lhs, _) | ExprAssign(ref lhs, _) | ExprAssignOp(_, ref lhs, _) => if let ExprPath(ref qpath) = lhs.node {
ExprAssignOp(_, ref lhs, _) => {
if let ExprPath(ref qpath) = lhs.node {
if let QPath::Resolved(_, ref path) = *qpath { if let QPath::Resolved(_, ref path) = *qpath {
if path.segments.len() == 1 { if path.segments.len() == 1 {
let var = cx.tables.qpath_def(qpath, lhs.hir_id).def_id(); let var = cx.tables.qpath_def(qpath, lhs.hir_id).def_id();
@ -77,21 +75,20 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
check_for_unsequenced_reads(&mut visitor); check_for_unsequenced_reads(&mut visitor);
} }
} }
}
}, },
_ => {}, _ => {},
} }
} }
fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) { fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
match stmt.node { match stmt.node {
StmtExpr(ref e, _) | StmtExpr(ref e, _) | StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e), StmtDecl(ref d, _) => if let DeclLocal(ref local) = d.node {
StmtDecl(ref d, _) => { if let Local {
if let DeclLocal(ref local) = d.node { init: Some(ref e), ..
if let Local { init: Some(ref e), .. } = **local { } = **local
{
DivergenceVisitor { cx: cx }.visit_expr(e); DivergenceVisitor { cx: cx }.visit_expr(e);
} }
}
}, },
} }
} }
@ -230,8 +227,7 @@ fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> St
ExprStruct(_, _, _) => { ExprStruct(_, _, _) => {
walk_expr(vis, expr); walk_expr(vis, expr);
}, },
ExprBinary(op, _, _) | ExprBinary(op, _, _) | ExprAssignOp(op, _, _) => {
ExprAssignOp(op, _, _) => {
if op.node == BiAnd || op.node == BiOr { if op.node == BiAnd || op.node == BiOr {
// x && y and x || y always evaluate x first, so these are // x && y and x || y always evaluate x first, so these are
// strictly sequenced. // strictly sequenced.
@ -265,8 +261,7 @@ fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> St
fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly { fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
match stmt.node { match stmt.node {
StmtExpr(ref expr, _) | StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => check_expr(vis, expr),
StmtSemi(ref expr, _) => check_expr(vis, expr),
StmtDecl(ref decl, _) => { StmtDecl(ref decl, _) => {
// If the declaration is of a local variable, check its initializer // If the declaration is of a local variable, check its initializer
// expression if it has one. Otherwise, keep going. // expression if it has one. Otherwise, keep going.
@ -274,10 +269,9 @@ fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> St
DeclLocal(ref local) => Some(local), DeclLocal(ref local) => Some(local),
_ => None, _ => None,
}; };
local.and_then(|local| local.init.as_ref()).map_or( local
StopEarly::KeepGoing, .and_then(|local| local.init.as_ref())
|expr| check_expr(vis, expr), .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
)
}, },
} }
} }

View file

@ -57,12 +57,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
}} }}
}, },
// `format!("foo")` expansion contains `match () { () => [], }` // `format!("foo")` expansion contains `match () { () => [], }`
ExprMatch(ref matchee, _, _) => { ExprMatch(ref matchee, _, _) => if let ExprTup(ref tup) = matchee.node {
if let ExprTup(ref tup) = matchee.node {
if tup.is_empty() { if tup.is_empty() {
span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`"); span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
} }
}
}, },
_ => (), _ => (),
} }

View file

@ -142,9 +142,9 @@ fn check_else_if(cx: &EarlyContext, expr: &ast::Expr) {
// the snippet should look like " else \n " with maybe comments anywhere // the snippet should look like " else \n " with maybe comments anywhere
// its bad when there is a \n after the “else” // its bad when there is a \n after the “else”
if let Some(else_snippet) = snippet_opt(cx, else_span) { if let Some(else_snippet) = snippet_opt(cx, else_span) {
let else_pos = else_snippet.find("else").expect( let else_pos = else_snippet
"there must be a `else` here", .find("else")
); .expect("there must be a `else` here");
if else_snippet[else_pos..].contains('\n') { if else_snippet[else_pos..].contains('\n') {
span_note_and_lint( span_note_and_lint(
@ -215,8 +215,9 @@ fn check_consecutive_ifs(cx: &EarlyContext, first: &ast::Expr, second: &ast::Exp
/// Match `if` or `if let` expressions and return the `then` and `else` block. /// Match `if` or `if let` expressions and return the `then` and `else` block.
fn unsugar_if(expr: &ast::Expr) -> Option<(&P<ast::Block>, &Option<P<ast::Expr>>)> { fn unsugar_if(expr: &ast::Expr) -> Option<(&P<ast::Block>, &Option<P<ast::Expr>>)> {
match expr.node { match expr.node {
ast::ExprKind::If(_, ref then, ref else_) | ast::ExprKind::If(_, ref then, ref else_) | ast::ExprKind::IfLet(_, _, ref then, ref else_) => {
ast::ExprKind::IfLet(_, _, ref then, ref else_) => Some((then, else_)), Some((then, else_))
},
_ => None, _ => None,
} }
} }

View file

@ -6,7 +6,7 @@ use std::collections::HashSet;
use syntax::ast; use syntax::ast;
use syntax::abi::Abi; use syntax::abi::Abi;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{span_lint, type_is_unsafe_function, iter_input_pats}; use utils::{iter_input_pats, span_lint, type_is_unsafe_function};
/// **What it does:** Checks for functions with too many parameters. /// **What it does:** Checks for functions with too many parameters.
/// ///
@ -60,7 +60,9 @@ pub struct Functions {
impl Functions { impl Functions {
pub fn new(threshold: u64) -> Self { pub fn new(threshold: u64) -> Self {
Self { threshold: threshold } Self {
threshold: threshold,
}
} }
} }

View file

@ -2,7 +2,7 @@ use consts::{constant_simple, Constant};
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{span_lint, snippet, in_macro}; use utils::{in_macro, snippet, span_lint};
use syntax::attr::IntType::{SignedInt, UnsignedInt}; use syntax::attr::IntType::{SignedInt, UnsignedInt};
/// **What it does:** Checks for identity operations, e.g. `x + 0`. /// **What it does:** Checks for identity operations, e.g. `x + 0`.
@ -63,16 +63,13 @@ fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
if let Some(Constant::Int(v)) = constant_simple(cx, e) { if let Some(Constant::Int(v)) = constant_simple(cx, e) {
if match m { if match m {
0 => v.to_u128_unchecked() == 0, 0 => v.to_u128_unchecked() == 0,
-1 => { -1 => match v.int_type() {
match v.int_type() {
SignedInt(_) => (v.to_u128_unchecked() as i128 == -1), SignedInt(_) => (v.to_u128_unchecked() as i128 == -1),
UnsignedInt(_) => false, UnsignedInt(_) => false,
}
}, },
1 => v.to_u128_unchecked() == 1, 1 => v.to_u128_unchecked() == 1,
_ => unreachable!(), _ => unreachable!(),
} } {
{
span_lint( span_lint(
cx, cx,
IDENTITY_OP, IDENTITY_OP,

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{paths, span_lint_and_then, match_qpath, snippet}; use utils::{match_qpath, paths, snippet, span_lint_and_then};
/// **What it does:*** Lint for redundant pattern matching over `Result` or /// **What it does:*** Lint for redundant pattern matching over `Result` or
/// `Option` /// `Option`
@ -45,11 +45,8 @@ impl LintPass for Pass {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if let ExprMatch(ref op, ref arms, MatchSource::IfLetDesugar { .. }) = expr.node { if let ExprMatch(ref op, ref arms, MatchSource::IfLetDesugar { .. }) = expr.node {
if arms[0].pats.len() == 1 { if arms[0].pats.len() == 1 {
let good_method = match arms[0].pats[0].node { let good_method = match arms[0].pats[0].node {
PatKind::TupleStruct(ref path, ref pats, _) if pats.len() == 1 && pats[0].node == PatKind::Wild => { PatKind::TupleStruct(ref path, ref pats, _) if pats.len() == 1 && pats[0].node == PatKind::Wild => {
if match_qpath(path, &paths::RESULT_OK) { if match_qpath(path, &paths::RESULT_OK) {
@ -68,16 +65,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
_ => return, _ => return,
}; };
span_lint_and_then(cx, span_lint_and_then(
cx,
IF_LET_REDUNDANT_PATTERN_MATCHING, IF_LET_REDUNDANT_PATTERN_MATCHING,
arms[0].pats[0].span, arms[0].pats[0].span,
&format!("redundant pattern matching, consider using `{}`", good_method), &format!("redundant pattern matching, consider using `{}`", good_method),
|db| { |db| {
let span = expr.span.with_hi(op.span.hi()); let span = expr.span.with_hi(op.span.hi());
db.span_suggestion(span, "try this", format!("if {}.{}", snippet(cx, op.span, "_"), good_method)); db.span_suggestion(
}); span,
"try this",
format!("if {}.{}", snippet(cx, op.span, "_"), good_method),
);
},
);
} }
} }
} }
} }

View file

@ -1,6 +1,6 @@
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::*; use rustc::lint::*;
use utils::{get_trait_def_id, implements_trait, higher, match_qpath, paths, span_lint}; use utils::{get_trait_def_id, higher, implements_trait, match_qpath, paths, span_lint};
/// **What it does:** Checks for iteration that is guaranteed to be infinite. /// **What it does:** Checks for iteration that is guaranteed to be infinite.
/// ///
@ -66,14 +66,13 @@ enum Finiteness {
Finite, Finite,
} }
use self::Finiteness::{Infinite, MaybeInfinite, Finite}; use self::Finiteness::{Finite, Infinite, MaybeInfinite};
impl Finiteness { impl Finiteness {
fn and(self, b: Self) -> Self { fn and(self, b: Self) -> Self {
match (self, b) { match (self, b) {
(Finite, _) | (_, Finite) => Finite, (Finite, _) | (_, Finite) => Finite,
(MaybeInfinite, _) | (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite,
(_, MaybeInfinite) => MaybeInfinite,
_ => Infinite, _ => Infinite,
} }
} }
@ -81,8 +80,7 @@ impl Finiteness {
fn or(self, b: Self) -> Self { fn or(self, b: Self) -> Self {
match (self, b) { match (self, b) {
(Infinite, _) | (_, Infinite) => Infinite, (Infinite, _) | (_, Infinite) => Infinite,
(MaybeInfinite, _) | (MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite,
(_, MaybeInfinite) => MaybeInfinite,
_ => Finite, _ => Finite,
} }
} }
@ -90,7 +88,11 @@ impl Finiteness {
impl From<bool> for Finiteness { impl From<bool> for Finiteness {
fn from(b: bool) -> Self { fn from(b: bool) -> Self {
if b { Infinite } else { Finite } if b {
Infinite
} else {
Finite
}
} }
} }
@ -108,7 +110,7 @@ enum Heuristic {
All, All,
} }
use self::Heuristic::{Always, First, Any, All}; use self::Heuristic::{All, Always, Any, First};
/// a slice of (method name, number of args, heuristic, bounds) tuples /// a slice of (method name, number of args, heuristic, bounds) tuples
/// that will be used to determine whether the method in question /// that will be used to determine whether the method in question
@ -159,20 +161,15 @@ fn is_infinite(cx: &LateContext, expr: &Expr) -> Finiteness {
Finite Finite
}, },
ExprBlock(ref block) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)), ExprBlock(ref block) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)),
ExprBox(ref e) | ExprBox(ref e) | ExprAddrOf(_, ref e) => is_infinite(cx, e),
ExprAddrOf(_, ref e) => is_infinite(cx, e), ExprCall(ref path, _) => if let ExprPath(ref qpath) = path.node {
ExprCall(ref path, _) => {
if let ExprPath(ref qpath) = path.node {
match_qpath(qpath, &paths::REPEAT).into() match_qpath(qpath, &paths::REPEAT).into()
} else { } else {
Finite Finite
}
}, },
ExprStruct(..) => { ExprStruct(..) => higher::range(expr)
higher::range(expr)
.map_or(false, |r| r.end.is_none()) .map_or(false, |r| r.end.is_none())
.into() .into(),
},
_ => Finite, _ => Finite,
} }
} }
@ -220,23 +217,18 @@ fn complete_infinite_iter(cx: &LateContext, expr: &Expr) -> Finiteness {
} }
} }
if method.name == "last" && args.len() == 1 { if method.name == "last" && args.len() == 1 {
let not_double_ended = get_trait_def_id(cx, let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR)
&paths::DOUBLE_ENDED_ITERATOR) .map_or(false, |id| !implements_trait(cx, cx.tables.expr_ty(&args[0]), id, &[]));
.map_or(false, |id| {
!implements_trait(cx, cx.tables.expr_ty(&args[0]), id, &[])
});
if not_double_ended { if not_double_ended {
return is_infinite(cx, &args[0]); return is_infinite(cx, &args[0]);
} }
} }
}, },
ExprBinary(op, ref l, ref r) => { ExprBinary(op, ref l, ref r) => if op.node.is_comparison() {
if op.node.is_comparison() { return is_infinite(cx, l)
return is_infinite(cx, l).and(is_infinite(cx, r)).and( .and(is_infinite(cx, r))
MaybeInfinite, .and(MaybeInfinite);
); }, // TODO: ExprLoop + Match
}
}, //TODO: ExprLoop + Match
_ => (), _ => (),
} }
Finite Finite

View file

@ -100,12 +100,10 @@ impl EarlyLintPass for UnitExpr {
} }
fn is_unit_expr(expr: &Expr) -> Option<Span> { fn is_unit_expr(expr: &Expr) -> Option<Span> {
match expr.node { match expr.node {
ExprKind::Block(ref block) => { ExprKind::Block(ref block) => if check_last_stmt_in_block(block) {
if check_last_stmt_in_block(block) {
Some(block.stmts[block.stmts.len() - 1].span) Some(block.stmts[block.stmts.len() - 1].span)
} else { } else {
None None
}
}, },
ExprKind::If(_, ref then, ref else_) => { ExprKind::If(_, ref then, ref else_) => {
let check_then = check_last_stmt_in_block(then); let check_then = check_last_stmt_in_block(then);
@ -115,7 +113,11 @@ fn is_unit_expr(expr: &Expr) -> Option<Span> {
return Some(*expr_else); return Some(*expr_else);
} }
} }
if check_then { Some(expr.span) } else { None } if check_then {
Some(expr.span)
} else {
None
}
}, },
ExprKind::Match(ref _pattern, ref arms) => { ExprKind::Match(ref _pattern, ref arms) => {
for arm in arms { for arm in arms {
@ -137,12 +139,9 @@ fn check_last_stmt_in_block(block: &Block) -> bool {
// like `panic!()` // like `panic!()`
match final_stmt.node { match final_stmt.node {
StmtKind::Expr(_) => false, StmtKind::Expr(_) => false,
StmtKind::Semi(ref expr) => { StmtKind::Semi(ref expr) => match expr.node {
match expr.node { ExprKind::Break(_, _) | ExprKind::Ret(_) => false,
ExprKind::Break(_, _) |
ExprKind::Ret(_) => false,
_ => true, _ => true,
}
}, },
_ => true, _ => true,
} }

View file

@ -47,9 +47,10 @@ impl EarlyLintPass for ItemsAfterStatements {
} }
// skip initial items // skip initial items
let stmts = item.stmts.iter().map(|stmt| &stmt.node).skip_while(|s| { let stmts = item.stmts
matches!(**s, StmtKind::Item(..)) .iter()
}); .map(|stmt| &stmt.node)
.skip_while(|s| matches!(**s, StmtKind::Item(..)));
// lint on all further items // lint on all further items
for stmt in stmts { for stmt in stmts {

View file

@ -2,7 +2,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{span_lint_and_then, snippet_opt, type_size}; use utils::{snippet_opt, span_lint_and_then, type_size};
use rustc::ty::TypeFoldable; use rustc::ty::TypeFoldable;
/// **What it does:** Checks for large size differences between variants on /// **What it does:** Checks for large size differences between variants on
@ -34,7 +34,9 @@ pub struct LargeEnumVariant {
impl LargeEnumVariant { impl LargeEnumVariant {
pub fn new(maximum_size_difference_allowed: u64) -> Self { pub fn new(maximum_size_difference_allowed: u64) -> Self {
Self { maximum_size_difference_allowed: maximum_size_difference_allowed } Self {
maximum_size_difference_allowed: maximum_size_difference_allowed,
}
} }
} }
@ -49,9 +51,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
let did = cx.tcx.hir.local_def_id(item.id); let did = cx.tcx.hir.local_def_id(item.id);
if let ItemEnum(ref def, _) = item.node { if let ItemEnum(ref def, _) = item.node {
let ty = cx.tcx.type_of(did); let ty = cx.tcx.type_of(did);
let adt = ty.ty_adt_def().expect( let adt = ty.ty_adt_def()
"already checked whether this is an enum", .expect("already checked whether this is an enum");
);
let mut smallest_variant: Option<(_, _)> = None; let mut smallest_variant: Option<(_, _)> = None;
let mut largest_variant: Option<(_, _)> = None; let mut largest_variant: Option<(_, _)> = None;
@ -90,8 +91,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
|db| { |db| {
if variant.fields.len() == 1 { if variant.fields.len() == 1 {
let span = match def.variants[i].node.data { let span = match def.variants[i].node.data {
VariantData::Struct(ref fields, _) | VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => {
VariantData::Tuple(ref fields, _) => fields[0].ty.span, fields[0].ty.span
},
VariantData::Unit(_) => unreachable!(), VariantData::Unit(_) => unreachable!(),
}; };
if let Some(snip) = snippet_opt(cx, span) { if let Some(snip) = snippet_opt(cx, span) {
@ -112,7 +114,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
); );
} }
} }
} }
} }
} }

View file

@ -91,10 +91,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LenZero {
fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[TraitItemRef]) { fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[TraitItemRef]) {
fn is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool { fn is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool {
item.name == name && item.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
if let AssociatedItemKind::Method { has_self } = item.kind { has_self && {
has_self &&
{
let did = cx.tcx.hir.local_def_id(item.id.node_id); let did = cx.tcx.hir.local_def_id(item.id.node_id);
cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
} }
@ -121,9 +119,7 @@ fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[Trai
.iter() .iter()
.flat_map(|&i| cx.tcx.associated_items(i)) .flat_map(|&i| cx.tcx.associated_items(i))
.any(|i| { .any(|i| {
i.kind == ty::AssociatedKind::Method && i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.name == "is_empty" &&
i.method_has_self_argument &&
i.name == "is_empty" &&
cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1 cx.tcx.fn_sig(i.def_id).inputs().skip_binder().len() == 1
}); });
@ -143,10 +139,8 @@ fn check_trait_items(cx: &LateContext, visited_trait: &Item, trait_items: &[Trai
fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) { fn check_impl_items(cx: &LateContext, item: &Item, impl_items: &[ImplItemRef]) {
fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool { fn is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
item.name == name && item.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
if let AssociatedItemKind::Method { has_self } = item.kind { has_self && {
has_self &&
{
let did = cx.tcx.hir.local_def_id(item.id.node_id); let did = cx.tcx.hir.local_def_id(item.id.node_id);
cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1 cx.tcx.fn_sig(did).inputs().skip_binder().len() == 1
} }
@ -197,7 +191,11 @@ fn check_cmp(cx: &LateContext, span: Span, left: &Expr, right: &Expr, op: &str)
} }
fn check_len_zero(cx: &LateContext, span: Span, name: Name, args: &[Expr], lit: &Lit, op: &str) { fn check_len_zero(cx: &LateContext, span: Span, name: Name, args: &[Expr], lit: &Lit, op: &str) {
if let Spanned { node: LitKind::Int(0, _), .. } = *lit { if let Spanned {
node: LitKind::Int(0, _),
..
} = *lit
{
if name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) { if name == "len" && args.len() == 1 && has_is_empty(cx, &args[0]) {
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
@ -231,25 +229,19 @@ fn has_is_empty(cx: &LateContext, expr: &Expr) -> bool {
/// Check the inherent impl's items for an `is_empty(self)` method. /// Check the inherent impl's items for an `is_empty(self)` method.
fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool { fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
cx.tcx.inherent_impls(id).iter().any(|imp| { cx.tcx.inherent_impls(id).iter().any(|imp| {
cx.tcx.associated_items(*imp).any( cx.tcx
|item| is_is_empty(cx, &item), .associated_items(*imp)
) .any(|item| is_is_empty(cx, &item))
}) })
} }
let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr)); let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
match ty.sty { match ty.sty {
ty::TyDynamic(..) => { ty::TyDynamic(..) => cx.tcx
cx.tcx
.associated_items(ty.ty_to_def_id().expect("trait impl not found")) .associated_items(ty.ty_to_def_id().expect("trait impl not found"))
.any(|item| is_is_empty(cx, &item)) .any(|item| is_is_empty(cx, &item)),
}, ty::TyProjection(_) => ty.ty_to_def_id()
ty::TyProjection(_) => { .map_or(false, |id| has_is_empty_impl(cx, id)),
ty.ty_to_def_id().map_or(
false,
|id| has_is_empty_impl(cx, id),
)
},
ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did), ty::TyAdt(id, _) => has_is_empty_impl(cx, id.did),
ty::TyArray(..) | ty::TySlice(..) | ty::TyStr => true, ty::TyArray(..) | ty::TySlice(..) | ty::TyStr => true,
_ => false, _ => false,

View file

@ -8,39 +8,42 @@
#![feature(slice_patterns)] #![feature(slice_patterns)]
#![feature(stmt_expr_attributes)] #![feature(stmt_expr_attributes)]
#![feature(conservative_impl_trait)] #![feature(conservative_impl_trait)]
#![allow(unknown_lints, indexing_slicing, shadow_reuse, missing_docs_in_private_items)] #![allow(unknown_lints, indexing_slicing, shadow_reuse, missing_docs_in_private_items)]
extern crate syntax;
extern crate syntax_pos;
#[macro_use] #[macro_use]
extern crate rustc; extern crate rustc;
extern crate syntax;
extern crate syntax_pos;
extern crate toml; extern crate toml;
// for unicode nfc normalization // for unicode nfc normalization
extern crate unicode_normalization; extern crate unicode_normalization;
// for semver check in attrs.rs // for semver check in attrs.rs
extern crate semver; extern crate semver;
// for regex checking // for regex checking
extern crate regex_syntax; extern crate regex_syntax;
// for finding minimal boolean expressions // for finding minimal boolean expressions
extern crate quine_mc_cluskey; extern crate quine_mc_cluskey;
extern crate rustc_errors;
extern crate rustc_plugin;
extern crate rustc_const_eval; extern crate rustc_const_eval;
extern crate rustc_const_math; extern crate rustc_const_math;
extern crate rustc_errors;
extern crate rustc_plugin;
#[macro_use] #[macro_use]
extern crate matches as matches_macro; extern crate matches as matches_macro;
extern crate serde;
#[macro_use] #[macro_use]
extern crate serde_derive; extern crate serde_derive;
extern crate serde;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;

View file

@ -2,10 +2,10 @@ use reexport::*;
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::def::Def; use rustc::hir::def::Def;
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_ty, walk_ty_param_bound, walk_fn_decl, walk_generics, NestedVisitorMap}; use rustc::hir::intravisit::{walk_fn_decl, walk_generics, walk_ty, walk_ty_param_bound, NestedVisitorMap, Visitor};
use std::collections::{HashSet, HashMap}; use std::collections::{HashMap, HashSet};
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{in_external_macro, span_lint, last_path_segment}; use utils::{in_external_macro, last_path_segment, span_lint};
use syntax::symbol::keywords; use syntax::symbol::keywords;
/// **What it does:** Checks for lifetime annotations which can be removed by /// **What it does:** Checks for lifetime annotations which can be removed by
@ -171,7 +171,9 @@ fn could_use_elision<'a, 'tcx: 'a>(
}; };
if let Some(body_id) = body { if let Some(body_id) = body {
let mut checker = BodyLifetimeChecker { lifetimes_used_in_body: false }; let mut checker = BodyLifetimeChecker {
lifetimes_used_in_body: false,
};
checker.visit_expr(&cx.tcx.hir.body(body_id).value); checker.visit_expr(&cx.tcx.hir.body(body_id).value);
if checker.lifetimes_used_in_body { if checker.lifetimes_used_in_body {
return false; return false;
@ -192,9 +194,9 @@ fn could_use_elision<'a, 'tcx: 'a>(
// no output lifetimes, check distinctness of input lifetimes // no output lifetimes, check distinctness of input lifetimes
// only unnamed and static, ok // only unnamed and static, ok
let unnamed_and_static = input_lts.iter().all(|lt| { let unnamed_and_static = input_lts
*lt == RefLt::Unnamed || *lt == RefLt::Static .iter()
}); .all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
if unnamed_and_static { if unnamed_and_static {
return false; return false;
} }
@ -210,8 +212,8 @@ fn could_use_elision<'a, 'tcx: 'a>(
match (&input_lts[0], &output_lts[0]) { match (&input_lts[0], &output_lts[0]) {
(&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true, (&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
(&RefLt::Named(_), &RefLt::Unnamed) => true, (&RefLt::Named(_), &RefLt::Unnamed) => true,
_ => false, // already elided, different named lifetimes _ => false, /* already elided, different named lifetimes
// or something static going on * or something static going on */
} }
} else { } else {
false false
@ -277,7 +279,11 @@ impl<'v, 't> RefVisitor<'v, 't> {
} }
fn into_vec(self) -> Option<Vec<RefLt>> { fn into_vec(self) -> Option<Vec<RefLt>> {
if self.abort { None } else { Some(self.lts) } if self.abort {
None
} else {
Some(self.lts)
}
} }
fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) { fn collect_anonymous_lifetimes(&mut self, qpath: &QPath, ty: &Ty) {
@ -285,8 +291,7 @@ impl<'v, 't> RefVisitor<'v, 't> {
if !last_path_segment.parenthesized && last_path_segment.lifetimes.is_empty() { if !last_path_segment.parenthesized && last_path_segment.lifetimes.is_empty() {
let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id); let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
match self.cx.tables.qpath_def(qpath, hir_id) { match self.cx.tables.qpath_def(qpath, hir_id) {
Def::TyAlias(def_id) | Def::TyAlias(def_id) | Def::Struct(def_id) => {
Def::Struct(def_id) => {
let generics = self.cx.tcx.generics_of(def_id); let generics = self.cx.tcx.generics_of(def_id);
for _ in generics.regions.as_slice() { for _ in generics.regions.as_slice() {
self.record(&None); self.record(&None);
@ -318,12 +323,10 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
TyPath(ref path) => { TyPath(ref path) => {
self.collect_anonymous_lifetimes(path, ty); self.collect_anonymous_lifetimes(path, ty);
}, },
TyImplTrait(ref param_bounds) => { TyImplTrait(ref param_bounds) => for bound in param_bounds {
for bound in param_bounds {
if let RegionTyParamBound(_) = *bound { if let RegionTyParamBound(_) = *bound {
self.record(&None); self.record(&None);
} }
}
}, },
TyTraitObject(ref bounds, ref lt) => { TyTraitObject(ref bounds, ref lt) => {
if !lt.is_elided() { if !lt.is_elided() {
@ -366,12 +369,10 @@ fn has_where_lifetimes<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, where_clause: &
// and check that all lifetimes are allowed // and check that all lifetimes are allowed
match visitor.into_vec() { match visitor.into_vec() {
None => return false, None => return false,
Some(lts) => { Some(lts) => for lt in lts {
for lt in lts {
if !allowed_lts.contains(&lt) { if !allowed_lts.contains(&lt) {
return true; return true;
} }
}
}, },
} }
}, },

View file

@ -4,7 +4,7 @@
use rustc::lint::*; use rustc::lint::*;
use syntax::ast::*; use syntax::ast::*;
use syntax_pos; use syntax_pos;
use utils::{span_help_and_lint, snippet_opt, in_external_macro}; use utils::{in_external_macro, snippet_opt, span_help_and_lint};
/// **What it does:** Warns if a long integral or floating-point constant does /// **What it does:** Warns if a long integral or floating-point constant does
/// not contain underscores. /// not contain underscores.
@ -195,33 +195,27 @@ enum WarningType {
impl WarningType { impl WarningType {
pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) { pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) {
match *self { match *self {
WarningType::UnreadableLiteral => { WarningType::UnreadableLiteral => span_help_and_lint(
span_help_and_lint(
cx, cx,
UNREADABLE_LITERAL, UNREADABLE_LITERAL,
*span, *span,
"long literal lacking separators", "long literal lacking separators",
&format!("consider: {}", grouping_hint), &format!("consider: {}", grouping_hint),
) ),
}, WarningType::LargeDigitGroups => span_help_and_lint(
WarningType::LargeDigitGroups => {
span_help_and_lint(
cx, cx,
LARGE_DIGIT_GROUPS, LARGE_DIGIT_GROUPS,
*span, *span,
"digit groups should be smaller", "digit groups should be smaller",
&format!("consider: {}", grouping_hint), &format!("consider: {}", grouping_hint),
) ),
}, WarningType::InconsistentDigitGrouping => span_help_and_lint(
WarningType::InconsistentDigitGrouping => {
span_help_and_lint(
cx, cx,
INCONSISTENT_DIGIT_GROUPING, INCONSISTENT_DIGIT_GROUPING,
*span, *span,
"digits grouped inconsistently by underscores", "digits grouped inconsistently by underscores",
&format!("consider: {}", grouping_hint), &format!("consider: {}", grouping_hint),
) ),
},
}; };
} }
} }

View file

@ -2,7 +2,7 @@ use reexport::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::def::Def; use rustc::hir::def::Def;
use rustc::hir::def_id::DefId; use rustc::hir::def_id::DefId;
use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl, walk_pat, walk_stmt, NestedVisitorMap}; use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt}; use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
use rustc::lint::*; use rustc::lint::*;
use rustc::middle::const_val::ConstVal; use rustc::middle::const_val::ConstVal;
@ -14,9 +14,9 @@ use std::collections::{HashMap, HashSet};
use syntax::ast; use syntax::ast;
use utils::sugg; use utils::sugg;
use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, multispan_sugg, in_external_macro, use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
is_refutable, span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, higher, last_path_segment, match_trait_method, match_type, multispan_sugg, snippet, span_help_and_lint, span_lint,
last_path_segment, span_lint_and_sugg}; span_lint_and_sugg, span_lint_and_then};
use utils::paths; use utils::paths;
/// **What it does:** Checks for looping over the range of `0..len` of some /// **What it does:** Checks for looping over the range of `0..len` of some
@ -340,11 +340,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
// check for never_loop // check for never_loop
match expr.node { match expr.node {
ExprWhile(_, ref block, _) | ExprWhile(_, ref block, _) | ExprLoop(ref block, _, _) => if never_loop(block, &expr.id) {
ExprLoop(ref block, _, _) => {
if never_loop(block, &expr.id) {
span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"); span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
}
}, },
_ => (), _ => (),
} }
@ -371,8 +368,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node { if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
// ensure "if let" compatible match structure // ensure "if let" compatible match structure
match *source { match *source {
MatchSource::Normal | MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
MatchSource::IfLetDesugar { .. } => {
if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() && if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
arms[1].pats.len() == 1 && arms[1].guard.is_none() && arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
is_break_expr(&arms[1].body) is_break_expr(&arms[1].body)
@ -407,8 +403,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
} }
if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node { if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
let pat = &arms[0].pats[0].node; let pat = &arms[0].pats[0].node;
if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _), if let (
&ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node) &PatKind::TupleStruct(ref qpath, ref pat_args, _),
&ExprMethodCall(ref method_path, _, ref method_args),
) = (pat, &match_expr.node)
{ {
let iter_expr = &method_args[0]; let iter_expr = &method_args[0];
let lhs_constructor = last_path_segment(qpath); let lhs_constructor = last_path_segment(qpath);
@ -455,28 +453,25 @@ fn never_loop(block: &Block, id: &NodeId) -> bool {
fn contains_continue_block(block: &Block, dest: &NodeId) -> bool { fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) || block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
block.expr.as_ref().map_or( block
false, .expr
|e| contains_continue_expr(e, dest), .as_ref()
) .map_or(false, |e| contains_continue_expr(e, dest))
} }
fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool { fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
match stmt.node { match stmt.node {
StmtSemi(ref e, _) | StmtSemi(ref e, _) | StmtExpr(ref e, _) => contains_continue_expr(e, dest),
StmtExpr(ref e, _) => contains_continue_expr(e, dest),
StmtDecl(ref d, _) => contains_continue_decl(d, dest), StmtDecl(ref d, _) => contains_continue_decl(d, dest),
} }
} }
fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool { fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
match decl.node { match decl.node {
DeclLocal(ref local) => { DeclLocal(ref local) => local
local.init.as_ref().map_or( .init
false, .as_ref()
|e| contains_continue_expr(e, dest), .map_or(false, |e| contains_continue_expr(e, dest)),
)
},
_ => false, _ => false,
} }
} }
@ -492,9 +487,9 @@ fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
ExprTupField(ref e, _) | ExprTupField(ref e, _) |
ExprAddrOf(_, ref e) | ExprAddrOf(_, ref e) |
ExprRepeat(ref e, _) => contains_continue_expr(e, dest), ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
ExprArray(ref es) | ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => {
ExprMethodCall(_, _, ref es) | es.iter().any(|e| contains_continue_expr(e, dest))
ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)), },
ExprCall(ref e, ref es) => { ExprCall(ref e, ref es) => {
contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest)) contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
}, },
@ -502,22 +497,17 @@ fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
ExprAssign(ref e1, ref e2) | ExprAssign(ref e1, ref e2) |
ExprAssignOp(_, ref e1, ref e2) | ExprAssignOp(_, ref e1, ref e2) |
ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)), ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
ExprIf(ref e, ref e2, ref e3) => { ExprIf(ref e, ref e2, ref e3) => [e, e2]
[e, e2].iter().chain(e3.as_ref().iter()).any(|e| { .iter()
contains_continue_expr(e, dest) .chain(e3.as_ref().iter())
}) .any(|e| contains_continue_expr(e, dest)),
},
ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest), ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
ExprMatch(ref e, ref arms, _) => { ExprMatch(ref e, ref arms, _) => {
contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest)) contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
}, },
ExprBlock(ref block) => contains_continue_block(block, dest), ExprBlock(ref block) => contains_continue_block(block, dest),
ExprStruct(_, _, ref base) => { ExprStruct(_, _, ref base) => base.as_ref()
base.as_ref().map_or( .map_or(false, |e| contains_continue_expr(e, dest)),
false,
|e| contains_continue_expr(e, dest),
)
},
ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest), ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
_ => false, _ => false,
} }
@ -529,8 +519,7 @@ fn loop_exit_block(block: &Block) -> bool {
fn loop_exit_stmt(stmt: &Stmt) -> bool { fn loop_exit_stmt(stmt: &Stmt) -> bool {
match stmt.node { match stmt.node {
StmtSemi(ref e, _) | StmtSemi(ref e, _) | StmtExpr(ref e, _) => loop_exit_expr(e),
StmtExpr(ref e, _) => loop_exit_expr(e),
StmtDecl(ref d, _) => loop_exit_decl(d), StmtDecl(ref d, _) => loop_exit_decl(d),
} }
} }
@ -552,9 +541,7 @@ fn loop_exit_expr(expr: &Expr) -> bool {
ExprTupField(ref e, _) | ExprTupField(ref e, _) |
ExprAddrOf(_, ref e) | ExprAddrOf(_, ref e) |
ExprRepeat(ref e, _) => loop_exit_expr(e), ExprRepeat(ref e, _) => loop_exit_expr(e),
ExprArray(ref es) | ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
ExprMethodCall(_, _, ref es) |
ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)), ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
ExprBinary(_, ref e1, ref e2) | ExprBinary(_, ref e1, ref e2) |
ExprAssign(ref e1, ref e2) | ExprAssign(ref e1, ref e2) |
@ -613,9 +600,11 @@ fn check_for_loop_range<'a, 'tcx>(
// linting condition: we only indexed one variable // linting condition: we only indexed one variable
if visitor.indexed.len() == 1 { if visitor.indexed.len() == 1 {
let (indexed, indexed_extent) = visitor.indexed.into_iter().next().expect( let (indexed, indexed_extent) = visitor
"already checked that we have exactly 1 element", .indexed
); .into_iter()
.next()
.expect("already checked that we have exactly 1 element");
// ensure that the indexed variable was declared before the loop, see #601 // ensure that the indexed variable was declared before the loop, see #601
if let Some(indexed_extent) = indexed_extent { if let Some(indexed_extent) = indexed_extent {
@ -659,16 +648,22 @@ fn check_for_loop_range<'a, 'tcx>(
}; };
if visitor.nonindex { if visitor.nonindex {
span_lint_and_then(cx, span_lint_and_then(
cx,
NEEDLESS_RANGE_LOOP, NEEDLESS_RANGE_LOOP,
expr.span, expr.span,
&format!("the loop variable `{}` is used to index `{}`", ident.node, indexed), &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
|db| { |db| {
multispan_sugg(db, multispan_sugg(
db,
"consider using an iterator".to_string(), "consider using an iterator".to_string(),
vec![(pat.span, format!("({}, <item>)", ident.node)), vec![
(arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip))]); (pat.span, format!("({}, <item>)", ident.node)),
}); (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip)),
],
);
},
);
} else { } else {
let repl = if starts_at_zero && take.is_empty() { let repl = if starts_at_zero && take.is_empty() {
format!("&{}", indexed) format!("&{}", indexed)
@ -676,17 +671,19 @@ fn check_for_loop_range<'a, 'tcx>(
format!("{}.iter(){}{}", indexed, take, skip) format!("{}.iter(){}{}", indexed, take, skip)
}; };
span_lint_and_then(cx, span_lint_and_then(
cx,
NEEDLESS_RANGE_LOOP, NEEDLESS_RANGE_LOOP,
expr.span, expr.span,
&format!("the loop variable `{}` is only used to index `{}`.", &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
ident.node,
indexed),
|db| { |db| {
multispan_sugg(db, multispan_sugg(
db,
"consider using an iterator".to_string(), "consider using an iterator".to_string(),
vec![(pat.span, "<item>".to_string()), (arg.span, repl)]); vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
}); );
},
);
} }
} }
} }
@ -743,19 +740,25 @@ fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
".." ".."
}; };
span_lint_and_then(cx, span_lint_and_then(
cx,
REVERSE_RANGE_LOOP, REVERSE_RANGE_LOOP,
expr.span, expr.span,
"this range is empty so this for loop will never run", "this range is empty so this for loop will never run",
|db| { |db| {
db.span_suggestion(arg.span, db.span_suggestion(
arg.span,
"consider using the following if you are attempting to iterate over this \ "consider using the following if you are attempting to iterate over this \
range in reverse", range in reverse",
format!("({end}{dots}{start}).rev()", format!(
"({end}{dots}{start}).rev()",
end = end_snippet, end = end_snippet,
dots = dots, dots = dots,
start = start_snippet)); start = start_snippet
}); ),
);
},
);
} else if eq && limits != ast::RangeLimits::Closed { } else if eq && limits != ast::RangeLimits::Closed {
// if they are equal, it's also problematic - this loop // if they are equal, it's also problematic - this loop
// will never run. // will never run.
@ -894,14 +897,14 @@ fn check_for_loop_explicit_counter<'a, 'tcx>(
// For each candidate, check the parent block to see if // For each candidate, check the parent block to see if
// it's initialized to zero at the start of the loop. // it's initialized to zero at the start of the loop.
let map = &cx.tcx.hir; let map = &cx.tcx.hir;
let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| { let parent_scope = map.get_enclosing_scope(expr.id)
map.get_enclosing_scope(id) .and_then(|id| map.get_enclosing_scope(id));
});
if let Some(parent_id) = parent_scope { if let Some(parent_id) = parent_scope {
if let NodeBlock(block) = map.get(parent_id) { if let NodeBlock(block) = map.get(parent_id) {
for (id, _) in visitor.states.iter().filter( for (id, _) in visitor
|&(_, v)| *v == VarState::IncrOnce, .states
) .iter()
.filter(|&(_, v)| *v == VarState::IncrOnce)
{ {
let mut visitor2 = InitializeVisitor { let mut visitor2 = InitializeVisitor {
cx: cx, cx: cx,
@ -948,12 +951,10 @@ fn check_for_loop_over_map_kv<'a, 'tcx>(
if pat.len() == 2 { if pat.len() == 2 {
let arg_span = arg.span; let arg_span = arg.span;
let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty { let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
ty::TyRef(_, ref tam) => { ty::TyRef(_, ref tam) => match (&pat[0].node, &pat[1].node) {
match (&pat[0].node, &pat[1].node) {
(key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl), (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
(_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable), (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
_ => return, _ => return,
}
}, },
_ => return, _ => return,
}; };
@ -967,21 +968,26 @@ fn check_for_loop_over_map_kv<'a, 'tcx>(
}; };
if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) { if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
span_lint_and_then(cx, span_lint_and_then(
cx,
FOR_KV_MAP, FOR_KV_MAP,
expr.span, expr.span,
&format!("you seem to want to iterate on a map's {}s", kind), &format!("you seem to want to iterate on a map's {}s", kind),
|db| { |db| {
let map = sugg::Sugg::hir(cx, arg, "map"); let map = sugg::Sugg::hir(cx, arg, "map");
multispan_sugg(db, multispan_sugg(
db,
"use the corresponding method".into(), "use the corresponding method".into(),
vec![(pat_span, snippet(cx, new_pat_span, kind).into_owned()), vec![
(arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl))]); (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
}); (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
],
);
},
);
} }
} }
} }
} }
/// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`. /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
@ -1196,12 +1202,9 @@ fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
fn extract_first_expr(block: &Block) -> Option<&Expr> { fn extract_first_expr(block: &Block) -> Option<&Expr> {
match block.expr { match block.expr {
Some(ref expr) if block.stmts.is_empty() => Some(expr), Some(ref expr) if block.stmts.is_empty() => Some(expr),
None if !block.stmts.is_empty() => { None if !block.stmts.is_empty() => match block.stmts[0].node {
match block.stmts[0].node { StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
StmtExpr(ref expr, _) |
StmtSemi(ref expr, _) => Some(expr),
StmtDecl(..) => None, StmtDecl(..) => None,
}
}, },
_ => None, _ => None,
} }
@ -1211,11 +1214,9 @@ fn extract_first_expr(block: &Block) -> Option<&Expr> {
fn is_break_expr(expr: &Expr) -> bool { fn is_break_expr(expr: &Expr) -> bool {
match expr.node { match expr.node {
ExprBreak(dest, _) if dest.ident.is_none() => true, ExprBreak(dest, _) if dest.ident.is_none() => true,
ExprBlock(ref b) => { ExprBlock(ref b) => match extract_first_expr(b) {
match extract_first_expr(b) {
Some(subexpr) => is_break_expr(subexpr), Some(subexpr) => is_break_expr(subexpr),
None => false, None => false,
}
}, },
_ => false, _ => false,
} }
@ -1379,9 +1380,10 @@ fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
if let ExprPath(ref qpath) = expr.node { if let ExprPath(ref qpath) = expr.node {
let path_res = cx.tables.qpath_def(qpath, expr.hir_id); let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
if let Def::Local(def_id) = path_res { if let Def::Local(def_id) = path_res {
let node_id = cx.tcx.hir.as_local_node_id(def_id).expect( let node_id = cx.tcx
"That DefId should be valid", .hir
); .as_local_node_id(def_id)
.expect("That DefId should be valid");
return Some(node_id); return Some(node_id);
} }
} }
@ -1425,13 +1427,11 @@ fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool
return false; return false;
} }
match cx.tcx.hir.find(parent) { match cx.tcx.hir.find(parent) {
Some(NodeExpr(expr)) => { Some(NodeExpr(expr)) => match expr.node {
match expr.node {
ExprLoop(..) | ExprWhile(..) => { ExprLoop(..) | ExprWhile(..) => {
return true; return true;
}, },
_ => (), _ => (),
}
}, },
Some(NodeBlock(block)) => { Some(NodeBlock(block)) => {
let mut block_visitor = LoopNestVisitor { let mut block_visitor = LoopNestVisitor {
@ -1460,7 +1460,7 @@ enum Nesting {
LookFurther, // no nesting detected, no further walk required LookFurther, // no nesting detected, no further walk required
} }
use self::Nesting::{Unknown, RuledOut, LookFurther}; use self::Nesting::{LookFurther, RuledOut, Unknown};
struct LoopNestVisitor { struct LoopNestVisitor {
id: NodeId, id: NodeId,
@ -1486,11 +1486,8 @@ impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
return; return;
} }
match expr.node { match expr.node {
ExprAssign(ref path, _) | ExprAssign(ref path, _) | ExprAssignOp(_, ref path, _) => if match_var(path, self.iterator) {
ExprAssignOp(_, ref path, _) => {
if match_var(path, self.iterator) {
self.nesting = RuledOut; self.nesting = RuledOut;
}
}, },
_ => walk_expr(self, expr), _ => walk_expr(self, expr),
} }

View file

@ -2,8 +2,8 @@ use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::ty; use rustc::ty;
use syntax::ast; use syntax::ast;
use utils::{is_adjusted, match_qpath, match_trait_method, match_type, remove_blocks, paths, snippet, use utils::{is_adjusted, iter_input_pats, match_qpath, match_trait_method, match_type, paths, remove_blocks, snippet,
span_help_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, iter_input_pats}; span_help_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
/// **What it does:** Checks for mapping `clone()` over an iterator. /// **What it does:** Checks for mapping `clone()` over an iterator.
/// ///
@ -73,8 +73,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
} }
}} }}
}, },
ExprPath(ref path) => { ExprPath(ref path) => if match_qpath(path, &paths::CLONE) {
if match_qpath(path, &paths::CLONE) {
let type_name = get_type_name(cx, expr, &args[0]).unwrap_or("_"); let type_name = get_type_name(cx, expr, &args[0]).unwrap_or("_");
span_help_and_lint( span_help_and_lint(
cx, cx,
@ -87,7 +86,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
), ),
&format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")), &format!("try\n{}.cloned()", snippet(cx, args[0].span, "..")),
); );
}
}, },
_ => (), _ => (),
} }

View file

@ -11,8 +11,8 @@ use syntax::ast::LitKind;
use syntax::ast::NodeId; use syntax::ast::NodeId;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::paths; use utils::paths;
use utils::{match_type, snippet, span_note_and_lint, span_lint_and_then, span_lint_and_sugg, in_external_macro, use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_type, remove_blocks, snippet,
expr_block, walk_ptrs_ty, is_expn_of, remove_blocks, is_allowed}; span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
use utils::sugg::Sugg; use utils::sugg::Sugg;
/// **What it does:** Checks for matches with a single arm where an `if let` /// **What it does:** Checks for matches with a single arm where an `if let`
@ -290,21 +290,17 @@ fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
if let Some((true_expr, false_expr)) = exprs { if let Some((true_expr, false_expr)) = exprs {
let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) { let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
(false, false) => { (false, false) => Some(format!(
Some(format!(
"if {} {} else {}", "if {} {} else {}",
snippet(cx, ex.span, "b"), snippet(cx, ex.span, "b"),
expr_block(cx, true_expr, None, ".."), expr_block(cx, true_expr, None, ".."),
expr_block(cx, false_expr, None, "..") expr_block(cx, false_expr, None, "..")
)) )),
}, (false, true) => Some(format!(
(false, true) => {
Some(format!(
"if {} {}", "if {} {}",
snippet(cx, ex.span, "b"), snippet(cx, ex.span, "b"),
expr_block(cx, true_expr, None, "..") expr_block(cx, true_expr, None, "..")
)) )),
},
(true, false) => { (true, false) => {
let test = Sugg::hir(cx, ex, ".."); let test = Sugg::hir(cx, ex, "..");
Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, ".."))) Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
@ -317,7 +313,6 @@ fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
} }
} }
} }
}, },
); );
} }
@ -384,7 +379,8 @@ fn is_panic_block(block: &Block) -> bool {
fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) { fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
if has_only_ref_pats(arms) { if has_only_ref_pats(arms) {
if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node { if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
span_lint_and_then(cx, span_lint_and_then(
cx,
MATCH_REF_PATS, MATCH_REF_PATS,
expr.span, expr.span,
"you don't need to add `&` to both the expression and the patterns", "you don't need to add `&` to both the expression and the patterns",
@ -392,7 +388,8 @@ fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: Match
let inner = Sugg::hir(cx, inner, ".."); let inner = Sugg::hir(cx, inner, "..");
let template = match_template(expr.span, source, &inner); let template = match_template(expr.span, source, &inner);
db.span_suggestion(expr.span, "try", template); db.span_suggestion(expr.span, "try", template);
}); },
);
} else { } else {
span_lint_and_then( span_lint_and_then(
cx, cx,
@ -471,24 +468,18 @@ fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
ranges ranges
.iter() .iter()
.filter_map(|range| match range.node { .filter_map(|range| match range.node {
(ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => { (ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => Some(SpannedRange {
Some(SpannedRange {
span: range.span, span: range.span,
node: (start, Bound::Included(end)), node: (start, Bound::Included(end)),
}) }),
}, (ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => Some(SpannedRange {
(ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => {
Some(SpannedRange {
span: range.span, span: range.span,
node: (start, Bound::Excluded(end)), node: (start, Bound::Excluded(end)),
}) }),
}, (ConstVal::Integral(start), Bound::Unbounded) => Some(SpannedRange {
(ConstVal::Integral(start), Bound::Unbounded) => {
Some(SpannedRange {
span: range.span, span: range.span,
node: (start, Bound::Unbounded), node: (start, Bound::Unbounded),
}) }),
},
_ => None, _ => None,
}) })
.collect() .collect()
@ -540,8 +531,7 @@ where
impl<'a, T: Copy> Kind<'a, T> { impl<'a, T: Copy> Kind<'a, T> {
fn range(&self) -> &'a SpannedRange<T> { fn range(&self) -> &'a SpannedRange<T> {
match *self { match *self {
Kind::Start(_, r) | Kind::Start(_, r) | Kind::End(_, r) => r,
Kind::End(_, r) => r,
} }
} }
@ -562,22 +552,16 @@ where
impl<'a, T: Copy + Ord> Ord for Kind<'a, T> { impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
match (self.value(), other.value()) { match (self.value(), other.value()) {
(Bound::Included(a), Bound::Included(b)) | (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
(Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
// Range patterns cannot be unbounded (yet) // Range patterns cannot be unbounded (yet)
(Bound::Unbounded, _) | (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
(_, Bound::Unbounded) => unimplemented!(), (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
(Bound::Included(a), Bound::Excluded(b)) => {
match a.cmp(&b) {
Ordering::Equal => Ordering::Greater, Ordering::Equal => Ordering::Greater,
other => other, other => other,
}
}, },
(Bound::Excluded(a), Bound::Included(b)) => { (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
match a.cmp(&b) {
Ordering::Equal => Ordering::Less, Ordering::Equal => Ordering::Less,
other => other, other => other,
}
}, },
} }
} }
@ -594,10 +578,8 @@ where
for (a, b) in values.iter().zip(values.iter().skip(1)) { for (a, b) in values.iter().zip(values.iter().skip(1)) {
match (a, b) { match (a, b) {
(&Kind::Start(_, ra), &Kind::End(_, rb)) => { (&Kind::Start(_, ra), &Kind::End(_, rb)) => if ra.node != rb.node {
if ra.node != rb.node {
return Some((ra, rb)); return Some((ra, rb));
}
}, },
(&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (), (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
_ => return Some((a.range(), b.range())), _ => return Some((a.range(), b.range())),

View file

@ -39,8 +39,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemForget {
if match forgot_ty.ty_adt_def() { if match forgot_ty.ty_adt_def() {
Some(def) => def.has_dtor(cx.tcx), Some(def) => def.has_dtor(cx.tcx),
_ => false, _ => false,
} } {
{
span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type"); span_lint(cx, MEM_FORGET, e.span, "usage of mem::forget on Drop type");
} }
} }

View file

@ -8,10 +8,10 @@ use rustc_const_eval::ConstContext;
use std::borrow::Cow; use std::borrow::Cow;
use std::fmt; use std::fmt;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_qpath, match_trait_method, use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
match_type, method_chain_args, return_ty, same_tys, snippet, span_lint, span_lint_and_then, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
span_lint_and_sugg, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, last_path_segment, match_type, method_chain_args, return_ty, same_tys, single_segment_path, snippet, span_lint,
single_segment_path, match_def_path, is_self, is_self_ty, iter_input_pats, match_path}; span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
use utils::paths; use utils::paths;
use utils::sugg; use utils::sugg;
@ -618,12 +618,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
} }
match self_ty.sty { match self_ty.sty {
ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => { ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
for &(method, pos) in &PATTERN_METHODS {
if method_call.name == method && args.len() > pos { if method_call.name == method && args.len() > pos {
lint_single_char_pattern(cx, expr, &args[pos]); lint_single_char_pattern(cx, expr, &args[pos]);
} }
}
}, },
_ => (), _ => (),
} }
@ -723,8 +721,7 @@ fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir:
if ["default", "new"].contains(&path) { if ["default", "new"].contains(&path) {
let arg_ty = cx.tables.expr_ty(arg); let arg_ty = cx.tables.expr_ty(arg);
let default_trait_id = let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
default_trait_id default_trait_id
} else { } else {
return false; return false;
@ -771,8 +768,7 @@ fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, name: &str, args: &[hir:
} }
// (path, fn_has_argument, methods, suffix) // (path, fn_has_argument, methods, suffix)
let know_types: &[(&[_], _, &[_], _)] = let know_types: &[(&[_], _, &[_], _)] = &[
&[
(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"), (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
(&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"), (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
(&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"), (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
@ -1021,12 +1017,10 @@ fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::S
match ty.sty { match ty.sty {
ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr), ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr), ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => { ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
if may_slice(cx, inner) {
sugg::Sugg::hir_opt(cx, expr) sugg::Sugg::hir_opt(cx, expr)
} else { } else {
None None
}
}, },
_ => None, _ => None,
} }
@ -1459,22 +1453,22 @@ fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Gener
single_segment_ty(ty).map_or(false, |seg| { single_segment_ty(ty).map_or(false, |seg| {
generics.ty_params.iter().any(|param| { generics.ty_params.iter().any(|param| {
param.name == seg.name && param.name == seg.name &&
param.bounds.iter().any(|bound| { param
if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound { .bounds
.iter()
.any(|bound| if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
let path = &ptr.trait_ref.path; let path = &ptr.trait_ref.path;
match_path(path, name) && match_path(path, name) &&
path.segments.last().map_or( path.segments
false, .last()
|s| if s.parameters.parenthesized { .map_or(false, |s| if s.parameters.parenthesized {
false false
} else { } else {
s.parameters.types.len() == 1 && s.parameters.types.len() == 1 &&
(is_self_ty(&s.parameters.types[0]) || is_ty(&*s.parameters.types[0], self_ty)) (is_self_ty(&s.parameters.types[0]) || is_ty(&*s.parameters.types[0], self_ty))
}, })
)
} else { } else {
false false
}
}) })
}) })
}) })
@ -1482,12 +1476,14 @@ fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Gener
fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool { fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
match (&ty.node, &self_ty.node) { match (&ty.node, &self_ty.node) {
(&hir::TyPath(hir::QPath::Resolved(_, ref ty_path)), (
&hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path))) => { &hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
ty_path.segments.iter().map(|seg| seg.name).eq( &hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
self_ty_path.segments.iter().map(|seg| seg.name), ) => ty_path
) .segments
}, .iter()
.map(|seg| seg.name)
.eq(self_ty_path.segments.iter().map(|seg| seg.name)),
_ => false, _ => false,
} }
} }

View file

@ -1,7 +1,7 @@
use consts::{Constant, constant_simple}; use consts::{constant_simple, Constant};
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use std::cmp::{PartialOrd, Ordering}; use std::cmp::{Ordering, PartialOrd};
use utils::{match_def_path, paths, span_lint}; use utils::{match_def_path, paths, span_lint};
/// **What it does:** Checks for expressions where `std::cmp::min` and `max` are /// **What it does:** Checks for expressions where `std::cmp::min` and `max` are
@ -41,9 +41,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass {
return; return;
} }
match (outer_max, outer_c.partial_cmp(&inner_c)) { match (outer_max, outer_c.partial_cmp(&inner_c)) {
(_, None) | (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (),
(MinMax::Max, Some(Ordering::Less)) |
(MinMax::Min, Some(Ordering::Greater)) => (),
_ => { _ => {
span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result"); span_lint(cx, MIN_MAX, expr.span, "this min/max combination leads to constant result");
}, },

View file

@ -7,12 +7,12 @@ use rustc::ty;
use rustc::ty::subst::Substs; use rustc::ty::subst::Substs;
use rustc_const_eval::ConstContext; use rustc_const_eval::ConstContext;
use rustc_const_math::ConstFloat; use rustc_const_math::ConstFloat;
use syntax::codemap::{Span, ExpnFormat}; use syntax::codemap::{ExpnFormat, Span};
use utils::{get_item_name, get_parent_expr, implements_trait, in_macro, is_integer_literal, match_qpath, snippet, use utils::{get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal,
span_lint, span_lint_and_then, walk_ptrs_ty, last_path_segment, iter_input_pats, in_constant, iter_input_pats, last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint,
match_trait_method, paths}; span_lint_and_then, walk_ptrs_ty};
use utils::sugg::Sugg; use utils::sugg::Sugg;
use syntax::ast::{LitKind, CRATE_NODE_ID, FloatTy}; use syntax::ast::{FloatTy, LitKind, CRATE_NODE_ID};
/// **What it does:** Checks for function arguments and let bindings denoted as /// **What it does:** Checks for function arguments and let bindings denoted as
/// `ref`. /// `ref`.
@ -484,8 +484,7 @@ fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
return; return;
} }
}, },
ExprCall(ref path, ref v) if v.len() == 1 => { ExprCall(ref path, ref v) if v.len() == 1 => if let ExprPath(ref path) = path.node {
if let ExprPath(ref path) = path.node {
if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) { if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
(cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, "..")) (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
} else { } else {
@ -493,7 +492,6 @@ fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
} }
} else { } else {
return; return;
}
}, },
_ => return, _ => return,
}; };
@ -554,8 +552,7 @@ fn check_to_owned(cx: &LateContext, expr: &Expr, other: &Expr) {
fn is_used(cx: &LateContext, expr: &Expr) -> bool { fn is_used(cx: &LateContext, expr: &Expr) -> bool {
if let Some(parent) = get_parent_expr(cx, expr) { if let Some(parent) = get_parent_expr(cx, expr) {
match parent.node { match parent.node {
ExprAssign(_, ref rhs) | ExprAssign(_, ref rhs) | ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
ExprAssignOp(_, _, ref rhs) => **rhs == *expr,
_ => is_used(cx, parent), _ => is_used(cx, parent),
} }
} else { } else {
@ -567,20 +564,21 @@ fn is_used(cx: &LateContext, expr: &Expr) -> bool {
/// generated by /// generated by
/// `#[derive(...)`] or the like). /// `#[derive(...)`] or the like).
fn in_attributes_expansion(expr: &Expr) -> bool { fn in_attributes_expansion(expr: &Expr) -> bool {
expr.span.ctxt().outer().expn_info().map_or( expr.span
false, .ctxt()
|info| matches!(info.callee.format, ExpnFormat::MacroAttribute(_)), .outer()
) .expn_info()
.map_or(false, |info| matches!(info.callee.format, ExpnFormat::MacroAttribute(_)))
} }
/// Test whether `def` is a variable defined outside a macro. /// Test whether `def` is a variable defined outside a macro.
fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool { fn non_macro_local(cx: &LateContext, def: &def::Def) -> bool {
match *def { match *def {
def::Def::Local(def_id) | def::Def::Local(def_id) | def::Def::Upvar(def_id, _, _) => {
def::Def::Upvar(def_id, _, _) => { let id = cx.tcx
let id = cx.tcx.hir.as_local_node_id(def_id).expect( .hir
"local variables should be found in the same crate", .as_local_node_id(def_id)
); .expect("local variables should be found in the same crate");
!in_macro(cx.tcx.hir.span(id)) !in_macro(cx.tcx.hir.span(id))
}, },
_ => false, _ => false,

View file

@ -4,7 +4,7 @@ use std::char;
use syntax::ast::*; use syntax::ast::*;
use syntax::codemap::Span; use syntax::codemap::Span;
use syntax::visit::FnKind; use syntax::visit::FnKind;
use utils::{constants, span_lint, span_help_and_lint, snippet, snippet_opt, span_lint_and_then, in_external_macro}; use utils::{constants, in_external_macro, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
/// **What it does:** Checks for structure field patterns bound to wildcards. /// **What it does:** Checks for structure field patterns bound to wildcards.
/// ///
@ -293,29 +293,27 @@ impl EarlyLintPass for MiscEarly {
return; return;
} }
match expr.node { match expr.node {
ExprKind::Call(ref paren, _) => { ExprKind::Call(ref paren, _) => if let ExprKind::Paren(ref closure) = paren.node {
if let ExprKind::Paren(ref closure) = paren.node {
if let ExprKind::Closure(_, ref decl, ref block, _) = closure.node { if let ExprKind::Closure(_, ref decl, ref block, _) = closure.node {
span_lint_and_then(cx, span_lint_and_then(
cx,
REDUNDANT_CLOSURE_CALL, REDUNDANT_CLOSURE_CALL,
expr.span, expr.span,
"Try not to call a closure in the expression where it is declared.", "Try not to call a closure in the expression where it is declared.",
|db| if decl.inputs.is_empty() { |db| if decl.inputs.is_empty() {
let hint = snippet(cx, block.span, "..").into_owned(); let hint = snippet(cx, block.span, "..").into_owned();
db.span_suggestion(expr.span, "Try doing something like: ", hint); db.span_suggestion(expr.span, "Try doing something like: ", hint);
}); },
} );
} }
}, },
ExprKind::Unary(UnOp::Neg, ref inner) => { ExprKind::Unary(UnOp::Neg, ref inner) => if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
span_lint( span_lint(
cx, cx,
DOUBLE_NEG, DOUBLE_NEG,
expr.span, expr.span,
"`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op", "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
); );
}
}, },
ExprKind::Lit(ref lit) => self.check_lit(cx, lit), ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
_ => (), _ => (),

View file

@ -64,13 +64,15 @@ impl ::std::default::Default for MissingDoc {
impl MissingDoc { impl MissingDoc {
pub fn new() -> Self { pub fn new() -> Self {
Self { doc_hidden_stack: vec![false] } Self {
doc_hidden_stack: vec![false],
}
} }
fn doc_hidden(&self) -> bool { fn doc_hidden(&self) -> bool {
*self.doc_hidden_stack.last().expect( *self.doc_hidden_stack
"empty doc_hidden_stack", .last()
) .expect("empty doc_hidden_stack")
} }
fn check_missing_docs_attrs(&self, cx: &LateContext, attrs: &[ast::Attribute], sp: Span, desc: &'static str) { fn check_missing_docs_attrs(&self, cx: &LateContext, attrs: &[ast::Attribute], sp: Span, desc: &'static str) {
@ -89,9 +91,9 @@ impl MissingDoc {
return; return;
} }
let has_doc = attrs.iter().any(|a| { let has_doc = attrs
a.is_value_str() && a.name().map_or(false, |n| n == "doc") .iter()
}); .any(|a| a.is_value_str() && a.name().map_or(false, |n| n == "doc"));
if !has_doc { if !has_doc {
cx.span_lint( cx.span_lint(
MISSING_DOCS_IN_PRIVATE_ITEMS, MISSING_DOCS_IN_PRIVATE_ITEMS,
@ -110,10 +112,8 @@ impl LintPass for MissingDoc {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
fn enter_lint_attrs(&mut self, _: &LateContext<'a, 'tcx>, attrs: &'tcx [ast::Attribute]) { fn enter_lint_attrs(&mut self, _: &LateContext<'a, 'tcx>, attrs: &'tcx [ast::Attribute]) {
let doc_hidden = self.doc_hidden() || let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
attrs.iter().any(|attr| { attr.check_name("doc") && match attr.meta_item_list() {
attr.check_name("doc") &&
match attr.meta_item_list() {
None => false, None => false,
Some(l) => attr::list_contains_name(&l[..], "hidden"), Some(l) => attr::list_contains_name(&l[..], "hidden"),
} }
@ -166,10 +166,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
let def_id = cx.tcx.hir.local_def_id(impl_item.id); let def_id = cx.tcx.hir.local_def_id(impl_item.id);
match cx.tcx.associated_item(def_id).container { match cx.tcx.associated_item(def_id).container {
ty::TraitContainer(_) => return, ty::TraitContainer(_) => return,
ty::ImplContainer(cid) => { ty::ImplContainer(cid) => if cx.tcx.impl_trait_ref(cid).is_some() {
if cx.tcx.impl_trait_ref(cid).is_some() {
return; return;
}
}, },
} }

View file

@ -70,7 +70,14 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
expr.span, expr.span,
"generally you want to avoid `&mut &mut _` if possible", "generally you want to avoid `&mut &mut _` if possible",
); );
} else if let ty::TyRef(_, ty::TypeAndMut { mutbl: hir::MutMutable, .. }) = self.cx.tables.expr_ty(e).sty { } else if let ty::TyRef(
_,
ty::TypeAndMut {
mutbl: hir::MutMutable,
..
},
) = self.cx.tables.expr_ty(e).sty
{
span_lint( span_lint(
self.cx, self.cx,
MUT_MUT, MUT_MUT,
@ -82,13 +89,22 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
} }
fn visit_ty(&mut self, ty: &'tcx hir::Ty) { fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
if let hir::TyRptr(_, if let hir::TyRptr(
_,
hir::MutTy { hir::MutTy {
ty: ref pty, ty: ref pty,
mutbl: hir::MutMutable, mutbl: hir::MutMutable,
}) = ty.node },
) = ty.node
{
if let hir::TyRptr(
_,
hir::MutTy {
mutbl: hir::MutMutable,
..
},
) = pty.node
{ {
if let hir::TyRptr(_, hir::MutTy { mutbl: hir::MutMutable, .. }) = pty.node {
span_lint( span_lint(
self.cx, self.cx,
MUT_MUT, MUT_MUT,
@ -96,7 +112,6 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
"generally you want to avoid `&mut &mut _` if possible", "generally you want to avoid `&mut &mut _` if possible",
); );
} }
} }
intravisit::walk_ty(self, ty); intravisit::walk_ty(self, ty);

View file

@ -36,15 +36,13 @@ impl LintPass for UnnecessaryMutPassed {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnecessaryMutPassed { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnecessaryMutPassed {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
match e.node { match e.node {
ExprCall(ref fn_expr, ref arguments) => { ExprCall(ref fn_expr, ref arguments) => if let ExprPath(ref path) = fn_expr.node {
if let ExprPath(ref path) = fn_expr.node {
check_arguments( check_arguments(
cx, cx,
arguments, arguments,
cx.tables.expr_ty(fn_expr), cx.tables.expr_ty(fn_expr),
&print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)), &print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
); );
}
}, },
ExprMethodCall(ref path, _, ref arguments) => { ExprMethodCall(ref path, _, ref arguments) => {
let def_id = cx.tables.type_dependent_defs()[e.hir_id].def_id(); let def_id = cx.tables.type_dependent_defs()[e.hir_id].def_id();
@ -63,16 +61,23 @@ fn check_arguments<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arguments: &[Expr], typ
let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs(); let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
for (argument, parameter) in arguments.iter().zip(parameters.iter()) { for (argument, parameter) in arguments.iter().zip(parameters.iter()) {
match parameter.sty { match parameter.sty {
ty::TyRef(_, ty::TypeAndMut { mutbl: MutImmutable, .. }) | ty::TyRef(
ty::TyRawPtr(ty::TypeAndMut { mutbl: MutImmutable, .. }) => { _,
if let ExprAddrOf(MutMutable, _) = argument.node { ty::TypeAndMut {
mutbl: MutImmutable,
..
},
) |
ty::TyRawPtr(ty::TypeAndMut {
mutbl: MutImmutable,
..
}) => if let ExprAddrOf(MutMutable, _) = argument.node {
span_lint( span_lint(
cx, cx,
UNNECESSARY_MUT_PASSED, UNNECESSARY_MUT_PASSED,
argument.span, argument.span,
&format!("The function/method `{}` doesn't need a mutable reference", name), &format!("The function/method `{}` doesn't need a mutable reference", name),
); );
}
}, },
_ => (), _ => (),
} }

View file

@ -2,7 +2,7 @@
//! //!
//! This lint is **warn** by default //! This lint is **warn** by default
use rustc::lint::{LintPass, LintArray, LateLintPass, LateContext}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::ty::{self, Ty}; use rustc::ty::{self, Ty};
use rustc::hir::Expr; use rustc::hir::Expr;
use syntax::ast; use syntax::ast;

View file

@ -6,7 +6,7 @@ use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use syntax::ast::LitKind; use syntax::ast::LitKind;
use syntax::codemap::Spanned; use syntax::codemap::Spanned;
use utils::{span_lint, span_lint_and_sugg, snippet}; use utils::{snippet, span_lint, span_lint_and_sugg};
use utils::sugg::Sugg; use utils::sugg::Sugg;
/// **What it does:** Checks for expressions of the form `if c { true } else { /// **What it does:** Checks for expressions of the form `if c { true } else {
@ -82,8 +82,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
}; };
if let ExprBlock(ref then_block) = then_block.node { if let ExprBlock(ref then_block) = then_block.node {
match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) { match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
(RetBool(true), RetBool(true)) | (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
(Bool(true), Bool(true)) => {
span_lint( span_lint(
cx, cx,
NEEDLESS_BOOL, NEEDLESS_BOOL,
@ -91,8 +90,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
"this if-then-else expression will always return true", "this if-then-else expression will always return true",
); );
}, },
(RetBool(false), RetBool(false)) | (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
(Bool(false), Bool(false)) => {
span_lint( span_lint(
cx, cx,
NEEDLESS_BOOL, NEEDLESS_BOOL,
@ -186,8 +184,7 @@ enum Expression {
fn fetch_bool_block(block: &Block) -> Expression { fn fetch_bool_block(block: &Block) -> Expression {
match (&*block.stmts, block.expr.as_ref()) { match (&*block.stmts, block.expr.as_ref()) {
(&[], Some(e)) => fetch_bool_expr(&**e), (&[], Some(e)) => fetch_bool_expr(&**e),
(&[ref e], None) => { (&[ref e], None) => if let StmtSemi(ref e, _) = e.node {
if let StmtSemi(ref e, _) = e.node {
if let ExprRet(_) = e.node { if let ExprRet(_) = e.node {
fetch_bool_expr(&**e) fetch_bool_expr(&**e)
} else { } else {
@ -195,7 +192,6 @@ fn fetch_bool_block(block: &Block) -> Expression {
} }
} else { } else {
Expression::Other Expression::Other
}
}, },
_ => Expression::Other, _ => Expression::Other,
} }
@ -204,18 +200,14 @@ fn fetch_bool_block(block: &Block) -> Expression {
fn fetch_bool_expr(expr: &Expr) -> Expression { fn fetch_bool_expr(expr: &Expr) -> Expression {
match expr.node { match expr.node {
ExprBlock(ref block) => fetch_bool_block(block), ExprBlock(ref block) => fetch_bool_block(block),
ExprLit(ref lit_ptr) => { ExprLit(ref lit_ptr) => if let LitKind::Bool(value) = lit_ptr.node {
if let LitKind::Bool(value) = lit_ptr.node {
Expression::Bool(value) Expression::Bool(value)
} else { } else {
Expression::Other Expression::Other
}
}, },
ExprRet(Some(ref expr)) => { ExprRet(Some(ref expr)) => match fetch_bool_expr(expr) {
match fetch_bool_expr(expr) {
Expression::Bool(value) => Expression::RetBool(value), Expression::Bool(value) => Expression::RetBool(value),
_ => Expression::Other, _ => Expression::Other,
}
}, },
_ => Expression::Other, _ => Expression::Other,
} }

View file

@ -3,10 +3,10 @@
//! This lint is **warn** by default //! This lint is **warn** by default
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::{ExprAddrOf, Expr, MutImmutable, Pat, PatKind, BindingAnnotation}; use rustc::hir::{BindingAnnotation, Expr, ExprAddrOf, MutImmutable, Pat, PatKind};
use rustc::ty; use rustc::ty;
use rustc::ty::adjustment::{Adjustment, Adjust}; use rustc::ty::adjustment::{Adjust, Adjustment};
use utils::{span_lint, in_macro}; use utils::{in_macro, span_lint};
/// **What it does:** Checks for address of operations (`&`) that are going to /// **What it does:** Checks for address of operations (`&`) that are going to
/// be dereferenced immediately by the compiler. /// be dereferenced immediately by the compiler.
@ -43,16 +43,24 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow {
if let ExprAddrOf(MutImmutable, ref inner) = e.node { if let ExprAddrOf(MutImmutable, ref inner) = e.node {
if let ty::TyRef(..) = cx.tables.expr_ty(inner).sty { if let ty::TyRef(..) = cx.tables.expr_ty(inner).sty {
for adj3 in cx.tables.expr_adjustments(e).windows(3) { for adj3 in cx.tables.expr_adjustments(e).windows(3) {
if let [ if let [Adjustment {
Adjustment { kind: Adjust::Deref(_), .. }, kind: Adjust::Deref(_),
Adjustment { kind: Adjust::Deref(_), .. }, ..
Adjustment { kind: Adjust::Borrow(_), .. } }, Adjustment {
] = *adj3 { kind: Adjust::Deref(_),
span_lint(cx, ..
}, Adjustment {
kind: Adjust::Borrow(_),
..
}] = *adj3
{
span_lint(
cx,
NEEDLESS_BORROW, NEEDLESS_BORROW,
e.span, e.span,
"this expression borrows a reference that is immediately dereferenced by the \ "this expression borrows a reference that is immediately dereferenced by the \
compiler"); compiler",
);
} }
} }
} }

View file

@ -3,8 +3,8 @@
//! This lint is **warn** by default //! This lint is **warn** by default
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::{MutImmutable, Pat, PatKind, BindingAnnotation}; use rustc::hir::{BindingAnnotation, MutImmutable, Pat, PatKind};
use utils::{span_lint_and_then, in_macro, snippet}; use utils::{in_macro, snippet, span_lint_and_then};
/// **What it does:** Checks for useless borrowed references. /// **What it does:** Checks for useless borrowed references.
/// ///

View file

@ -32,7 +32,7 @@ use syntax::ast;
use syntax::codemap::{original_sp, DUMMY_SP}; use syntax::codemap::{original_sp, DUMMY_SP};
use std::borrow::Cow; use std::borrow::Cow;
use utils::{in_macro, span_help_and_lint, snippet_block, snippet, trim_multiline}; use utils::{in_macro, snippet, snippet_block, span_help_and_lint, trim_multiline};
/// **What it does:** The lint checks for `if`-statements appearing in loops /// **What it does:** The lint checks for `if`-statements appearing in loops
/// that contain a `continue` statement in either their main blocks or their /// that contain a `continue` statement in either their main blocks or their
@ -181,13 +181,10 @@ fn needless_continue_in_else(else_expr: &ast::Expr) -> bool {
fn is_first_block_stmt_continue(block: &ast::Block) -> bool { fn is_first_block_stmt_continue(block: &ast::Block) -> bool {
block.stmts.get(0).map_or(false, |stmt| match stmt.node { block.stmts.get(0).map_or(false, |stmt| match stmt.node {
ast::StmtKind::Semi(ref e) | ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => if let ast::ExprKind::Continue(_) = e.node {
ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::Continue(_) = e.node {
true true
} else { } else {
false false
}
}, },
_ => false, _ => false,
}) })
@ -222,8 +219,7 @@ where
F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr), F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
{ {
match stmt.node { match stmt.node {
ast::StmtKind::Semi(ref e) | ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node { if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
func(e, cond, if_block, else_expr); func(e, cond, if_block, else_expr);
} }
@ -269,25 +265,20 @@ const DROP_ELSE_BLOCK_MSG: &'static str = "Consider dropping the else clause, an
fn emit_warning<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str, typ: LintType) { fn emit_warning<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str, typ: LintType) {
// snip is the whole *help* message that appears after the warning. // snip is the whole *help* message that appears after the warning.
// message is the warning message. // message is the warning message.
// expr is the expression which the lint warning message refers to. // expr is the expression which the lint warning message refers to.
let (snip, message, expr) = match typ { let (snip, message, expr) = match typ {
LintType::ContinueInsideElseBlock => { LintType::ContinueInsideElseBlock => (
(
suggestion_snippet_for_continue_inside_else(ctx, data, header), suggestion_snippet_for_continue_inside_else(ctx, data, header),
MSG_REDUNDANT_ELSE_BLOCK, MSG_REDUNDANT_ELSE_BLOCK,
data.else_expr, data.else_expr,
) ),
}, LintType::ContinueInsideThenBlock => (
LintType::ContinueInsideThenBlock => {
(
suggestion_snippet_for_continue_inside_if(ctx, data, header), suggestion_snippet_for_continue_inside_if(ctx, data, header),
MSG_ELSE_BLOCK_NOT_NEEDED, MSG_ELSE_BLOCK_NOT_NEEDED,
data.if_expr, data.if_expr,
) ),
},
}; };
span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip); span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
} }

View file

@ -9,9 +9,9 @@ use rustc::middle::mem_categorization as mc;
use syntax::ast::NodeId; use syntax::ast::NodeId;
use syntax_pos::Span; use syntax_pos::Span;
use syntax::errors::DiagnosticBuilder; use syntax::errors::DiagnosticBuilder;
use utils::{in_macro, is_self, is_copy, implements_trait, get_trait_def_id, match_type, snippet, span_lint_and_then, use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
multispan_sugg, paths}; snippet, span_lint_and_then};
use std::collections::{HashSet, HashMap}; use std::collections::{HashMap, HashSet};
/// **What it does:** Checks for functions taking arguments by value, but not /// **What it does:** Checks for functions taking arguments by value, but not
/// consuming them in its /// consuming them in its
@ -62,8 +62,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
} }
match kind { match kind {
FnKind::ItemFn(.., attrs) => { FnKind::ItemFn(.., attrs) => for a in attrs {
for a in attrs {
if_let_chain!{[ if_let_chain!{[
a.meta_item_list().is_some(), a.meta_item_list().is_some(),
let Some(name) = a.name(), let Some(name) = a.name(),
@ -71,7 +70,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
], { ], {
return; return;
}} }}
}
}, },
_ => return, _ => return,
} }
@ -106,7 +104,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig); let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) { for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
// Determines whether `ty` implements `Borrow<U>` (U != ty) specifically. // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
// This is needed due to the `Borrow<T> for T` blanket impl. // This is needed due to the `Borrow<T> for T` blanket impl.
let implements_borrow_trait = preds let implements_borrow_trait = preds
@ -118,9 +115,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
}) })
.filter(|tpred| tpred.def_id() == borrow_trait && tpred.self_ty() == ty) .filter(|tpred| tpred.def_id() == borrow_trait && tpred.self_ty() == ty)
.any(|tpred| { .any(|tpred| {
tpred.input_types().nth(1).expect( tpred
"Borrow trait must have an parameter", .input_types()
) != ty .nth(1)
.expect("Borrow trait must have an parameter") != ty
}); });
if_let_chain! {[ if_let_chain! {[
@ -299,8 +297,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt { fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
loop { loop {
match cmt.cat.clone() { match cmt.cat.clone() {
mc::Categorization::Downcast(c, _) | mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {
mc::Categorization::Interior(c, _) => {
cmt = c; cmt = c;
}, },
_ => return cmt, _ => return cmt,

View file

@ -115,9 +115,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
return; return;
} }
if decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) { if decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
let self_ty = cx.tcx.type_of( let self_ty = cx.tcx
cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)), .type_of(cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)));
);
if_let_chain!{[ if_let_chain!{[
same_tys(cx, self_ty, return_ty(cx, id)), same_tys(cx, self_ty, return_ty(cx, id)),
let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT), let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT),

View file

@ -1,7 +1,7 @@
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::hir::def::Def; use rustc::hir::def::Def;
use rustc::hir::{Expr, Expr_, Stmt, StmtSemi, BlockCheckMode, UnsafeSource, BiAnd, BiOr}; use rustc::hir::{BiAnd, BiOr, BlockCheckMode, Expr, Expr_, Stmt, StmtSemi, UnsafeSource};
use utils::{in_macro, span_lint, snippet_opt, span_lint_and_sugg}; use utils::{in_macro, snippet_opt, span_lint, span_lint_and_sugg};
use std::ops::Deref; use std::ops::Deref;
/// **What it does:** Checks for statements which have no effect. /// **What it does:** Checks for statements which have no effect.
@ -45,13 +45,11 @@ fn has_no_effect(cx: &LateContext, expr: &Expr) -> bool {
return false; return false;
} }
match expr.node { match expr.node {
Expr_::ExprLit(..) | Expr_::ExprLit(..) | Expr_::ExprClosure(.., _) | Expr_::ExprPath(..) => true,
Expr_::ExprClosure(.., _) | Expr_::ExprIndex(ref a, ref b) | Expr_::ExprBinary(_, ref a, ref b) => {
Expr_::ExprPath(..) => true, has_no_effect(cx, a) && has_no_effect(cx, b)
Expr_::ExprIndex(ref a, ref b) | },
Expr_::ExprBinary(_, ref a, ref b) => has_no_effect(cx, a) && has_no_effect(cx, b), Expr_::ExprArray(ref v) | Expr_::ExprTup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
Expr_::ExprArray(ref v) |
Expr_::ExprTup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
Expr_::ExprRepeat(ref inner, _) | Expr_::ExprRepeat(ref inner, _) |
Expr_::ExprCast(ref inner, _) | Expr_::ExprCast(ref inner, _) |
Expr_::ExprType(ref inner, _) | Expr_::ExprType(ref inner, _) |
@ -61,29 +59,24 @@ fn has_no_effect(cx: &LateContext, expr: &Expr) -> bool {
Expr_::ExprAddrOf(_, ref inner) | Expr_::ExprAddrOf(_, ref inner) |
Expr_::ExprBox(ref inner) => has_no_effect(cx, inner), Expr_::ExprBox(ref inner) => has_no_effect(cx, inner),
Expr_::ExprStruct(_, ref fields, ref base) => { Expr_::ExprStruct(_, ref fields, ref base) => {
fields.iter().all(|field| has_no_effect(cx, &field.expr)) && fields.iter().all(|field| has_no_effect(cx, &field.expr)) && match *base {
match *base {
Some(ref base) => has_no_effect(cx, base), Some(ref base) => has_no_effect(cx, base),
None => true, None => true,
} }
}, },
Expr_::ExprCall(ref callee, ref args) => { Expr_::ExprCall(ref callee, ref args) => if let Expr_::ExprPath(ref qpath) = callee.node {
if let Expr_::ExprPath(ref qpath) = callee.node {
let def = cx.tables.qpath_def(qpath, callee.hir_id); let def = cx.tables.qpath_def(qpath, callee.hir_id);
match def { match def {
Def::Struct(..) | Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
Def::Variant(..) | args.iter().all(|arg| has_no_effect(cx, arg))
Def::StructCtor(..) | },
Def::VariantCtor(..) => args.iter().all(|arg| has_no_effect(cx, arg)),
_ => false, _ => false,
} }
} else { } else {
false false
}
}, },
Expr_::ExprBlock(ref block) => { Expr_::ExprBlock(ref block) => {
block.stmts.is_empty() && block.stmts.is_empty() && if let Some(ref expr) = block.expr {
if let Some(ref expr) = block.expr {
has_no_effect(cx, expr) has_no_effect(cx, expr)
} else { } else {
false false
@ -143,8 +136,7 @@ fn reduce_expression<'a>(cx: &LateContext, expr: &'a Expr) -> Option<Vec<&'a Exp
Expr_::ExprBinary(ref binop, ref a, ref b) if binop.node != BiAnd && binop.node != BiOr => { Expr_::ExprBinary(ref binop, ref a, ref b) if binop.node != BiAnd && binop.node != BiOr => {
Some(vec![&**a, &**b]) Some(vec![&**a, &**b])
}, },
Expr_::ExprArray(ref v) | Expr_::ExprArray(ref v) | Expr_::ExprTup(ref v) => Some(v.iter().collect()),
Expr_::ExprTup(ref v) => Some(v.iter().collect()),
Expr_::ExprRepeat(ref inner, _) | Expr_::ExprRepeat(ref inner, _) |
Expr_::ExprCast(ref inner, _) | Expr_::ExprCast(ref inner, _) |
Expr_::ExprType(ref inner, _) | Expr_::ExprType(ref inner, _) |
@ -153,29 +145,24 @@ fn reduce_expression<'a>(cx: &LateContext, expr: &'a Expr) -> Option<Vec<&'a Exp
Expr_::ExprTupField(ref inner, _) | Expr_::ExprTupField(ref inner, _) |
Expr_::ExprAddrOf(_, ref inner) | Expr_::ExprAddrOf(_, ref inner) |
Expr_::ExprBox(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])), Expr_::ExprBox(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
Expr_::ExprStruct(_, ref fields, ref base) => { Expr_::ExprStruct(_, ref fields, ref base) => Some(
Some(
fields fields
.iter() .iter()
.map(|f| &f.expr) .map(|f| &f.expr)
.chain(base) .chain(base)
.map(Deref::deref) .map(Deref::deref)
.collect(), .collect(),
) ),
}, Expr_::ExprCall(ref callee, ref args) => if let Expr_::ExprPath(ref qpath) = callee.node {
Expr_::ExprCall(ref callee, ref args) => {
if let Expr_::ExprPath(ref qpath) = callee.node {
let def = cx.tables.qpath_def(qpath, callee.hir_id); let def = cx.tables.qpath_def(qpath, callee.hir_id);
match def { match def {
Def::Struct(..) | Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
Def::Variant(..) | Some(args.iter().collect())
Def::StructCtor(..) | },
Def::VariantCtor(..) => Some(args.iter().collect()),
_ => None, _ => None,
} }
} else { } else {
None None
}
}, },
Expr_::ExprBlock(ref block) => { Expr_::ExprBlock(ref block) => {
if block.stmts.is_empty() { if block.stmts.is_empty() {

View file

@ -3,8 +3,8 @@ use syntax::codemap::Span;
use syntax::symbol::InternedString; use syntax::symbol::InternedString;
use syntax::ast::*; use syntax::ast::*;
use syntax::attr; use syntax::attr;
use syntax::visit::{Visitor, walk_block, walk_pat, walk_expr}; use syntax::visit::{walk_block, walk_expr, walk_pat, Visitor};
use utils::{span_lint_and_then, in_macro, span_lint}; use utils::{in_macro, span_lint, span_lint_and_then};
/// **What it does:** Checks for names that are very similar and thus confusing. /// **What it does:** Checks for names that are very similar and thus confusing.
/// ///
@ -82,12 +82,10 @@ impl<'a, 'tcx: 'a, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
fn visit_pat(&mut self, pat: &'tcx Pat) { fn visit_pat(&mut self, pat: &'tcx Pat) {
match pat.node { match pat.node {
PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name), PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name),
PatKind::Struct(_, ref fields, _) => { PatKind::Struct(_, ref fields, _) => for field in fields {
for field in fields {
if !field.node.is_shorthand { if !field.node.is_shorthand {
self.visit_pat(&field.node.pat); self.visit_pat(&field.node.pat);
} }
}
}, },
_ => walk_pat(self, pat), _ => walk_pat(self, pat),
} }
@ -104,9 +102,8 @@ fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
} }
fn whitelisted(interned_name: &str, list: &[&str]) -> bool { fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
list.iter().any(|&name| { list.iter()
interned_name.starts_with(name) || interned_name.ends_with(name) .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
})
} }
impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> { impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
@ -157,21 +154,21 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
} else { } else {
let mut interned_chars = interned_name.chars(); let mut interned_chars = interned_name.chars();
let mut existing_chars = existing_name.interned.chars(); let mut existing_chars = existing_name.interned.chars();
let first_i = interned_chars.next().expect( let first_i = interned_chars
"we know we have at least one char", .next()
); .expect("we know we have at least one char");
let first_e = existing_chars.next().expect( let first_e = existing_chars
"we know we have at least one char", .next()
); .expect("we know we have at least one char");
let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric(); let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
if eq_or_numeric((first_i, first_e)) { if eq_or_numeric((first_i, first_e)) {
let last_i = interned_chars.next_back().expect( let last_i = interned_chars
"we know we have at least two chars", .next_back()
); .expect("we know we have at least two chars");
let last_e = existing_chars.next_back().expect( let last_e = existing_chars
"we know we have at least two chars", .next_back()
); .expect("we know we have at least two chars");
if eq_or_numeric((last_i, last_e)) { if eq_or_numeric((last_i, last_e)) {
if interned_chars if interned_chars
.zip(existing_chars) .zip(existing_chars)
@ -181,12 +178,12 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
continue; continue;
} }
} else { } else {
let second_last_i = interned_chars.next_back().expect( let second_last_i = interned_chars
"we know we have at least three chars", .next_back()
); .expect("we know we have at least three chars");
let second_last_e = existing_chars.next_back().expect( let second_last_e = existing_chars
"we know we have at least three chars", .next_back()
); .expect("we know we have at least three chars");
if !eq_or_numeric((second_last_i, second_last_e)) || second_last_i == '_' || if !eq_or_numeric((second_last_i, second_last_e)) || second_last_i == '_' ||
!interned_chars.zip(existing_chars).all(eq_or_numeric) !interned_chars.zip(existing_chars).all(eq_or_numeric)
{ {
@ -197,12 +194,12 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
split_at = interned_name.char_indices().rev().next().map(|(i, _)| i); split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
} }
} else { } else {
let second_i = interned_chars.next().expect( let second_i = interned_chars
"we know we have at least two chars", .next()
); .expect("we know we have at least two chars");
let second_e = existing_chars.next().expect( let second_e = existing_chars
"we know we have at least two chars", .next()
); .expect("we know we have at least two chars");
if !eq_or_numeric((second_i, second_e)) || second_i == '_' || if !eq_or_numeric((second_i, second_e)) || second_i == '_' ||
!interned_chars.zip(existing_chars).all(eq_or_numeric) !interned_chars.zip(existing_chars).all(eq_or_numeric)
{ {

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{paths, method_chain_args, span_help_and_lint, match_type, snippet}; use utils::{match_type, method_chain_args, paths, snippet, span_help_and_lint};
/// **What it does:*** Checks for unnecessary `ok()` in if let. /// **What it does:*** Checks for unnecessary `ok()` in if let.
/// ///

View file

@ -1,4 +1,4 @@
use rustc::hir::{Expr, ExprMethodCall, ExprLit}; use rustc::hir::{Expr, ExprLit, ExprMethodCall};
use rustc::lint::*; use rustc::lint::*;
use syntax::ast::LitKind; use syntax::ast::LitKind;
use syntax::codemap::{Span, Spanned}; use syntax::codemap::{Span, Spanned};
@ -67,11 +67,18 @@ fn get_open_options(cx: &LateContext, argument: &Expr, options: &mut Vec<(OpenOp
// Only proceed if this is a call on some object of type std::fs::OpenOptions // Only proceed if this is a call on some object of type std::fs::OpenOptions
if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 2 { if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 2 {
let argument_option = match arguments[1].node { let argument_option = match arguments[1].node {
ExprLit(ref span) => { ExprLit(ref span) => {
if let Spanned { node: LitKind::Bool(lit), .. } = **span { if let Spanned {
if lit { Argument::True } else { Argument::False } node: LitKind::Bool(lit),
..
} = **span
{
if lit {
Argument::True
} else {
Argument::False
}
} else { } else {
return; // The function is called with a literal return; // The function is called with a literal
// which is not a boolean literal. This is theoretically // which is not a boolean literal. This is theoretically

View file

@ -1,7 +1,7 @@
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::*; use rustc::lint::*;
use syntax::ast::LitKind; use syntax::ast::LitKind;
use utils::{is_direct_expn_of, match_def_path, resolve_node, paths, span_lint}; use utils::{is_direct_expn_of, match_def_path, paths, resolve_node, span_lint};
/// **What it does:** Checks for missing parameters in `panic!`. /// **What it does:** Checks for missing parameters in `panic!`.
/// ///

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use syntax::ast::*; use syntax::ast::*;
use syntax::codemap::Spanned; use syntax::codemap::Spanned;
use utils::{span_lint_and_sugg, snippet}; use utils::{snippet, span_lint_and_sugg};
/// **What it does:** Checks for operations where precedence may be unclear /// **What it does:** Checks for operations where precedence may be unclear
/// and suggests to add parentheses. Currently it catches the following: /// and suggests to add parentheses. Currently it catches the following:
@ -89,9 +89,7 @@ impl EarlyLintPass for Precedence {
if let Some(slf) = args.first() { if let Some(slf) = args.first() {
if let ExprKind::Lit(ref lit) = slf.node { if let ExprKind::Lit(ref lit) = slf.node {
match lit.node { match lit.node {
LitKind::Int(..) | LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
LitKind::Float(..) |
LitKind::FloatUnsuffixed(..) => {
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
PRECEDENCE, PRECEDENCE,

View file

@ -1,8 +1,8 @@
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::map::Node::{NodeItem, NodeImplItem}; use rustc::hir::map::Node::{NodeImplItem, NodeItem};
use rustc::lint::*; use rustc::lint::*;
use utils::paths; use utils::paths;
use utils::{is_expn_of, match_def_path, resolve_node, span_lint, match_path}; use utils::{is_expn_of, match_def_path, match_path, resolve_node, span_lint};
use format::get_argument_fmtstr_parts; use format::get_argument_fmtstr_parts;
/// **What it does:** This lint warns when you using `print!()` with a format /// **What it does:** This lint warns when you using `print!()` with a format

View file

@ -128,11 +128,13 @@ fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId) {
let fn_ty = sig.skip_binder(); let fn_ty = sig.skip_binder();
for (arg, ty) in decl.inputs.iter().zip(fn_ty.inputs()) { for (arg, ty) in decl.inputs.iter().zip(fn_ty.inputs()) {
if let ty::TyRef(_, if let ty::TyRef(
_,
ty::TypeAndMut { ty::TypeAndMut {
ty, ty,
mutbl: MutImmutable, mutbl: MutImmutable,
}) = ty.sty },
) = ty.sty
{ {
if match_type(cx, ty, &paths::VEC) { if match_type(cx, ty, &paths::VEC) {
span_lint( span_lint(
@ -157,10 +159,10 @@ fn check_fn(cx: &LateContext, decl: &FnDecl, fn_id: NodeId) {
if let FunctionRetTy::Return(ref ty) = decl.output { if let FunctionRetTy::Return(ref ty) = decl.output {
if let Some((out, MutMutable, _)) = get_rptr_lm(ty) { if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
let mut immutables = vec![]; let mut immutables = vec![];
for (_, ref mutbl, ref argspan) in for (_, ref mutbl, ref argspan) in decl.inputs
decl.inputs.iter().filter_map(|ty| get_rptr_lm(ty)).filter( .iter()
|&(lt, _, _)| lt.name == out.name, .filter_map(|ty| get_rptr_lm(ty))
) .filter(|&(lt, _, _)| lt.name == out.name)
{ {
if *mutbl == MutMutable { if *mutbl == MutMutable {
return; return;

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{is_integer_literal, paths, snippet, span_lint}; use utils::{is_integer_literal, paths, snippet, span_lint};
use utils::{higher, implements_trait, get_trait_def_id}; use utils::{get_trait_def_id, higher, implements_trait};
/// **What it does:** Checks for calling `.step_by(0)` on iterators, /// **What it does:** Checks for calling `.step_by(0)` on iterators,
/// which never terminates. /// which never terminates.
@ -54,7 +54,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StepByZero {
// Range with step_by(0). // Range with step_by(0).
if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) { if name == "step_by" && args.len() == 2 && has_step_by(cx, &args[0]) {
use consts::{Constant, constant}; use consts::{constant, Constant};
use rustc_const_math::ConstInt::Usize; use rustc_const_math::ConstInt::Usize;
if let Some((Constant::Int(Usize(us)), _)) = constant(cx, &args[1]) { if let Some((Constant::Int(Usize(us)), _)) = constant(cx, &args[1]) {
if us.as_u64(cx.sess().target.uint_type) == 0 { if us.as_u64(cx.sess().target.uint_type) == 0 {

View file

@ -1,6 +1,6 @@
use syntax::ast::{Expr, ExprKind, UnOp}; use syntax::ast::{Expr, ExprKind, UnOp};
use rustc::lint::*; use rustc::lint::*;
use utils::{span_lint_and_sugg, snippet}; use utils::{snippet, span_lint_and_sugg};
/// **What it does:** Checks for usage of `*&` and `*&mut` in expressions. /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
/// ///

View file

@ -7,9 +7,9 @@ use rustc::ty::subst::Substs;
use std::collections::HashSet; use std::collections::HashSet;
use std::error::Error; use std::error::Error;
use syntax::ast::{LitKind, NodeId}; use syntax::ast::{LitKind, NodeId};
use syntax::codemap::{Span, BytePos}; use syntax::codemap::{BytePos, Span};
use syntax::symbol::InternedString; use syntax::symbol::InternedString;
use utils::{is_expn_of, match_def_path, match_type, paths, span_lint, span_help_and_lint}; use utils::{is_expn_of, match_def_path, match_type, paths, span_help_and_lint, span_lint};
/// **What it does:** Checks [regex](https://crates.io/crates/regex) creation /// **What it does:** Checks [regex](https://crates.io/crates/regex) creation
/// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct /// (with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct
@ -161,27 +161,19 @@ fn is_trivial_regex(s: &regex_syntax::Expr) -> Option<&'static str> {
match *s { match *s {
Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"), Expr::Empty | Expr::StartText | Expr::EndText => Some("the regex is unlikely to be useful as it is"),
Expr::Literal { .. } => Some("consider using `str::contains`"), Expr::Literal { .. } => Some("consider using `str::contains`"),
Expr::Concat(ref exprs) => { Expr::Concat(ref exprs) => match exprs.len() {
match exprs.len() { 2 => match (&exprs[0], &exprs[1]) {
2 => {
match (&exprs[0], &exprs[1]) {
(&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"), (&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
(&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"), (&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
(&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"), (&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
_ => None, _ => None,
}
}, },
3 => { 3 => if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) =
(&exprs[0], &exprs[1], &exprs[2])
{
Some("consider using `==` on `str`s") Some("consider using `==` on `str`s")
} else { } else {
None None
}
}, },
_ => None, _ => None,
}
}, },
_ => None, _ => None,
} }
@ -205,8 +197,7 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
if let LitKind::Str(ref r, _) = lit.node { if let LitKind::Str(ref r, _) = lit.node {
let r = &r.as_str(); let r = &r.as_str();
match builder.parse(r) { match builder.parse(r) {
Ok(r) => { Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
if let Some(repl) = is_trivial_regex(&r) {
span_help_and_lint( span_help_and_lint(
cx, cx,
TRIVIAL_REGEX, TRIVIAL_REGEX,
@ -214,7 +205,6 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
"trivial regex", "trivial regex",
&format!("consider using {}", repl), &format!("consider using {}", repl),
); );
}
}, },
Err(e) => { Err(e) => {
span_lint( span_lint(
@ -228,8 +218,7 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
} }
} else if let Some(r) = const_str(cx, expr) { } else if let Some(r) = const_str(cx, expr) {
match builder.parse(&r) { match builder.parse(&r) {
Ok(r) => { Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
if let Some(repl) = is_trivial_regex(&r) {
span_help_and_lint( span_help_and_lint(
cx, cx,
TRIVIAL_REGEX, TRIVIAL_REGEX,
@ -237,7 +226,6 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
"trivial regex", "trivial regex",
&format!("consider using {}", repl), &format!("consider using {}", repl),
); );
}
}, },
Err(e) => { Err(e) => {
span_lint( span_lint(

View file

@ -3,7 +3,7 @@ use syntax::ast;
use syntax::codemap::{Span, Spanned}; use syntax::codemap::{Span, Spanned};
use syntax::visit::FnKind; use syntax::visit::FnKind;
use utils::{span_note_and_lint, span_lint_and_then, snippet_opt, match_path_ast, in_macro, in_external_macro}; use utils::{in_external_macro, in_macro, match_path_ast, snippet_opt, span_lint_and_then, span_note_and_lint};
/// **What it does:** Checks for return statements at the end of a block. /// **What it does:** Checks for return statements at the end of a block.
/// ///
@ -50,8 +50,7 @@ impl ReturnPass {
fn check_block_return(&mut self, cx: &EarlyContext, block: &ast::Block) { fn check_block_return(&mut self, cx: &EarlyContext, block: &ast::Block) {
if let Some(stmt) = block.stmts.last() { if let Some(stmt) = block.stmts.last() {
match stmt.node { match stmt.node {
ast::StmtKind::Expr(ref expr) | ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
ast::StmtKind::Semi(ref expr) => {
self.check_final_expr(cx, expr, Some(stmt.span)); self.check_final_expr(cx, expr, Some(stmt.span));
}, },
_ => (), _ => (),
@ -81,10 +80,8 @@ impl ReturnPass {
self.check_final_expr(cx, elsexpr, None); self.check_final_expr(cx, elsexpr, None);
}, },
// a match expr, check all arms // a match expr, check all arms
ast::ExprKind::Match(_, ref arms) => { ast::ExprKind::Match(_, ref arms) => for arm in arms {
for arm in arms {
self.check_final_expr(cx, &arm.body, Some(arm.body.span)); self.check_final_expr(cx, &arm.body, Some(arm.body.span));
}
}, },
_ => (), _ => (),
} }
@ -140,8 +137,7 @@ impl LintPass for ReturnPass {
impl EarlyLintPass for ReturnPass { impl EarlyLintPass for ReturnPass {
fn check_fn(&mut self, cx: &EarlyContext, kind: FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { fn check_fn(&mut self, cx: &EarlyContext, kind: FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
match kind { match kind {
FnKind::ItemFn(.., block) | FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
FnKind::Method(.., block) => self.check_block_return(cx, block),
FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)), FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
} }
} }

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{span_lint, get_trait_def_id, paths}; use utils::{get_trait_def_id, paths, span_lint};
/// **What it does:** Checks for mis-uses of the serde API. /// **What it does:** Checks for mis-uses of the serde API.
/// ///

View file

@ -4,7 +4,7 @@ use rustc::hir::*;
use rustc::hir::intravisit::FnKind; use rustc::hir::intravisit::FnKind;
use rustc::ty; use rustc::ty;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{contains_name, higher, in_external_macro, snippet, span_lint_and_then, iter_input_pats}; use utils::{contains_name, higher, in_external_macro, iter_input_pats, snippet, span_lint_and_then};
/// **What it does:** Checks for bindings that shadow other bindings already in /// **What it does:** Checks for bindings that shadow other bindings already in
/// scope, while just changing reference level or mutability. /// scope, while just changing reference level or mutability.
@ -111,8 +111,7 @@ fn check_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, block: &'tcx Block, binding
for stmt in &block.stmts { for stmt in &block.stmts {
match stmt.node { match stmt.node {
StmtDecl(ref decl, _) => check_decl(cx, decl, bindings), StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
StmtExpr(ref e, _) | StmtExpr(ref e, _) | StmtSemi(ref e, _) => check_expr(cx, e, bindings),
StmtSemi(ref e, _) => check_expr(cx, e, bindings),
} }
} }
if let Some(ref o) = block.expr { if let Some(ref o) = block.expr {
@ -185,14 +184,14 @@ fn check_pat<'a, 'tcx>(
check_pat(cx, p, init, span, bindings); check_pat(cx, p, init, span, bindings);
} }
}, },
PatKind::Struct(_, ref pfields, _) => { PatKind::Struct(_, ref pfields, _) => if let Some(init_struct) = init {
if let Some(init_struct) = init {
if let ExprStruct(_, ref efields, _) = init_struct.node { if let ExprStruct(_, ref efields, _) = init_struct.node {
for field in pfields { for field in pfields {
let name = field.node.name; let name = field.node.name;
let efield = efields.iter().find(|f| f.name.node == name).map( let efield = efields
|f| &*f.expr, .iter()
); .find(|f| f.name.node == name)
.map(|f| &*f.expr);
check_pat(cx, &field.node.pat, efield, span, bindings); check_pat(cx, &field.node.pat, efield, span, bindings);
} }
} else { } else {
@ -204,10 +203,8 @@ fn check_pat<'a, 'tcx>(
for field in pfields { for field in pfields {
check_pat(cx, &field.node.pat, None, span, bindings); check_pat(cx, &field.node.pat, None, span, bindings);
} }
}
}, },
PatKind::Tuple(ref inner, _) => { PatKind::Tuple(ref inner, _) => if let Some(init_tup) = init {
if let Some(init_tup) = init {
if let ExprTup(ref tup) = init_tup.node { if let ExprTup(ref tup) = init_tup.node {
for (i, p) in inner.iter().enumerate() { for (i, p) in inner.iter().enumerate() {
check_pat(cx, p, Some(&tup[i]), p.span, bindings); check_pat(cx, p, Some(&tup[i]), p.span, bindings);
@ -221,10 +218,8 @@ fn check_pat<'a, 'tcx>(
for p in inner { for p in inner {
check_pat(cx, p, None, span, bindings); check_pat(cx, p, None, span, bindings);
} }
}
}, },
PatKind::Box(ref inner) => { PatKind::Box(ref inner) => if let Some(initp) = init {
if let Some(initp) = init {
if let ExprBox(ref inner_init) = initp.node { if let ExprBox(ref inner_init) = initp.node {
check_pat(cx, inner, Some(&**inner_init), span, bindings); check_pat(cx, inner, Some(&**inner_init), span, bindings);
} else { } else {
@ -232,7 +227,6 @@ fn check_pat<'a, 'tcx>(
} }
} else { } else {
check_pat(cx, inner, init, span, bindings); check_pat(cx, inner, init, span, bindings);
}
}, },
PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings), PatKind::Ref(ref inner, _) => check_pat(cx, inner, init, span, bindings),
// PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>), // PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
@ -292,13 +286,14 @@ fn lint_shadow<'a, 'tcx: 'a>(
}, },
); );
} }
} else { } else {
span_lint_and_then(cx, span_lint_and_then(
cx,
SHADOW_UNRELATED, SHADOW_UNRELATED,
span, span,
&format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")), &format!("`{}` shadows a previous declaration", snippet(cx, pattern_span, "_")),
|db| { db.span_note(prev_span, "previous binding is here"); }); |db| { db.span_note(prev_span, "previous binding is here"); },
);
} }
} }
@ -307,19 +302,14 @@ fn check_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, bindings:
return; return;
} }
match expr.node { match expr.node {
ExprUnary(_, ref e) | ExprUnary(_, ref e) | ExprField(ref e, _) | ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) => {
ExprField(ref e, _) | check_expr(cx, e, bindings)
ExprTupField(ref e, _) | },
ExprAddrOf(_, ref e) | ExprBlock(ref block) | ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
ExprBox(ref e) => check_expr(cx, e, bindings),
ExprBlock(ref block) |
ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
// ExprCall // ExprCall
// ExprMethodCall // ExprMethodCall
ExprArray(ref v) | ExprTup(ref v) => { ExprArray(ref v) | ExprTup(ref v) => for e in v {
for e in v {
check_expr(cx, e, bindings) check_expr(cx, e, bindings)
}
}, },
ExprIf(ref cond, ref then, ref otherwise) => { ExprIf(ref cond, ref then, ref otherwise) => {
check_expr(cx, cond, bindings); check_expr(cx, cond, bindings);
@ -358,12 +348,9 @@ fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut V
check_ty(cx, fty, bindings); check_ty(cx, fty, bindings);
check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings); check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings);
}, },
TyPtr(MutTy { ty: ref mty, .. }) | TyPtr(MutTy { ty: ref mty, .. }) | TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings), TyTup(ref tup) => for t in tup {
TyTup(ref tup) => {
for t in tup {
check_ty(cx, t, bindings) check_ty(cx, t, bindings)
}
}, },
TyTypeof(body_id) => check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings), TyTypeof(body_id) => check_expr(cx, &cx.tcx.hir.body(body_id).value, bindings),
_ => (), _ => (),
@ -372,14 +359,13 @@ fn check_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: &'tcx Ty, bindings: &mut V
fn is_self_shadow(name: Name, expr: &Expr) -> bool { fn is_self_shadow(name: Name, expr: &Expr) -> bool {
match expr.node { match expr.node {
ExprBox(ref inner) | ExprBox(ref inner) | ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
ExprBlock(ref block) => { ExprBlock(ref block) => {
block.stmts.is_empty() && block.stmts.is_empty() &&
block.expr.as_ref().map_or( block
false, .expr
|e| is_self_shadow(name, e), .as_ref()
) .map_or(false, |e| is_self_shadow(name, e))
}, },
ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner), ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path), ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::{is_direct_expn_of, is_expn_of, implements_trait, span_lint}; use utils::{implements_trait, is_direct_expn_of, is_expn_of, span_lint};
/// **What it does:** Checks for `assert!(x == y)` or `assert!(x != y)` which /// **What it does:** Checks for `assert!(x == y)` or `assert!(x != y)` which
/// can be better written /// can be better written

View file

@ -2,7 +2,7 @@ use rustc::hir::*;
use rustc::lint::*; use rustc::lint::*;
use syntax::codemap::Spanned; use syntax::codemap::Spanned;
use utils::SpanlessEq; use utils::SpanlessEq;
use utils::{match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty, get_parent_expr, is_allowed}; use utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
/// **What it does:** Checks for string appends of the form `x = x + y` (without /// **What it does:** Checks for string appends of the form `x = x + y` (without
/// `let`!). /// `let`!).
@ -124,10 +124,10 @@ fn is_add(cx: &LateContext, src: &Expr, target: &Expr) -> bool {
ExprBinary(Spanned { node: BiAdd, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left), ExprBinary(Spanned { node: BiAdd, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left),
ExprBlock(ref block) => { ExprBlock(ref block) => {
block.stmts.is_empty() && block.stmts.is_empty() &&
block.expr.as_ref().map_or( block
false, .expr
|expr| is_add(cx, expr, target), .as_ref()
) .map_or(false, |expr| is_add(cx, expr, target))
}, },
_ => false, _ => false,
} }
@ -146,7 +146,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use syntax::ast::LitKind; use syntax::ast::LitKind;
use utils::{snippet, in_macro}; use utils::{in_macro, snippet};
if let ExprMethodCall(ref path, _, ref args) = e.node { if let ExprMethodCall(ref path, _, ref args) = e.node {
if path.name == "as_bytes" { if path.name == "as_bytes" {

View file

@ -41,11 +41,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if let ExprAssign(ref target, _) = expr.node { if let ExprAssign(ref target, _) = expr.node {
match target.node { match target.node {
ExprField(ref base, _) | ExprField(ref base, _) | ExprTupField(ref base, _) => if is_temporary(base) && !is_adjusted(cx, base) {
ExprTupField(ref base, _) => {
if is_temporary(base) && !is_adjusted(cx, base) {
span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary"); span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
}
}, },
_ => (), _ => (),
} }

View file

@ -1,7 +1,7 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::ty::{self, Ty}; use rustc::ty::{self, Ty};
use rustc::hir::*; use rustc::hir::*;
use utils::{match_def_path, paths, span_lint, span_lint_and_then, snippet, last_path_segment}; use utils::{last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_then};
use utils::sugg; use utils::sugg;
/// **What it does:** Checks for transmutes that can't ever be correct on any /// **What it does:** Checks for transmutes that can't ever be correct on any
@ -95,16 +95,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
let to_ty = cx.tables.expr_ty(e); let to_ty = cx.tables.expr_ty(e);
match (&from_ty.sty, &to_ty.sty) { match (&from_ty.sty, &to_ty.sty) {
_ if from_ty == to_ty => { _ if from_ty == to_ty => span_lint(
span_lint(
cx, cx,
USELESS_TRANSMUTE, USELESS_TRANSMUTE,
e.span, e.span,
&format!("transmute from a type (`{}`) to itself", from_ty), &format!("transmute from a type (`{}`) to itself", from_ty),
) ),
}, (&ty::TyRef(_, rty), &ty::TyRawPtr(ptr_ty)) => span_lint_and_then(
(&ty::TyRef(_, rty), &ty::TyRawPtr(ptr_ty)) => {
span_lint_and_then(
cx, cx,
USELESS_TRANSMUTE, USELESS_TRANSMUTE,
e.span, e.span,
@ -118,11 +115,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
db.span_suggestion(e.span, "try", sugg.to_string()); db.span_suggestion(e.span, "try", sugg.to_string());
}, },
) ),
}, (&ty::TyInt(_), &ty::TyRawPtr(_)) | (&ty::TyUint(_), &ty::TyRawPtr(_)) => span_lint_and_then(
(&ty::TyInt(_), &ty::TyRawPtr(_)) |
(&ty::TyUint(_), &ty::TyRawPtr(_)) => {
span_lint_and_then(
cx, cx,
USELESS_TRANSMUTE, USELESS_TRANSMUTE,
e.span, e.span,
@ -130,21 +124,17 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
|db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) { |db| if let Some(arg) = sugg::Sugg::hir_opt(cx, &args[0]) {
db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string()); db.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
}, },
) ),
},
(&ty::TyFloat(_), &ty::TyRef(..)) | (&ty::TyFloat(_), &ty::TyRef(..)) |
(&ty::TyFloat(_), &ty::TyRawPtr(_)) | (&ty::TyFloat(_), &ty::TyRawPtr(_)) |
(&ty::TyChar, &ty::TyRef(..)) | (&ty::TyChar, &ty::TyRef(..)) |
(&ty::TyChar, &ty::TyRawPtr(_)) => { (&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
span_lint(
cx, cx,
WRONG_TRANSMUTE, WRONG_TRANSMUTE,
e.span, e.span,
&format!("transmute from a `{}` to a pointer", from_ty), &format!("transmute from a `{}` to a pointer", from_ty),
) ),
}, (&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => span_lint(
(&ty::TyRawPtr(from_ptr), _) if from_ptr.ty == to_ty => {
span_lint(
cx, cx,
CROSSPOINTER_TRANSMUTE, CROSSPOINTER_TRANSMUTE,
e.span, e.span,
@ -153,18 +143,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
from_ty, from_ty,
to_ty to_ty
), ),
) ),
}, (_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => span_lint(
(_, &ty::TyRawPtr(to_ptr)) if to_ptr.ty == from_ty => {
span_lint(
cx, cx,
CROSSPOINTER_TRANSMUTE, CROSSPOINTER_TRANSMUTE,
e.span, e.span,
&format!("transmute from a type (`{}`) to a pointer to that type (`{}`)", from_ty, to_ty), &format!("transmute from a type (`{}`) to a pointer to that type (`{}`)", from_ty, to_ty),
) ),
}, (&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_rty)) => span_lint_and_then(
(&ty::TyRawPtr(from_pty), &ty::TyRef(_, to_rty)) => {
span_lint_and_then(
cx, cx,
TRANSMUTE_PTR_TO_REF, TRANSMUTE_PTR_TO_REF,
e.span, e.span,
@ -190,8 +176,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string()); db.span_suggestion(e.span, "try", sugg::make_unop(deref, arg).to_string());
}, },
) ),
},
_ => return, _ => return,
}; };
} }

View file

@ -1,16 +1,16 @@
use reexport::*; use reexport::*;
use rustc::hir; use rustc::hir;
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{FnKind, Visitor, walk_ty, NestedVisitorMap}; use rustc::hir::intravisit::{walk_ty, FnKind, NestedVisitorMap, Visitor};
use rustc::lint::*; use rustc::lint::*;
use rustc::ty::{self, Ty, TyCtxt}; use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::Substs; use rustc::ty::subst::Substs;
use std::cmp::Ordering; use std::cmp::Ordering;
use syntax::ast::{IntTy, UintTy, FloatTy}; use syntax::ast::{FloatTy, IntTy, UintTy};
use syntax::attr::IntType; use syntax::attr::IntType;
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{comparisons, higher, in_external_macro, in_macro, match_def_path, snippet, span_help_and_lint, span_lint, use utils::{comparisons, higher, in_external_macro, in_macro, last_path_segment, match_def_path, match_path,
span_lint_and_sugg, opt_def_id, last_path_segment, type_size, match_path}; opt_def_id, snippet, span_help_and_lint, span_lint, span_lint_and_sugg, type_size};
use utils::paths; use utils::paths;
/// Handles all the linting of funky types /// Handles all the linting of funky types
@ -114,8 +114,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) { fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
match item.node { match item.node {
TraitItemKind::Const(ref ty, _) | TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl), TraitItemKind::Method(ref sig, _) => check_fn_decl(cx, &sig.decl),
_ => (), _ => (),
} }
@ -182,20 +181,18 @@ fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
match *qpath { match *qpath {
QPath::Resolved(Some(ref ty), ref p) => { QPath::Resolved(Some(ref ty), ref p) => {
check_ty(cx, ty, is_local); check_ty(cx, ty, is_local);
for ty in p.segments.iter().flat_map( for ty in p.segments
|seg| seg.parameters.types.iter(), .iter()
) .flat_map(|seg| seg.parameters.types.iter())
{ {
check_ty(cx, ty, is_local); check_ty(cx, ty, is_local);
} }
}, },
QPath::Resolved(None, ref p) => { QPath::Resolved(None, ref p) => for ty in p.segments
for ty in p.segments.iter().flat_map( .iter()
|seg| seg.parameters.types.iter(), .flat_map(|seg| seg.parameters.types.iter())
)
{ {
check_ty(cx, ty, is_local); check_ty(cx, ty, is_local);
}
}, },
QPath::TypeRelative(ref ty, ref seg) => { QPath::TypeRelative(ref ty, ref seg) => {
check_ty(cx, ty, is_local); check_ty(cx, ty, is_local);
@ -248,13 +245,9 @@ fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
} }
}, },
// recurse // recurse
TySlice(ref ty) | TySlice(ref ty) | TyArray(ref ty, _) | TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
TyArray(ref ty, _) | TyTup(ref tys) => for ty in tys {
TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
TyTup(ref tys) => {
for ty in tys {
check_ty(cx, ty, is_local); check_ty(cx, ty, is_local);
}
}, },
_ => {}, _ => {},
} }
@ -529,25 +522,21 @@ declare_lint! {
/// Will return 0 if the type is not an int or uint variant /// Will return 0 if the type is not an int or uint variant
fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 { fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
match typ.sty { match typ.sty {
ty::TyInt(i) => { ty::TyInt(i) => match i {
match i {
IntTy::Is => tcx.data_layout.pointer_size.bits(), IntTy::Is => tcx.data_layout.pointer_size.bits(),
IntTy::I8 => 8, IntTy::I8 => 8,
IntTy::I16 => 16, IntTy::I16 => 16,
IntTy::I32 => 32, IntTy::I32 => 32,
IntTy::I64 => 64, IntTy::I64 => 64,
IntTy::I128 => 128, IntTy::I128 => 128,
}
}, },
ty::TyUint(i) => { ty::TyUint(i) => match i {
match i {
UintTy::Us => tcx.data_layout.pointer_size.bits(), UintTy::Us => tcx.data_layout.pointer_size.bits(),
UintTy::U8 => 8, UintTy::U8 => 8,
UintTy::U16 => 16, UintTy::U16 => 16,
UintTy::U32 => 32, UintTy::U32 => 32,
UintTy::U64 => 64, UintTy::U64 => 64,
UintTy::U128 => 128, UintTy::U128 => 128,
}
}, },
_ => 0, _ => 0,
} }
@ -555,8 +544,7 @@ fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
fn is_isize_or_usize(typ: Ty) -> bool { fn is_isize_or_usize(typ: Ty) -> bool {
match typ.sty { match typ.sty {
ty::TyInt(IntTy::Is) | ty::TyInt(IntTy::Is) | ty::TyUint(UintTy::Us) => true,
ty::TyUint(UintTy::Us) => true,
_ => false, _ => false,
} }
} }
@ -617,16 +605,13 @@ fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, c
let to_nbits = int_ty_to_nbits(cast_to, cx.tcx); let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) = let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) { match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
(true, true) | (false, false) => { (true, true) | (false, false) => (
(
to_nbits < from_nbits, to_nbits < from_nbits,
ArchSuffix::None, ArchSuffix::None,
to_nbits == from_nbits && cast_unsigned_to_signed, to_nbits == from_nbits && cast_unsigned_to_signed,
ArchSuffix::None, ArchSuffix::None,
) ),
}, (true, false) => (
(true, false) => {
(
to_nbits <= 32, to_nbits <= 32,
if to_nbits == 32 { if to_nbits == 32 {
ArchSuffix::_64 ArchSuffix::_64
@ -635,10 +620,8 @@ fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, c
}, },
to_nbits <= 32 && cast_unsigned_to_signed, to_nbits <= 32 && cast_unsigned_to_signed,
ArchSuffix::_32, ArchSuffix::_32,
) ),
}, (false, true) => (
(false, true) => {
(
from_nbits == 64, from_nbits == 64,
ArchSuffix::_32, ArchSuffix::_32,
cast_unsigned_to_signed, cast_unsigned_to_signed,
@ -647,8 +630,7 @@ fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, c
} else { } else {
ArchSuffix::_32 ArchSuffix::_32
}, },
) ),
},
}; };
if span_truncation { if span_truncation {
span_lint( span_lint(
@ -690,8 +672,7 @@ fn check_lossless(cx: &LateContext, expr: &Expr, op: &Expr, cast_from: Ty, cast_
let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed(); let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
let from_nbits = int_ty_to_nbits(cast_from, cx.tcx); let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
let to_nbits = int_ty_to_nbits(cast_to, cx.tcx); let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
!cast_signed_to_unsigned
{ {
span_lossless_lint(cx, expr, op, cast_from, cast_to); span_lossless_lint(cx, expr, op, cast_from, cast_to);
} }
@ -715,19 +696,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
if let ExprCast(ref ex, _) = expr.node { if let ExprCast(ref ex, _) = expr.node {
let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr)); let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
if let ExprLit(ref lit) = ex.node { if let ExprLit(ref lit) = ex.node {
use syntax::ast::{LitKind, LitIntType}; use syntax::ast::{LitIntType, LitKind};
match lit.node { match lit.node {
LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
LitKind::FloatUnsuffixed(_) => {}, _ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
_ => {
if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
span_lint( span_lint(
cx, cx,
UNNECESSARY_CAST, UNNECESSARY_CAST,
expr.span, expr.span,
&format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to), &format!("casting to the same type is unnecessary (`{}` -> `{}`)", cast_from, cast_to),
); );
}
}, },
} }
} }
@ -776,8 +754,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
check_lossless(cx, expr, ex, cast_from, cast_to); check_lossless(cx, expr, ex, cast_from, cast_to);
}, },
(false, false) => { (false, false) => {
if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
(&cast_from.sty, &cast_to.sty)
{ {
span_lint( span_lint(
cx, cx,
@ -786,8 +763,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
"casting f64 to f32 may truncate the value", "casting f64 to f32 may truncate the value",
); );
} }
if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
(&cast_from.sty, &cast_to.sty)
{ {
span_lossless_lint(cx, expr, ex, cast_from, cast_to); span_lossless_lint(cx, expr, ex, cast_from, cast_to);
} }
@ -823,7 +799,9 @@ pub struct TypeComplexityPass {
impl TypeComplexityPass { impl TypeComplexityPass {
pub fn new(threshold: u64) -> Self { pub fn new(threshold: u64) -> Self {
Self { threshold: threshold } Self {
threshold: threshold,
}
} }
} }
@ -853,8 +831,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) { fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
match item.node { match item.node {
ItemStatic(ref ty, _, _) | ItemStatic(ref ty, _, _) | ItemConst(ref ty, _) => self.check_type(cx, ty),
ItemConst(ref ty, _) => self.check_type(cx, ty),
// functions, enums, structs, impls and traits are covered // functions, enums, structs, impls and traits are covered
_ => (), _ => (),
} }
@ -862,8 +839,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) { fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
match item.node { match item.node {
TraitItemKind::Const(ref ty, _) | TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl), TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
// methods with default impl are covered by check_fn // methods with default impl are covered by check_fn
_ => (), _ => (),
@ -872,8 +848,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) { fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
match item.node { match item.node {
ImplItemKind::Const(ref ty, _) | ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
// methods are covered by check_fn // methods are covered by check_fn
_ => (), _ => (),
} }
@ -938,9 +913,9 @@ impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
TyBareFn(..) => (50 * self.nest, 1), TyBareFn(..) => (50 * self.nest, 1),
TyTraitObject(ref param_bounds, _) => { TyTraitObject(ref param_bounds, _) => {
let has_lifetime_parameters = param_bounds.iter().any( let has_lifetime_parameters = param_bounds
|bound| !bound.bound_lifetimes.is_empty(), .iter()
); .any(|bound| !bound.bound_lifetimes.is_empty());
if has_lifetime_parameters { if has_lifetime_parameters {
// complex trait bounds like A<'a, 'b> // complex trait bounds like A<'a, 'b>
(50 * self.nest, 1) (50 * self.nest, 1)
@ -1101,7 +1076,7 @@ fn detect_absurd_comparison<'a>(
Rel::Le => { Rel::Le => {
match (lx, rx) { match (lx, rx) {
(Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
(Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), //max <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
(_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
(_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
_ => return None, _ => return None,
@ -1187,14 +1162,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
let conclusion = match result { let conclusion = match result {
AlwaysFalse => "this comparison is always false".to_owned(), AlwaysFalse => "this comparison is always false".to_owned(),
AlwaysTrue => "this comparison is always true".to_owned(), AlwaysTrue => "this comparison is always true".to_owned(),
InequalityImpossible => { InequalityImpossible => format!(
format!(
"the case where the two sides are not equal never occurs, consider using {} == {} \ "the case where the two sides are not equal never occurs, consider using {} == {} \
instead", instead",
snippet(cx, lhs.span, "lhs"), snippet(cx, lhs.span, "lhs"),
snippet(cx, rhs.span, "rhs") snippet(cx, rhs.span, "rhs")
) ),
},
}; };
let help = format!( let help = format!(
@ -1264,9 +1237,8 @@ impl FullInt {
impl PartialEq for FullInt { impl PartialEq for FullInt {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.partial_cmp(other).expect( self.partial_cmp(other)
"partial_cmp only returns Some(_)", .expect("partial_cmp only returns Some(_)") == Ordering::Equal
) == Ordering::Equal
} }
} }
@ -1282,9 +1254,8 @@ impl PartialOrd for FullInt {
} }
impl Ord for FullInt { impl Ord for FullInt {
fn cmp(&self, other: &Self) -> Ordering { fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).expect( self.partial_cmp(other)
"partial_cmp for FullInt can never return None", .expect("partial_cmp for FullInt can never return None")
)
} }
} }
@ -1301,8 +1272,7 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(
return None; return None;
} }
match pre_cast_ty.sty { match pre_cast_ty.sty {
ty::TyInt(int_ty) => { ty::TyInt(int_ty) => Some(match int_ty {
Some(match int_ty {
IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))), IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
IntTy::I16 => ( IntTy::I16 => (
FullInt::S(i128::from(i16::min_value())), FullInt::S(i128::from(i16::min_value())),
@ -1318,10 +1288,8 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(
), ),
IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)), IntTy::I128 => (FullInt::S(i128::min_value() as i128), FullInt::S(i128::max_value() as i128)),
IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)), IntTy::Is => (FullInt::S(isize::min_value() as i128), FullInt::S(isize::max_value() as i128)),
}) }),
}, ty::TyUint(uint_ty) => Some(match uint_ty {
ty::TyUint(uint_ty) => {
Some(match uint_ty {
UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))), UintTy::U8 => (FullInt::U(u128::from(u8::min_value())), FullInt::U(u128::from(u8::max_value()))),
UintTy::U16 => ( UintTy::U16 => (
FullInt::U(u128::from(u16::min_value())), FullInt::U(u128::from(u16::min_value())),
@ -1337,8 +1305,7 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(
), ),
UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)), UintTy::U128 => (FullInt::U(u128::min_value() as u128), FullInt::U(u128::max_value() as u128)),
UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)), UintTy::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
}) }),
},
_ => None, _ => None,
} }
} else { } else {
@ -1355,15 +1322,13 @@ fn node_as_const_fullint(cx: &LateContext, expr: &Expr) -> Option<FullInt> {
let parent_def_id = cx.tcx.hir.local_def_id(parent_item); let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
let substs = Substs::identity_for_item(cx.tcx, parent_def_id); let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) { match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
Ok(val) => { Ok(val) => if let Integral(const_int) = val {
if let Integral(const_int) = val {
match const_int.int_type() { match const_int.int_type() {
IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)), IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())), IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
} }
} else { } else {
None None
}
}, },
Err(_) => None, Err(_) => None,
} }
@ -1402,42 +1367,32 @@ fn upcast_comparison_bounds_err(
err_upcast_comparison(cx, span, lhs, rel == Rel::Ne); err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
} }
} else if match rel { } else if match rel {
Rel::Lt => { Rel::Lt => if invert {
if invert {
norm_rhs_val < lb norm_rhs_val < lb
} else { } else {
ub < norm_rhs_val ub < norm_rhs_val
}
}, },
Rel::Le => { Rel::Le => if invert {
if invert {
norm_rhs_val <= lb norm_rhs_val <= lb
} else { } else {
ub <= norm_rhs_val ub <= norm_rhs_val
}
}, },
Rel::Eq | Rel::Ne => unreachable!(), Rel::Eq | Rel::Ne => unreachable!(),
} } {
{
err_upcast_comparison(cx, span, lhs, true) err_upcast_comparison(cx, span, lhs, true)
} else if match rel { } else if match rel {
Rel::Lt => { Rel::Lt => if invert {
if invert {
norm_rhs_val >= ub norm_rhs_val >= ub
} else { } else {
lb >= norm_rhs_val lb >= norm_rhs_val
}
}, },
Rel::Le => { Rel::Le => if invert {
if invert {
norm_rhs_val > ub norm_rhs_val > ub
} else { } else {
lb > norm_rhs_val lb > norm_rhs_val
}
}, },
Rel::Eq | Rel::Ne => unreachable!(), Rel::Eq | Rel::Ne => unreachable!(),
} } {
{
err_upcast_comparison(cx, span, lhs, false) err_upcast_comparison(cx, span, lhs, false)
} }
} }
@ -1447,7 +1402,6 @@ fn upcast_comparison_bounds_err(
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node { if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs); let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized { let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
val val

View file

@ -3,7 +3,7 @@ use rustc::hir::*;
use syntax::ast::{LitKind, NodeId}; use syntax::ast::{LitKind, NodeId};
use syntax::codemap::Span; use syntax::codemap::Span;
use unicode_normalization::UnicodeNormalization; use unicode_normalization::UnicodeNormalization;
use utils::{snippet, span_help_and_lint, is_allowed}; use utils::{is_allowed, snippet, span_help_and_lint};
/// **What it does:** Checks for the Unicode zero-width space in the code. /// **What it does:** Checks for the Unicode zero-width space in the code.
/// ///

View file

@ -48,13 +48,11 @@ impl EarlyLintPass for UnsafeNameRemoval {
&item.span, &item.span,
); );
}, },
ViewPath_::ViewPathList(_, ref path_list_items) => { ViewPath_::ViewPathList(_, ref path_list_items) => for path_list_item in path_list_items.iter() {
for path_list_item in path_list_items.iter() {
let plid = path_list_item.node; let plid = path_list_item.node;
if let Some(rename) = plid.rename { if let Some(rename) = plid.rename {
unsafe_to_safe_check(plid.name, rename, cx, &item.span); unsafe_to_safe_check(plid.name, rename, cx, &item.span);
}; };
}
}, },
ViewPath_::ViewPathGlob(_) => {}, ViewPath_::ViewPathGlob(_) => {},
} }

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir; use rustc::hir;
use utils::{span_lint, match_qpath, match_trait_method, is_try, paths}; use utils::{is_try, match_qpath, match_trait_method, paths, span_lint};
/// **What it does:** Checks for unused written/read amount. /// **What it does:** Checks for unused written/read amount.
/// ///
@ -40,8 +40,7 @@ impl LintPass for UnusedIoAmount {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedIoAmount { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedIoAmount {
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
let expr = match s.node { let expr = match s.node {
hir::StmtSemi(ref expr, _) | hir::StmtSemi(ref expr, _) | hir::StmtExpr(ref expr, _) => &**expr,
hir::StmtExpr(ref expr, _) => &**expr,
_ => return, _ => return,
}; };
@ -58,13 +57,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedIoAmount {
} }
}, },
hir::ExprMethodCall(ref path, _, ref args) => { hir::ExprMethodCall(ref path, _, ref args) => match &*path.name.as_str() {
match &*path.name.as_str() {
"expect" | "unwrap" | "unwrap_or" | "unwrap_or_else" => { "expect" | "unwrap" | "unwrap_or" | "unwrap_or_else" => {
check_method_call(cx, &args[0], expr); check_method_call(cx, &args[0], expr);
}, },
_ => (), _ => (),
}
}, },
_ => (), _ => (),

View file

@ -1,6 +1,6 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir; use rustc::hir;
use rustc::hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use std::collections::HashMap; use std::collections::HashMap;
use syntax::ast; use syntax::ast;
use syntax::codemap::Span; use syntax::codemap::Span;
@ -69,14 +69,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedLabel {
impl<'a, 'tcx: 'a> Visitor<'tcx> for UnusedLabelVisitor<'a, 'tcx> { impl<'a, 'tcx: 'a> Visitor<'tcx> for UnusedLabelVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx hir::Expr) { fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
match expr.node { match expr.node {
hir::ExprBreak(destination, _) | hir::ExprBreak(destination, _) | hir::ExprAgain(destination) => if let Some(label) = destination.ident {
hir::ExprAgain(destination) => {
if let Some(label) = destination.ident {
self.labels.remove(&label.node.name.as_str()); self.labels.remove(&label.node.name.as_str());
}
}, },
hir::ExprLoop(_, Some(label), _) | hir::ExprLoop(_, Some(label), _) | hir::ExprWhile(_, _, Some(label)) => {
hir::ExprWhile(_, _, Some(label)) => {
self.labels.insert(label.node.as_str(), expr.span); self.labels.insert(label.node.as_str(), expr.span);
}, },
_ => (), _ => (),

View file

@ -1,7 +1,7 @@
use rustc::lint::{LintArray, LateLintPass, LateContext, LintPass}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_path, NestedVisitorMap}; use rustc::hir::intravisit::{walk_path, NestedVisitorMap, Visitor};
use utils::{span_lint_and_then, in_macro}; use utils::{in_macro, span_lint_and_then};
use syntax::ast::NodeId; use syntax::ast::NodeId;
use syntax_pos::symbol::keywords::SelfType; use syntax_pos::symbol::keywords::SelfType;

View file

@ -5,9 +5,9 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir; use rustc::hir;
use rustc::hir::{Expr, QPath, Expr_}; use rustc::hir::{Expr, Expr_, QPath};
use rustc::hir::intravisit::{Visitor, NestedVisitorMap}; use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
use syntax::ast::{self, Attribute, NodeId, LitKind, DUMMY_NODE_ID}; use syntax::ast::{self, Attribute, LitKind, NodeId, DUMMY_NODE_ID};
use syntax::codemap::Span; use syntax::codemap::Span;
use std::collections::HashMap; use std::collections::HashMap;
@ -386,15 +386,13 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor {
println!("Again(ref {}) = {},", destination_pat, current); println!("Again(ref {}) = {},", destination_pat, current);
// FIXME: implement label printing // FIXME: implement label printing
}, },
Expr_::ExprRet(ref opt_value) => { Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
if let Some(ref value) = *opt_value {
let value_pat = self.next("value"); let value_pat = self.next("value");
println!("Ret(Some(ref {})) = {},", value_pat, current); println!("Ret(Some(ref {})) = {},", value_pat, current);
self.current = value_pat; self.current = value_pat;
self.visit_expr(value); self.visit_expr(value);
} else { } else {
println!("Ret(None) = {},", current); println!("Ret(None) = {},", current);
}
}, },
Expr_::ExprInlineAsm(_, ref _input, ref _output) => { Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
println!("InlineAsm(_, ref input, ref output) = {},", current); println!("InlineAsm(_, ref input, ref output) = {},", current);
@ -445,10 +443,8 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor {
fn has_attr(attrs: &[Attribute]) -> bool { fn has_attr(attrs: &[Attribute]) -> bool {
attrs.iter().any(|attr| { attrs.iter().any(|attr| {
attr.check_name("clippy") && attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
attr.meta_item_list().map_or(false, |list| { list.len() == 1 && match list[0].node {
list.len() == 1 &&
match list[0].node {
ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author", ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
ast::NestedMetaItemKind::Literal(_) => false, ast::NestedMetaItemKind::Literal(_) => false,
} }
@ -458,18 +454,15 @@ fn has_attr(attrs: &[Attribute]) -> bool {
fn print_path(path: &QPath, first: &mut bool) { fn print_path(path: &QPath, first: &mut bool) {
match *path { match *path {
QPath::Resolved(_, ref path) => { QPath::Resolved(_, ref path) => for segment in &path.segments {
for segment in &path.segments {
if *first { if *first {
*first = false; *first = false;
} else { } else {
print!(", "); print!(", ");
} }
print!("{:?}", segment.name.as_str()); print!("{:?}", segment.name.as_str());
}
}, },
QPath::TypeRelative(ref ty, ref segment) => { QPath::TypeRelative(ref ty, ref segment) => match ty.node {
match ty.node {
hir::Ty_::TyPath(ref inner_path) => { hir::Ty_::TyPath(ref inner_path) => {
print_path(inner_path, first); print_path(inner_path, first);
if *first { if *first {
@ -480,7 +473,6 @@ fn print_path(path: &QPath, first: &mut bool) {
print!("{:?}", segment.name.as_str()); print!("{:?}", segment.name.as_str());
}, },
ref other => print!("/* unimplemented: {:?}*/", other), ref other => print!("/* unimplemented: {:?}*/", other),
}
}, },
} }
} }

View file

@ -15,14 +15,13 @@ pub fn file_from_args(
for arg in args.iter().filter_map(|a| a.meta_item()) { for arg in args.iter().filter_map(|a| a.meta_item()) {
if arg.name() == "conf_file" { if arg.name() == "conf_file" {
return match arg.node { return match arg.node {
ast::MetaItemKind::Word | ast::MetaItemKind::Word | ast::MetaItemKind::List(_) => {
ast::MetaItemKind::List(_) => Err(("`conf_file` must be a named value", arg.span)), Err(("`conf_file` must be a named value", arg.span))
ast::MetaItemKind::NameValue(ref value) => { },
if let ast::LitKind::Str(ref file, _) = value.node { ast::MetaItemKind::NameValue(ref value) => if let ast::LitKind::Str(ref file, _) = value.node {
Ok(Some(file.to_string().into())) Ok(Some(file.to_string().into()))
} else { } else {
Err(("`conf_file` value must be a string", value.span)) Err(("`conf_file` value must be a string", value.span))
}
}, },
}; };
} }
@ -45,7 +44,7 @@ pub enum Error {
/// The expected type. /// The expected type.
&'static str, &'static str,
/// The type we got instead. /// The type we got instead.
&'static str &'static str,
), ),
/// There is an unknown key is the file. /// There is an unknown key is the file.
UnknownKey(String), UnknownKey(String),
@ -191,10 +190,8 @@ pub fn lookup_conf_file() -> io::Result<Option<path::PathBuf>> {
Ok(ref md) if md.is_file() => return Ok(Some(config_file)), Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
// Return the error if it's something other than `NotFound`; otherwise we didn't // Return the error if it's something other than `NotFound`; otherwise we didn't
// find the project file yet, and continue searching. // find the project file yet, and continue searching.
Err(e) => { Err(e) => if e.kind() != io::ErrorKind::NotFound {
if e.kind() != io::ErrorKind::NotFound {
return Err(e); return Err(e);
}
}, },
_ => (), _ => (),
} }

View file

@ -6,7 +6,7 @@
use rustc::hir; use rustc::hir;
use rustc::lint::LateContext; use rustc::lint::LateContext;
use syntax::ast; use syntax::ast;
use utils::{is_expn_of, match_qpath, match_def_path, resolve_node, paths}; use utils::{is_expn_of, match_def_path, match_qpath, paths, resolve_node};
/// Convert a hir binary operator to the corresponding `ast` type. /// Convert a hir binary operator to the corresponding `ast` type.
pub fn binop(op: hir::BinOp_) -> ast::BinOpKind { pub fn binop(op: hir::BinOp_) -> ast::BinOpKind {
@ -73,8 +73,9 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
None None
} }
}, },
hir::ExprStruct(ref path, ref fields, None) => { hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD) ||
if match_qpath(path, &paths::RANGE_FROM_STD) || match_qpath(path, &paths::RANGE_FROM) { match_qpath(path, &paths::RANGE_FROM)
{
Some(Range { Some(Range {
start: get_field("start", fields), start: get_field("start", fields),
end: None, end: None,
@ -92,9 +93,7 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
end: get_field("end", fields), end: get_field("end", fields),
limits: ast::RangeLimits::HalfOpen, limits: ast::RangeLimits::HalfOpen,
}) })
} else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || } else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
match_qpath(path, &paths::RANGE_TO_INCLUSIVE)
{
Some(Range { Some(Range {
start: None, start: None,
end: get_field("end", fields), end: get_field("end", fields),
@ -108,7 +107,6 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
}) })
} else { } else {
None None
}
}, },
_ => None, _ => None,
} }

View file

@ -46,8 +46,9 @@ impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
false false
} }
}, },
(&StmtExpr(ref l, _), &StmtExpr(ref r, _)) | (&StmtExpr(ref l, _), &StmtExpr(ref r, _)) | (&StmtSemi(ref l, _), &StmtSemi(ref r, _)) => {
(&StmtSemi(ref l, _), &StmtSemi(ref r, _)) => self.eq_expr(l, r), self.eq_expr(l, r)
},
_ => false, _ => false,
} }
} }
@ -107,8 +108,7 @@ impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.node.as_str() == r.node.as_str()) lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.node.as_str() == r.node.as_str())
}, },
(&ExprMatch(ref le, ref la, ref ls), &ExprMatch(ref re, ref ra, ref rs)) => { (&ExprMatch(ref le, ref la, ref ls), &ExprMatch(ref re, ref ra, ref rs)) => {
ls == rs && self.eq_expr(le, re) && ls == rs && self.eq_expr(le, re) && over(la, ra, |l, r| {
over(la, ra, |l, r| {
self.eq_expr(&l.body, &r.body) && both(&l.guard, &r.guard, |l, r| self.eq_expr(l, r)) && self.eq_expr(&l.body, &r.body) && both(&l.guard, &r.guard, |l, r| self.eq_expr(l, r)) &&
over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r)) over(&l.pats, &r.pats, |l, r| self.eq_pat(l, r))
}) })
@ -257,9 +257,8 @@ fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
where where
F: FnMut(&X, &X) -> bool, F: FnMut(&X, &X) -> bool,
{ {
l.as_ref().map_or_else(|| r.is_none(), |x| { l.as_ref()
r.as_ref().map_or(false, |y| eq_fn(x, y)) .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y)))
})
} }
/// Check if two slices are equal as per `eq_fn`. /// Check if two slices are equal as per `eq_fn`.

View file

@ -54,12 +54,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
match item.vis { match item.vis {
hir::Visibility::Public => println!("public"), hir::Visibility::Public => println!("public"),
hir::Visibility::Crate => println!("visible crate wide"), hir::Visibility::Crate => println!("visible crate wide"),
hir::Visibility::Restricted { ref path, .. } => { hir::Visibility::Restricted { ref path, .. } => println!(
println!(
"visible in module `{}`", "visible in module `{}`",
print::to_string(print::NO_ANN, |s| s.print_path(path, false)) print::to_string(print::NO_ANN, |s| s.print_path(path, false))
) ),
},
hir::Visibility::Inherited => println!("visibility inherited from outer item"), hir::Visibility::Inherited => println!("visibility inherited from outer item"),
} }
if item.defaultness.is_default() { if item.defaultness.is_default() {
@ -125,8 +123,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
} }
match stmt.node { match stmt.node {
hir::StmtDecl(ref decl, _) => print_decl(cx, decl), hir::StmtDecl(ref decl, _) => print_decl(cx, decl),
hir::StmtExpr(ref e, _) | hir::StmtExpr(ref e, _) | hir::StmtSemi(ref e, _) => print_expr(cx, e, 0),
hir::StmtSemi(ref e, _) => print_expr(cx, e, 0),
} }
} }
// fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx // fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx
@ -355,12 +352,10 @@ fn print_item(cx: &LateContext, item: &hir::Item) {
match item.vis { match item.vis {
hir::Visibility::Public => println!("public"), hir::Visibility::Public => println!("public"),
hir::Visibility::Crate => println!("visible crate wide"), hir::Visibility::Crate => println!("visible crate wide"),
hir::Visibility::Restricted { ref path, .. } => { hir::Visibility::Restricted { ref path, .. } => println!(
println!(
"visible in module `{}`", "visible in module `{}`",
print::to_string(print::NO_ANN, |s| s.print_path(path, false)) print::to_string(print::NO_ANN, |s| s.print_path(path, false))
) ),
},
hir::Visibility::Inherited => println!("visibility inherited from outer item"), hir::Visibility::Inherited => println!("visibility inherited from outer item"),
} }
match item.node { match item.node {

View file

@ -1,11 +1,11 @@
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap}; use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use utils::{paths, match_qpath, span_lint}; use utils::{match_qpath, paths, span_lint};
use syntax::symbol::InternedString; use syntax::symbol::InternedString;
use syntax::ast::{Name, NodeId, ItemKind, Crate as AstCrate}; use syntax::ast::{Crate as AstCrate, ItemKind, Name, NodeId};
use syntax::codemap::Span; use syntax::codemap::Span;
use std::collections::{HashSet, HashMap}; use std::collections::{HashMap, HashSet};
/// **What it does:** Checks for various things we like to keep tidy in clippy. /// **What it does:** Checks for various things we like to keep tidy in clippy.
@ -63,14 +63,17 @@ impl LintPass for Clippy {
impl EarlyLintPass for Clippy { impl EarlyLintPass for Clippy {
fn check_crate(&mut self, cx: &EarlyContext, krate: &AstCrate) { fn check_crate(&mut self, cx: &EarlyContext, krate: &AstCrate) {
if let Some(utils) = krate.module.items.iter().find( if let Some(utils) = krate
|item| item.ident.name == "utils", .module
) .items
.iter()
.find(|item| item.ident.name == "utils")
{ {
if let ItemKind::Mod(ref utils_mod) = utils.node { if let ItemKind::Mod(ref utils_mod) = utils.node {
if let Some(paths) = utils_mod.items.iter().find( if let Some(paths) = utils_mod
|item| item.ident.name == "paths", .items
) .iter()
.find(|item| item.ident.name == "paths")
{ {
if let ItemKind::Mod(ref paths_mod) = paths.node { if let ItemKind::Mod(ref paths_mod) = paths.node {
let mut last_name: Option<InternedString> = None; let mut last_name: Option<InternedString> = None;
@ -157,11 +160,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
fn is_lint_ref_type(ty: &Ty) -> bool { fn is_lint_ref_type(ty: &Ty) -> bool {
if let TyRptr(ref lt, if let TyRptr(
ref lt,
MutTy { MutTy {
ty: ref inner, ty: ref inner,
mutbl: MutImmutable, mutbl: MutImmutable,
}) = ty.node },
) = ty.node
{ {
if lt.is_elided() { if lt.is_elided() {
return false; return false;

View file

@ -5,10 +5,10 @@ use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc::hir::def::Def; use rustc::hir::def::Def;
use rustc::hir::intravisit::{NestedVisitorMap, Visitor}; use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
use rustc::hir::map::Node; use rustc::hir::map::Node;
use rustc::lint::{LintContext, Level, LateContext, Lint}; use rustc::lint::{LateContext, Level, Lint, LintContext};
use rustc::session::Session; use rustc::session::Session;
use rustc::traits; use rustc::traits;
use rustc::ty::{self, TyCtxt, Ty}; use rustc::ty::{self, Ty, TyCtxt};
use rustc::mir::transform::MirSource; use rustc::mir::transform::MirSource;
use rustc_errors; use rustc_errors;
use std::borrow::Cow; use std::borrow::Cow;
@ -104,18 +104,16 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
pub fn in_constant(cx: &LateContext, id: NodeId) -> bool { pub fn in_constant(cx: &LateContext, id: NodeId) -> bool {
let parent_id = cx.tcx.hir.get_parent(id); let parent_id = cx.tcx.hir.get_parent(id);
match MirSource::from_node(cx.tcx, parent_id) { match MirSource::from_node(cx.tcx, parent_id) {
MirSource::GeneratorDrop(_) | MirSource::GeneratorDrop(_) | MirSource::Fn(_) => false,
MirSource::Fn(_) => false, MirSource::Const(_) | MirSource::Static(..) | MirSource::Promoted(..) => true,
MirSource::Const(_) |
MirSource::Static(..) |
MirSource::Promoted(..) => true,
} }
} }
/// Returns true if this `expn_info` was expanded by any macro. /// Returns true if this `expn_info` was expanded by any macro.
pub fn in_macro(span: Span) -> bool { pub fn in_macro(span: Span) -> bool {
span.ctxt().outer().expn_info().map_or(false, |info| { span.ctxt().outer().expn_info().map_or(false, |info| {
match info.callee.format {// don't treat range expressions desugared to structs as "in_macro" match info.callee.format {
// don't treat range expressions desugared to structs as "in_macro"
ExpnFormat::CompilerDesugaring(kind) => kind != CompilerDesugaringKind::DotFill, ExpnFormat::CompilerDesugaring(kind) => kind != CompilerDesugaringKind::DotFill,
_ => true, _ => true,
} }
@ -138,18 +136,18 @@ pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
// no span for the callee = external macro // no span for the callee = external macro
info.callee.span.map_or(true, |span| { info.callee.span.map_or(true, |span| {
// no snippet = external macro or compiler-builtin expansion // no snippet = external macro or compiler-builtin expansion
cx.sess().codemap().span_to_snippet(span).ok().map_or( cx.sess()
true, .codemap()
|code| { .span_to_snippet(span)
!code.starts_with("macro_rules") .ok()
}, .map_or(true, |code| !code.starts_with("macro_rules"))
)
}) })
} }
span.ctxt().outer().expn_info().map_or(false, |info| { span.ctxt()
in_macro_ext(cx, &info) .outer()
}) .expn_info()
.map_or(false, |info| in_macro_ext(cx, &info))
} }
/// Check if a `DefId`'s path matches the given absolute type path usage. /// Check if a `DefId`'s path matches the given absolute type path usage.
@ -183,9 +181,10 @@ pub fn match_def_path(tcx: TyCtxt, def_id: DefId, path: &[&str]) -> bool {
tcx.push_item_path(&mut apb, def_id); tcx.push_item_path(&mut apb, def_id);
apb.names.len() == path.len() && apb.names.len() == path.len() &&
apb.names.into_iter().zip(path.iter()).all( apb.names
|(a, &b)| *a == *b, .into_iter()
) .zip(path.iter())
.all(|(a, &b)| *a == *b)
} }
/// Check if type is struct, enum or union type with given def path. /// Check if type is struct, enum or union type with given def path.
@ -220,11 +219,9 @@ pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool
pub fn last_path_segment(path: &QPath) -> &PathSegment { pub fn last_path_segment(path: &QPath) -> &PathSegment {
match *path { match *path {
QPath::Resolved(_, ref path) => { QPath::Resolved(_, ref path) => path.segments
path.segments.last().expect( .last()
"A path must have at least one segment", .expect("A path must have at least one segment"),
)
},
QPath::TypeRelative(_, ref seg) => seg, QPath::TypeRelative(_, ref seg) => seg,
} }
} }
@ -246,22 +243,22 @@ pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool { pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
match *path { match *path {
QPath::Resolved(_, ref path) => match_path(path, segments), QPath::Resolved(_, ref path) => match_path(path, segments),
QPath::TypeRelative(ref ty, ref segment) => { QPath::TypeRelative(ref ty, ref segment) => match ty.node {
match ty.node {
TyPath(ref inner_path) => { TyPath(ref inner_path) => {
!segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)]) && !segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)]) &&
segment.name == segments[segments.len() - 1] segment.name == segments[segments.len() - 1]
}, },
_ => false, _ => false,
}
}, },
} }
} }
pub fn match_path(path: &Path, segments: &[&str]) -> bool { pub fn match_path(path: &Path, segments: &[&str]) -> bool {
path.segments.iter().rev().zip(segments.iter().rev()).all( path.segments
|(a, b)| a.name == *b, .iter()
) .rev()
.zip(segments.iter().rev())
.all(|(a, b)| a.name == *b)
} }
/// Match a `Path` against a slice of segment string literals, e.g. /// Match a `Path` against a slice of segment string literals, e.g.
@ -271,9 +268,11 @@ pub fn match_path(path: &Path, segments: &[&str]) -> bool {
/// match_qpath(path, &["std", "rt", "begin_unwind"]) /// match_qpath(path, &["std", "rt", "begin_unwind"])
/// ``` /// ```
pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool { pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
path.segments.iter().rev().zip(segments.iter().rev()).all( path.segments
|(a, b)| a.identifier.name == *b, .iter()
) .rev()
.zip(segments.iter().rev())
.all(|(a, b)| a.identifier.name == *b)
} }
/// Get the definition associated to a path. /// Get the definition associated to a path.
@ -281,9 +280,9 @@ pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
let cstore = &cx.tcx.sess.cstore; let cstore = &cx.tcx.sess.cstore;
let crates = cstore.crates(); let crates = cstore.crates();
let krate = crates.iter().find( let krate = crates
|&&krate| cstore.crate_name(krate) == path[0], .iter()
); .find(|&&krate| cstore.crate_name(krate) == path[0]);
if let Some(krate) = krate { if let Some(krate) = krate {
let krate = DefId { let krate = DefId {
krate: *krate, krate: *krate,
@ -336,14 +335,9 @@ pub fn implements_trait<'a, 'tcx>(
ty_params: &[Ty<'tcx>], ty_params: &[Ty<'tcx>],
) -> bool { ) -> bool {
let ty = cx.tcx.erase_regions(&ty); let ty = cx.tcx.erase_regions(&ty);
let obligation = cx.tcx.predicate_for_trait_def( let obligation =
cx.param_env, cx.tcx
traits::ObligationCause::dummy(), .predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
trait_id,
0,
ty,
ty_params,
);
cx.tcx.infer_ctxt().enter(|infcx| { cx.tcx.infer_ctxt().enter(|infcx| {
traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation) traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
}) })
@ -522,30 +516,27 @@ pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
if node_id == parent_id { if node_id == parent_id {
return None; return None;
} }
map.find(parent_id).and_then( map.find(parent_id)
|node| if let Node::NodeExpr(parent) = .and_then(|node| if let Node::NodeExpr(parent) = node {
node
{
Some(parent) Some(parent)
} else { } else {
None None
}, })
)
} }
pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> { pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
let map = &cx.tcx.hir; let map = &cx.tcx.hir;
let enclosing_node = map.get_enclosing_scope(node).and_then(|enclosing_id| { let enclosing_node = map.get_enclosing_scope(node)
map.find(enclosing_id) .and_then(|enclosing_id| map.find(enclosing_id));
});
if let Some(node) = enclosing_node { if let Some(node) = enclosing_node {
match node { match node {
Node::NodeBlock(block) => Some(block), Node::NodeBlock(block) => Some(block),
Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => { Node::NodeItem(&Item {
match cx.tcx.hir.body(eid).value.node { node: ItemFn(_, _, _, _, _, eid),
..
}) => match cx.tcx.hir.body(eid).value.node {
ExprBlock(ref block) => Some(block), ExprBlock(ref block) => Some(block),
_ => None, _ => None,
}
}, },
_ => None, _ => None,
} }
@ -704,9 +695,9 @@ impl LimitStack {
Self { stack: vec![limit] } Self { stack: vec![limit] }
} }
pub fn limit(&self) -> u64 { pub fn limit(&self) -> u64 {
*self.stack.last().expect( *self.stack
"there should always be a value in the stack", .last()
) .expect("there should always be a value in the stack")
} }
pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) { pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
let stack = &mut self.stack; let stack = &mut self.stack;
@ -741,9 +732,10 @@ fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'
/// See also `is_direct_expn_of`. /// See also `is_direct_expn_of`.
pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> { pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
loop { loop {
let span_name_span = span.ctxt().outer().expn_info().map(|ei| { let span_name_span = span.ctxt()
(ei.callee.name(), ei.call_site) .outer()
}); .expn_info()
.map(|ei| (ei.callee.name(), ei.call_site));
match span_name_span { match span_name_span {
Some((mac_name, new_span)) if mac_name == name => return Some(new_span), Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
@ -763,9 +755,10 @@ pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
/// `bar!` by /// `bar!` by
/// `is_direct_expn_of`. /// `is_direct_expn_of`.
pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> { pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
let span_name_span = span.ctxt().outer().expn_info().map(|ei| { let span_name_span = span.ctxt()
(ei.callee.name(), ei.call_site) .outer()
}); .expn_info()
.map(|ei| (ei.callee.name(), ei.call_site));
match span_name_span { match span_name_span {
Some((mac_name, new_span)) if mac_name == name => Some(new_span), Some((mac_name, new_span)) if mac_name == name => Some(new_span),
@ -800,7 +793,11 @@ pub fn camel_case_until(s: &str) -> usize {
return i; return i;
} }
} }
if up { last_i } else { s.len() } if up {
last_i
} else {
s.len()
}
} }
/// Return index of the last camel-case component of `s`. /// Return index of the last camel-case component of `s`.
@ -844,9 +841,9 @@ pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'t
// <'b> Foo<'b>` but // <'b> Foo<'b>` but
// not for type parameters. // not for type parameters.
pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
cx.tcx.infer_ctxt().enter(|infcx| { cx.tcx
infcx.can_eq(cx.param_env, a, b).is_ok() .infer_ctxt()
}) .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
} }
/// Return whether the given type is an `unsafe` function. /// Return whether the given type is an `unsafe` function.
@ -875,36 +872,28 @@ pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
} }
match pat.node { match pat.node {
PatKind::Binding(..) | PatKind::Binding(..) | PatKind::Wild => false,
PatKind::Wild => false, PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
PatKind::Box(ref pat) | PatKind::Lit(..) | PatKind::Range(..) => true,
PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
PatKind::Lit(..) |
PatKind::Range(..) => true,
PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id), PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)), PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
PatKind::Struct(ref qpath, ref fields, _) => { PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
if is_enum_variant(cx, qpath, pat.hir_id) {
true true
} else { } else {
are_refutable(cx, fields.iter().map(|field| &*field.node.pat)) are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
}
}, },
PatKind::TupleStruct(ref qpath, ref pats, _) => { PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
if is_enum_variant(cx, qpath, pat.hir_id) {
true true
} else { } else {
are_refutable(cx, pats.iter().map(|pat| &**pat)) are_refutable(cx, pats.iter().map(|pat| &**pat))
}
}, },
PatKind::Slice(ref head, ref middle, ref tail) => { PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
are_refutable(
cx, cx,
head.iter().chain(middle).chain(tail.iter()).map( head.iter()
|pat| &**pat, .chain(middle)
.chain(tail.iter())
.map(|pat| &**pat),
), ),
)
},
} }
} }
@ -1029,9 +1018,9 @@ pub fn is_try(expr: &Expr) -> Option<&Expr> {
} }
pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> { pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> {
ty.layout(cx.tcx, cx.param_env).ok().map(|layout| { ty.layout(cx.tcx, cx.param_env)
layout.size(cx.tcx).bytes() .ok()
}) .map(|layout| layout.size(cx.tcx).bytes())
} }
/// Returns true if the lint is allowed in the current context /// Returns true if the lint is allowed in the current context

View file

@ -33,9 +33,7 @@ pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
impl<'a> Display for Sugg<'a> { impl<'a> Display for Sugg<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match *self { match *self {
Sugg::NonParen(ref s) | Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
Sugg::MaybeParen(ref s) |
Sugg::BinOp(_, ref s) => s.fmt(f),
} }
} }
} }
@ -178,12 +176,10 @@ impl<'a> Sugg<'a> {
match self { match self {
Sugg::NonParen(..) => self, Sugg::NonParen(..) => self,
// (x) and (x).y() both don't need additional parens // (x) and (x).y() both don't need additional parens
Sugg::MaybeParen(sugg) => { Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
if sugg.starts_with('(') && sugg.ends_with(')') {
Sugg::MaybeParen(sugg) Sugg::MaybeParen(sugg)
} else { } else {
Sugg::NonParen(format!("({})", sugg).into()) Sugg::NonParen(format!("({})", sugg).into())
}
}, },
Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()), Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
} }
@ -293,12 +289,24 @@ pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
let lhs = ParenHelper::new(lhs_paren, lhs); let lhs = ParenHelper::new(lhs_paren, lhs);
let rhs = ParenHelper::new(rhs_paren, rhs); let rhs = ParenHelper::new(rhs_paren, rhs);
let sugg = match op { let sugg = match op {
AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | AssocOp::Divide | AssocOp::Equal | AssocOp::Add |
AssocOp::Greater | AssocOp::GreaterEqual | AssocOp::LAnd | AssocOp::LOr | AssocOp::Less | AssocOp::BitAnd |
AssocOp::LessEqual | AssocOp::Modulus | AssocOp::Multiply | AssocOp::NotEqual | AssocOp::ShiftLeft | AssocOp::BitOr |
AssocOp::ShiftRight | AssocOp::Subtract => { AssocOp::BitXor |
format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs) AssocOp::Divide |
}, AssocOp::Equal |
AssocOp::Greater |
AssocOp::GreaterEqual |
AssocOp::LAnd |
AssocOp::LOr |
AssocOp::Less |
AssocOp::LessEqual |
AssocOp::Modulus |
AssocOp::Multiply |
AssocOp::NotEqual |
AssocOp::ShiftLeft |
AssocOp::ShiftRight |
AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
AssocOp::Inplace => format!("in ({}) {}", lhs, rhs), AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
AssocOp::Assign => format!("{} = {}", lhs, rhs), AssocOp::Assign => format!("{} = {}", lhs, rhs),
AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs), AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
@ -343,7 +351,16 @@ fn associativity(op: &AssocOp) -> Associativity {
match *op { match *op {
Inplace | Assign | AssignOp(_) => Associativity::Right, Inplace | Assign | AssignOp(_) => Associativity::Right,
Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both, Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight | Divide |
Equal |
Greater |
GreaterEqual |
Less |
LessEqual |
Modulus |
NotEqual |
ShiftLeft |
ShiftRight |
Subtract => Associativity::Left, Subtract => Associativity::Left,
DotDot | DotDotDot => Associativity::None, DotDot | DotDotDot => Associativity::None,
} }
@ -393,9 +410,8 @@ fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
/// before it on its line. /// before it on its line.
fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> { fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
let lo = cx.sess().codemap().lookup_char_pos(span.lo()); let lo = cx.sess().codemap().lookup_char_pos(span.lo());
if let Some(line) = lo.file.get_line( if let Some(line) = lo.file
lo.line - 1, /* line numbers in `Loc` are 1-based */ .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
)
{ {
if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') { if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
// we can mix char and byte positions here because we only consider `[ \t]` // we can mix char and byte positions here because we only consider `[ \t]`

View file

@ -72,14 +72,12 @@ fn check_vec_macro(cx: &LateContext, vec_args: &higher::VecArgs, span: Span) {
return; return;
} }
}, },
higher::VecArgs::Vec(args) => { higher::VecArgs::Vec(args) => if let Some(last) = args.iter().last() {
if let Some(last) = args.iter().last() {
let span = args[0].span.to(last.span); let span = args[0].span.to(last.span);
format!("&[{}]", snippet(cx, span, "..")).into() format!("&[{}]", snippet(cx, span, "..")).into()
} else { } else {
"&[]".into() "&[]".into()
}
}, },
}; };

View file

@ -1,4 +1,4 @@
use consts::{Constant, constant_simple, FloatWidth}; use consts::{constant_simple, Constant, FloatWidth};
use rustc::lint::*; use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use utils::span_help_and_lint; use utils::span_help_and_lint;

View file

@ -1,12 +1,11 @@
#![feature(plugin_registrar, rustc_private)] #![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
extern crate rustc_plugin; extern crate rustc_plugin;
extern crate syntax;
use syntax::codemap::Span; use syntax::codemap::Span;
use syntax::tokenstream::TokenTree; use syntax::tokenstream::TokenTree;
use syntax::ext::base::{ExtCtxt, MacResult, MacEager}; use syntax::ext::base::{ExtCtxt, MacEager, MacResult};
use syntax::ext::build::AstBuilder; // trait for expr_usize use syntax::ext::build::AstBuilder; // trait for expr_usize
use rustc_plugin::Registry; use rustc_plugin::Registry;

View file

@ -45,13 +45,8 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
descriptions: &rustc_errors::registry::Registry, descriptions: &rustc_errors::registry::Registry,
output: ErrorOutputType, output: ErrorOutputType,
) -> Compilation { ) -> Compilation {
self.default.early_callback( self.default
matches, .early_callback(matches, sopts, cfg, descriptions, output)
sopts,
cfg,
descriptions,
output,
)
} }
fn no_input( fn no_input(
&mut self, &mut self,
@ -62,14 +57,8 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
ofile: &Option<PathBuf>, ofile: &Option<PathBuf>,
descriptions: &rustc_errors::registry::Registry, descriptions: &rustc_errors::registry::Registry,
) -> Option<(Input, Option<PathBuf>)> { ) -> Option<(Input, Option<PathBuf>)> {
self.default.no_input( self.default
matches, .no_input(matches, sopts, cfg, odir, ofile, descriptions)
sopts,
cfg,
odir,
ofile,
descriptions,
)
} }
fn late_callback( fn late_callback(
&mut self, &mut self,
@ -79,13 +68,8 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
odir: &Option<PathBuf>, odir: &Option<PathBuf>,
ofile: &Option<PathBuf>, ofile: &Option<PathBuf>,
) -> Compilation { ) -> Compilation {
self.default.late_callback( self.default
matches, .late_callback(matches, sess, input, odir, ofile)
sess,
input,
odir,
ofile,
)
} }
fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> { fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
let mut control = self.default.build_controller(sess, matches); let mut control = self.default.build_controller(sess, matches);
@ -203,8 +187,8 @@ pub fn main() {
.skip(2) .skip(2)
.find(|val| val.starts_with("--manifest-path=")); .find(|val| val.starts_with("--manifest-path="));
let mut metadata = let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref))
if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) { {
metadata metadata
} else { } else {
let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n")); let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
@ -359,7 +343,6 @@ fn process<I>(old_args: I) -> Result<(), i32>
where where
I: Iterator<Item = String>, I: Iterator<Item = String>,
{ {
let mut args = vec!["rustc".to_owned()]; let mut args = vec!["rustc".to_owned()];
let mut found_dashes = false; let mut found_dashes = false;

View file

@ -29,6 +29,8 @@ fn compile_test() {
prepare_env(); prepare_env();
run_mode("run-pass", "run-pass"); run_mode("run-pass", "run-pass");
run_mode("ui", "ui"); run_mode("ui", "ui");
#[cfg(target_os = "windows")] run_mode("ui-windows", "ui"); #[cfg(target_os = "windows")]
#[cfg(not(target_os = "windows"))] run_mode("ui-posix", "ui"); run_mode("ui-windows", "ui");
#[cfg(not(target_os = "windows"))]
run_mode("ui-posix", "ui");
} }

View file

@ -5,7 +5,7 @@
extern crate compiletest_rs as compiletest; extern crate compiletest_rs as compiletest;
extern crate test; extern crate test;
use std::env::{var, set_var}; use std::env::{set_var, var};
use std::path::PathBuf; use std::path::PathBuf;
use test::TestPaths; use test::TestPaths;

View file

@ -1,14 +1,12 @@
#![feature(plugin)] #![feature(plugin)]
#![plugin(clippy)] #![plugin(clippy)]
#![allow(warnings)] #![allow(warnings)]
// this should compile in a reasonable amount of time // this should compile in a reasonable amount of time
fn rust_type_id(name: &str) { fn rust_type_id(name: &str) {
if "bool" == &name[..] || "uint" == &name[..] || "u8" == &name[..] || "u16" == &name[..] || if "bool" == &name[..] || "uint" == &name[..] || "u8" == &name[..] || "u16" == &name[..] || "u32" == &name[..] ||
"u32" == &name[..] || "f32" == &name[..] || "f64" == &name[..] || "i8" == &name[..] || "f32" == &name[..] || "f64" == &name[..] || "i8" == &name[..] || "i16" == &name[..] ||
"i16" == &name[..] || "i32" == &name[..] || "i32" == &name[..] || "i64" == &name[..] || "Self" == &name[..] || "str" == &name[..]
"i64" == &name[..] || "Self" == &name[..] || "str" == &name[..]
{ {
unreachable!(); unreachable!();
} }

View file

@ -21,13 +21,11 @@ fn test_overlapping() {
assert_eq!(None, overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])); assert_eq!(None, overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))]));
assert_eq!( assert_eq!(
None, None,
overlapping( overlapping(&[
&[
sp(1, Bound::Included(4)), sp(1, Bound::Included(4)),
sp(5, Bound::Included(6)), sp(5, Bound::Included(6)),
sp(10, Bound::Included(11)), sp(10, Bound::Included(11))
], ],)
)
); );
assert_eq!( assert_eq!(
Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))), Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
@ -35,12 +33,10 @@ fn test_overlapping() {
); );
assert_eq!( assert_eq!(
Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))), Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
overlapping( overlapping(&[
&[
sp(1, Bound::Included(4)), sp(1, Bound::Included(4)),
sp(5, Bound::Included(6)), sp(5, Bound::Included(6)),
sp(6, Bound::Included(11)), sp(6, Bound::Included(11))
], ],)
)
); );
} }

View file

@ -1,7 +1,8 @@
// Tests for the various helper functions used by the needless_continue // Tests for the various helper functions used by the needless_continue
// lint that don't belong in utils. // lint that don't belong in utils.
extern crate clippy_lints; extern crate clippy_lints;
use clippy_lints::needless_continue::{erode_from_back, erode_block, erode_from_front}; use clippy_lints::needless_continue::{erode_block, erode_from_back, erode_from_front};
#[test] #[test]
#[cfg_attr(rustfmt, rustfmt_skip)] #[cfg_attr(rustfmt, rustfmt_skip)]