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::hir::*;
use std::f64::consts as f64;
use syntax::ast::{Lit, LitKind, FloatTy};
use syntax::ast::{FloatTy, Lit, LitKind};
use syntax::symbol;
use utils::span_lint;

View File

@ -55,8 +55,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic {
match expr.node {
hir::ExprBinary(ref op, ref l, ref r) => {
match op.node {
hir::BiAnd | 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,
hir::BiAnd |
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));

View File

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

View File

@ -1,7 +1,7 @@
use rustc::hir;
use rustc::lint::*;
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};
/// **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 op.node == binop.node {
let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
span_lint_and_then(cx,
span_lint_and_then(
cx,
MISREFACTORED_ASSIGN_OP,
expr.span,
"variable appears on both sides of an assignment operation",
|db| if let (Some(snip_a), Some(snip_r)) =
(snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) {
db.span_suggestion(expr.span,
(snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
{
db.span_suggestion(
expr.span,
"replace it with",
format!("{} {}= {}",
snip_a,
op.node.as_str(),
snip_r));
});
format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
);
},
);
};
// lhs op= l op r
if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
@ -167,8 +169,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
BitXor: BiBitXor,
Shr: BiShr,
Shl: BiShl
)
{
) {
span_lint_and_then(
cx,
ASSIGN_OP_PATTERN,
@ -193,7 +194,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
// a = b commutative_op a
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
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 => {
lint(assignee, l);
},

View File

@ -7,7 +7,7 @@ use rustc::ty::{self, TyCtxt};
use semver::Version;
use syntax::ast::{Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
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)]`,
/// 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)
}
match item.node {
ItemExternCrate(_) |
ItemUse(_, _) => {
ItemExternCrate(_) | ItemUse(_, _) => {
for attr in &item.attrs {
if let Some(ref lint_list) = attr.meta_item_list() {
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() {
match stmt.node {
StmtDecl(_, _) => true,
StmtExpr(ref expr, _) |
StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
}
} else {
block.expr.as_ref().map_or(
false,
|e| is_relevant_expr(tcx, tables, e),
)
block
.expr
.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 {
ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
ExprRet(None) |
ExprBreak(_, None) => false,
ExprCall(ref path_expr, _) => {
if let ExprPath(ref qpath) = path_expr.node {
ExprRet(None) | ExprBreak(_, None) => false,
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();
!match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
} else {
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) {
match cmp_op {
BiEq | BiNe => {
match bit_op {
BiBitAnd => {
if mask_value & cmp_value != cmp_value {
BiEq | BiNe => match bit_op {
BiBitAnd => if mask_value & cmp_value != cmp_value {
if cmp_value != 0 {
span_lint(
cx,
@ -176,10 +174,8 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
}
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
},
BiBitOr => {
if mask_value | cmp_value != cmp_value {
BiBitOr => if mask_value | cmp_value != cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
@ -190,15 +186,11 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
cmp_value
),
);
}
},
_ => (),
}
},
BiLt | BiGe => {
match bit_op {
BiBitAnd => {
if mask_value < cmp_value {
BiLt | BiGe => match bit_op {
BiBitAnd => if mask_value < cmp_value {
span_lint(
cx,
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 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
},
BiBitOr => {
if mask_value >= cmp_value {
BiBitOr => if mask_value >= cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
@ -227,16 +217,12 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
);
} else {
check_ineffective_lt(cx, *span, mask_value, cmp_value, "|");
}
},
BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"),
_ => (),
}
},
BiLe | BiGt => {
match bit_op {
BiBitAnd => {
if mask_value <= cmp_value {
BiLe | BiGt => match bit_op {
BiBitAnd => if mask_value <= cmp_value {
span_lint(
cx,
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 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
}
},
BiBitOr => {
if mask_value > cmp_value {
BiBitOr => if mask_value > cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
@ -265,11 +249,9 @@ fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value:
);
} else {
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 {
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::intravisit::{Visitor, walk_expr, NestedVisitorMap};
use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use utils::*;
/// **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 {
let span = block.expr.as_ref().map_or_else(
|| block.stmts[0].span,
|e| e.span,
);
let span = block
.expr
.as_ref()
.map_or_else(|| block.stmts[0].span, |e| e.span);
if in_macro(span) || differing_macro_contexts(expr.span, span) {
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::intravisit::*;
use syntax::ast::{LitKind, DUMMY_NODE_ID, NodeId};
use syntax::codemap::{DUMMY_SP, dummy_spanned, Span};
use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
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
/// concisely.
@ -96,26 +96,23 @@ impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
if !in_macro(e.span) {
match e.node {
ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
ExprBinary(binop, ref lhs, ref rhs) => {
match binop.node {
ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
_ => (),
}
},
ExprLit(ref lit) => {
match lit.node {
ExprLit(ref lit) => match lit.node {
LitKind::Bool(true) => return Ok(Bool::True),
LitKind::Bool(false) => return Ok(Bool::False),
_ => (),
}
},
_ => (),
}
}
for (n, expr) in self.terminals.iter().enumerate() {
if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
#[allow(cast_possible_truncation)] return Ok(Bool::Term(n as u8));
#[allow(cast_possible_truncation)]
return Ok(Bool::Term(n as u8));
}
let negated = match e.node {
ExprBinary(binop, ref lhs, ref rhs) => {
@ -141,13 +138,15 @@ impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
_ => continue,
};
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();
self.terminals.push(e);
if n < 32 {
#[allow(cast_possible_truncation)] Ok(Bool::Term(n as u8))
#[allow(cast_possible_truncation)]
Ok(Bool::Term(n as u8))
} else {
Err("too many literals".to_owned())
}
@ -167,14 +166,12 @@ fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
s.push_str("false");
s
},
Not(ref inner) => {
match **inner {
Not(ref inner) => match **inner {
And(_) | Or(_) => {
s.push('!');
recurse(true, cx, inner, terminals, s)
},
Term(n) => {
if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
Term(n) => if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
let op = match binop.node {
BiEq => " != ",
BiNe => " == ",
@ -194,13 +191,11 @@ fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
} else {
s.push('!');
recurse(false, cx, inner, terminals, s)
}
},
_ => {
s.push('!');
recurse(false, cx, inner, terminals, s)
},
}
},
And(ref v) => {
if brackets {
@ -319,7 +314,6 @@ impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
cx: self.cx,
};
if let Ok(expr) = h2q.run(e) {
if h2q.terminals.len() > 8 {
// QMC has exponentially slow behavior as the number of terminals increases
// 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 {
ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
ExprUnary(UnNot, ref inner) => {
if self.cx.tables.node_types()[inner.hir_id].is_bool() {
ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
self.bool_expr(e);
} else {
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 {
PatKind::Binding(_, _, ref spname, _) => Some(spname.node),
PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
PatKind::Box(ref p) |
PatKind::Ref(ref p, _) => get_pat_name(&*p),
PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
_ => None,
}
}
fn get_path_name(expr: &Expr) -> Option<Name> {
match expr.node {
ExprBox(ref e) |
ExprAddrOf(_, ref e) |
ExprUnary(UnOp::UnDeref, ref e) => get_path_name(e),
ExprBlock(ref b) => {
if b.stmts.is_empty() {
ExprBox(ref e) | ExprAddrOf(_, ref e) | 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))
} else {
None
}
},
ExprPath(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
_ => None,

View File

@ -15,7 +15,7 @@
use rustc::lint::*;
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;
/// **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) {
match expr.node {
ast::ExprKind::If(ref check, ref then, ref else_) => {
if let Some(ref else_) = *else_ {
ast::ExprKind::If(ref check, ref then, ref else_) => if let Some(ref else_) = *else_ {
check_collapsible_maybe_if_let(cx, else_);
} else {
check_collapsible_no_if_let(cx, expr, check, then);
}
},
ast::ExprKind::IfLet(_, _, _, Some(ref 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()) {
match stmt.node {
ast::StmtKind::Expr(ref expr) |
ast::StmtKind::Semi(ref expr) => Some(expr),
ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
_ => None,
}
} else {

View File

@ -5,8 +5,8 @@ use rustc::hir::def::Def;
use rustc_const_eval::lookup_const_by_id;
use rustc_const_math::ConstInt;
use rustc::hir::*;
use rustc::ty::{self, TyCtxt, Ty};
use rustc::ty::subst::{Substs, Subst};
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::{Subst, Substs};
use std::cmp::Ordering::{self, Equal};
use std::cmp::PartialOrd;
use std::hash::{Hash, Hasher};
@ -110,8 +110,7 @@ impl Hash for Constant {
Constant::Bool(b) => {
b.hash(state);
},
Constant::Vec(ref v) |
Constant::Tuple(ref v) => {
Constant::Vec(ref v) | Constant::Tuple(ref v) => {
v.hash(state);
},
Constant::Repeat(ref c, l) => {
@ -125,12 +124,10 @@ impl Hash for Constant {
impl PartialOrd for Constant {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => {
if l_sty == r_sty {
(&Constant::Str(ref ls, ref l_sty), &Constant::Str(ref rs, ref r_sty)) => if l_sty == r_sty {
Some(ls.cmp(rs))
} else {
None
}
},
(&Constant::Char(ref l), &Constant::Char(ref r)) => Some(l.cmp(r)),
(&Constant::Int(l), &Constant::Int(r)) => Some(l.cmp(&r)),
@ -147,13 +144,12 @@ impl PartialOrd for Constant {
}
},
(&Constant::Bool(ref l), &Constant::Bool(ref r)) => Some(l.cmp(r)),
(&Constant::Tuple(ref l), &Constant::Tuple(ref r)) |
(&Constant::Vec(ref l), &Constant::Vec(ref r)) => l.partial_cmp(r),
(&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => {
match lv.partial_cmp(rv) {
(&Constant::Tuple(ref l), &Constant::Tuple(ref r)) | (&Constant::Vec(ref l), &Constant::Vec(ref r)) => {
l.partial_cmp(r)
},
(&Constant::Repeat(ref lv, ref ls), &Constant::Repeat(ref rv, ref rs)) => match lv.partial_cmp(rv) {
Some(Equal) => Some(ls.cmp(rs)),
x => x,
}
},
_ => 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::ByteStr(ref s) => Constant::Binary(s.clone()),
LitKind::Char(c) => Constant::Char(c),
LitKind::Int(n, hint) => {
match (&ty.sty, hint) {
(&ty::TyInt(ity), _) |
(_, Signed(ity)) => {
LitKind::Int(n, hint) => match (&ty.sty, hint) {
(&ty::TyInt(ity), _) | (_, Signed(ity)) => {
Constant::Int(ConstInt::new_signed_truncating(n as i128, ity, tcx.sess.target.int_type))
},
(&ty::TyUint(uty), _) |
(_, Unsigned(uty)) => {
(&ty::TyUint(uty), _) | (_, Unsigned(uty)) => {
Constant::Int(ConstInt::new_unsigned_truncating(n as u128, uty, tcx.sess.target.uint_type))
},
_ => bug!(),
}
},
LitKind::Float(ref is, ty) => Constant::Float(is.to_string(), ty.into()),
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))
},
ExprUnary(op, ref operand) => {
self.expr(operand).and_then(|o| match op {
ExprUnary(op, ref operand) => self.expr(operand).and_then(|o| match op {
UnNot => constant_not(&o),
UnNeg => constant_negate(o),
UnDeref => Some(o),
})
},
}),
ExprBinary(op, ref left, ref right) => self.binop(op, left, right),
// TODO: add other expressions
_ => None,
@ -287,8 +277,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
fn fetch_path(&mut self, qpath: &QPath, id: HirId) -> Option<Constant> {
let def = self.tables.qpath_def(qpath, id);
match def {
Def::Const(def_id) |
Def::AssociatedConst(def_id) => {
Def::Const(def_id) | Def::AssociatedConst(def_id) => {
let substs = self.tables.node_substs(id);
let substs = if self.substs.is_empty() {
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),
(BiAnd, Constant::Bool(false), _) => Some(Constant::Bool(false)),
(BiOr, Constant::Bool(true), _) => Some(Constant::Bool(true)),
(BiAnd, Constant::Bool(true), Some(r)) |
(BiOr, Constant::Bool(false), Some(r)) => Some(r),
(BiAnd, Constant::Bool(true), 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::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)),

View File

@ -6,7 +6,7 @@ use std::collections::hash_map::Entry;
use syntax::symbol::InternedString;
use syntax::util::small_vector::SmallVector;
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.
///
@ -114,7 +114,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if !in_macro(expr.span) {
// 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 {
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_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, Ty<'tcx>>) {
match pat.node {
PatKind::Box(ref pat) |
PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
PatKind::TupleStruct(_, ref pats, _) => {
for pat in pats {
PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
bindings_impl(cx, pat, map);
}
},
PatKind::Binding(_, _, ref ident, ref as_pat) => {
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);
}
},
PatKind::Struct(_, ref fields, _) => {
for pat in fields {
PatKind::Struct(_, ref fields, _) => for pat in fields {
bindings_impl(cx, &pat.node.pat, map);
}
},
PatKind::Tuple(ref fields, _) => {
for pat in fields {
PatKind::Tuple(ref fields, _) => for pat in fields {
bindings_impl(cx, pat, map);
}
},
PatKind::Slice(ref lhs, ref mid, ref rhs) => {
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);
}
},
PatKind::Lit(..) |
PatKind::Range(..) |
PatKind::Wild |
PatKind::Path(..) => (),
PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
}
}
@ -335,12 +329,10 @@ where
for expr in exprs {
match map.entry(hash(expr)) {
Entry::Occupied(o) => {
for o in o.get() {
Entry::Occupied(o) => for o in o.get() {
if eq(o, expr) {
return Some((o, expr));
}
}
},
Entry::Vacant(v) => {
v.insert(vec![expr]);

View File

@ -4,11 +4,11 @@ use rustc::cfg::CFG;
use rustc::lint::*;
use rustc::hir::*;
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::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.
///
@ -31,7 +31,9 @@ pub struct CyclomaticComplexity {
impl CyclomaticComplexity {
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]) {
self.limit.push_attrs(
cx.sess(),
attrs,
"cyclomatic_complexity",
);
self.limit
.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
}
fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
self.limit.pop_attrs(
cx.sess(),
attrs,
"cyclomatic_complexity",
);
self.limit
.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
}
}

View File

@ -3,7 +3,7 @@ use rustc::ty::{self, Ty};
use rustc::hir::*;
use syntax::codemap::Span;
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`
/// 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,
// Some types are not Clone by default but could be cloned “by hand” if necessary
ty::TyAdt(def, substs) => {
for variant in &def.variants {
ty::TyAdt(def, substs) => for variant in &def.variants {
for field in &variant.fields {
match field.ty(cx.tcx, substs).sty {
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,
item.span,
"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 rustc::lint::*;
use syntax::ast;
use syntax::codemap::{Span, BytePos};
use syntax::codemap::{BytePos, Span};
use syntax_pos::Pos;
use utils::span_lint;
@ -37,7 +37,9 @@ pub struct Doc {
impl Doc {
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 {
match event {
Start(CodeBlock(_)) |
Start(Code) => in_code = true,
End(CodeBlock(_)) |
End(Code) => in_code = false,
Start(CodeBlock(_)) | Start(Code) => in_code = true,
End(CodeBlock(_)) | End(Code) => in_code = false,
Start(_tag) | End(_tag) => (), // We don't care about other tags
Html(_html) |
InlineHtml(_html) => (), // HTML is weird, just ignore it
Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
SoftBreak => (),
HardBreak => (),
FootnoteReference(text) |
Text(text) => {
FootnoteReference(text) | Text(text) => {
if !in_code {
let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
Ok(o) => o,

View File

@ -1,5 +1,5 @@
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.
///
@ -31,30 +31,23 @@ impl LintPass for DoubleParens {
impl EarlyLintPass for DoubleParens {
fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
match expr.node {
ExprKind::Paren(ref in_paren) => {
match in_paren.node {
ExprKind::Paren(_) |
ExprKind::Tup(_) => {
ExprKind::Paren(ref in_paren) => match in_paren.node {
ExprKind::Paren(_) | ExprKind::Tup(_) => {
cx.span_lint(DOUBLE_PARENS, expr.span, "Consider removing unnecessary double parentheses");
},
_ => {},
}
},
ExprKind::Call(_, ref params) => {
if params.len() == 1 {
ExprKind::Call(_, ref params) => if params.len() == 1 {
let param = &params[0];
if let ExprKind::Paren(_) = param.node {
cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses");
}
}
},
ExprKind::MethodCall(_, ref params) => {
if params.len() == 2 {
ExprKind::MethodCall(_, ref params) => if params.len() == 2 {
let param = &params[1];
if let ExprKind::Paren(_) = param.node {
cx.span_lint(DOUBLE_PARENS, param.span, "Consider removing unnecessary double parentheses");
}
}
},
_ => {},
}

View File

@ -1,7 +1,7 @@
use rustc::lint::*;
use rustc::ty;
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
/// 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);
if let ItemEnum(..) = item.node {
let ty = cx.tcx.type_of(did);
let adt = ty.ty_adt_def().expect(
"already checked whether this is an enum",
);
let adt = ty.ty_adt_def()
.expect("already checked whether this is an enum");
if adt.variants.is_empty() {
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");

View File

@ -1,5 +1,5 @@
use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc::lint::*;
use syntax::codemap::Span;
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); }`
// we can give a better error message
let sole_expr = {
else_block.is_none() &&
if let ExprBlock(ref then_block) = then_block.node {
else_block.is_none() && if let ExprBlock(ref then_block) = then_block.node {
(then_block.expr.is_some() as usize) + then_block.stmts.len() == 1
} else {
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 param_env = ty::ParamEnv::empty(Reveal::UserFacing);
let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did);
let bad = match cx.tcx.at(expr.span).const_eval(
param_env.and((did, substs)),
) {
let bad = match cx.tcx
.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(Isize(Is64(i)))) => i64::from(i as i32) != i,
_ => false,

View File

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

View File

@ -1,6 +1,6 @@
use rustc::hir::*;
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
/// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
@ -82,8 +82,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp {
#[allow(match_same_arms)]
match (&left.node, &right.node) {
// do not suggest to dereference literals
(&ExprLit(..), _) |
(_, &ExprLit(..)) => {},
(&ExprLit(..), _) | (_, &ExprLit(..)) => {},
// &foo == &bar
(&ExprAddrOf(_, ref l), &ExprAddrOf(_, ref r)) => {
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);
}
}
}
fn borrow(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, loan_cause: LoanCause) {
if let Categorization::Local(lid) = cmt.cat {

View File

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

View File

@ -1,9 +1,9 @@
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::ty;
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
/// 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) {
// Find a write to a local variable.
match expr.node {
ExprAssign(ref lhs, _) |
ExprAssignOp(_, ref lhs, _) => {
if let ExprPath(ref qpath) = lhs.node {
ExprAssign(ref lhs, _) | ExprAssignOp(_, ref lhs, _) => if let ExprPath(ref qpath) = lhs.node {
if let QPath::Resolved(_, ref path) = *qpath {
if path.segments.len() == 1 {
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);
}
}
}
},
_ => {},
}
}
fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
match stmt.node {
StmtExpr(ref e, _) |
StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
StmtDecl(ref d, _) => {
if let DeclLocal(ref local) = d.node {
if let Local { init: Some(ref e), .. } = **local {
StmtExpr(ref e, _) | StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
StmtDecl(ref d, _) => if let DeclLocal(ref local) = d.node {
if let Local {
init: Some(ref e), ..
} = **local
{
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(_, _, _) => {
walk_expr(vis, expr);
},
ExprBinary(op, _, _) |
ExprAssignOp(op, _, _) => {
ExprBinary(op, _, _) | ExprAssignOp(op, _, _) => {
if op.node == BiAnd || op.node == BiOr {
// x && y and x || y always evaluate x first, so these are
// 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 {
match stmt.node {
StmtExpr(ref expr, _) |
StmtSemi(ref expr, _) => check_expr(vis, expr),
StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => check_expr(vis, expr),
StmtDecl(ref decl, _) => {
// If the declaration is of a local variable, check its initializer
// 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),
_ => None,
};
local.and_then(|local| local.init.as_ref()).map_or(
StopEarly::KeepGoing,
|expr| check_expr(vis, expr),
)
local
.and_then(|local| local.init.as_ref())
.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 () { () => [], }`
ExprMatch(ref matchee, _, _) => {
if let ExprTup(ref tup) = matchee.node {
ExprMatch(ref matchee, _, _) => if let ExprTup(ref tup) = matchee.node {
if tup.is_empty() {
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
// its bad when there is a \n after the “else”
if let Some(else_snippet) = snippet_opt(cx, else_span) {
let else_pos = else_snippet.find("else").expect(
"there must be a `else` here",
);
let else_pos = else_snippet
.find("else")
.expect("there must be a `else` here");
if else_snippet[else_pos..].contains('\n') {
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.
fn unsugar_if(expr: &ast::Expr) -> Option<(&P<ast::Block>, &Option<P<ast::Expr>>)> {
match expr.node {
ast::ExprKind::If(_, ref then, ref else_) |
ast::ExprKind::IfLet(_, _, ref then, ref else_) => Some((then, else_)),
ast::ExprKind::If(_, ref then, ref else_) | ast::ExprKind::IfLet(_, _, ref then, ref else_) => {
Some((then, else_))
},
_ => None,
}
}

View File

@ -6,7 +6,7 @@ use std::collections::HashSet;
use syntax::ast;
use syntax::abi::Abi;
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.
///
@ -60,7 +60,9 @@ pub struct Functions {
impl Functions {
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::hir::*;
use syntax::codemap::Span;
use utils::{span_lint, snippet, in_macro};
use utils::{in_macro, snippet, span_lint};
use syntax::attr::IntType::{SignedInt, UnsignedInt};
/// **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 match m {
0 => v.to_u128_unchecked() == 0,
-1 => {
match v.int_type() {
-1 => match v.int_type() {
SignedInt(_) => (v.to_u128_unchecked() as i128 == -1),
UnsignedInt(_) => false,
}
},
1 => v.to_u128_unchecked() == 1,
_ => unreachable!(),
}
{
} {
span_lint(
cx,
IDENTITY_OP,

View File

@ -1,6 +1,6 @@
use rustc::lint::*;
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
/// `Option`
@ -45,11 +45,8 @@ impl LintPass for Pass {
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if let ExprMatch(ref op, ref arms, MatchSource::IfLetDesugar { .. }) = expr.node {
if arms[0].pats.len() == 1 {
let good_method = match arms[0].pats[0].node {
PatKind::TupleStruct(ref path, ref pats, _) if pats.len() == 1 && pats[0].node == PatKind::Wild => {
if match_qpath(path, &paths::RESULT_OK) {
@ -68,16 +65,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
_ => return,
};
span_lint_and_then(cx,
span_lint_and_then(
cx,
IF_LET_REDUNDANT_PATTERN_MATCHING,
arms[0].pats[0].span,
&format!("redundant pattern matching, consider using `{}`", good_method),
|db| {
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::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.
///
@ -66,14 +66,13 @@ enum Finiteness {
Finite,
}
use self::Finiteness::{Infinite, MaybeInfinite, Finite};
use self::Finiteness::{Finite, Infinite, MaybeInfinite};
impl Finiteness {
fn and(self, b: Self) -> Self {
match (self, b) {
(Finite, _) | (_, Finite) => Finite,
(MaybeInfinite, _) |
(_, MaybeInfinite) => MaybeInfinite,
(MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite,
_ => Infinite,
}
}
@ -81,8 +80,7 @@ impl Finiteness {
fn or(self, b: Self) -> Self {
match (self, b) {
(Infinite, _) | (_, Infinite) => Infinite,
(MaybeInfinite, _) |
(_, MaybeInfinite) => MaybeInfinite,
(MaybeInfinite, _) | (_, MaybeInfinite) => MaybeInfinite,
_ => Finite,
}
}
@ -90,7 +88,11 @@ impl Finiteness {
impl From<bool> for Finiteness {
fn from(b: bool) -> Self {
if b { Infinite } else { Finite }
if b {
Infinite
} else {
Finite
}
}
}
@ -108,7 +110,7 @@ enum Heuristic {
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
/// that will be used to determine whether the method in question
@ -159,20 +161,15 @@ fn is_infinite(cx: &LateContext, expr: &Expr) -> Finiteness {
Finite
},
ExprBlock(ref block) => block.expr.as_ref().map_or(Finite, |e| is_infinite(cx, e)),
ExprBox(ref e) |
ExprAddrOf(_, ref e) => is_infinite(cx, e),
ExprCall(ref path, _) => {
if let ExprPath(ref qpath) = path.node {
ExprBox(ref e) | ExprAddrOf(_, ref e) => is_infinite(cx, e),
ExprCall(ref path, _) => if let ExprPath(ref qpath) = path.node {
match_qpath(qpath, &paths::REPEAT).into()
} else {
Finite
}
},
ExprStruct(..) => {
higher::range(expr)
ExprStruct(..) => higher::range(expr)
.map_or(false, |r| r.end.is_none())
.into()
},
.into(),
_ => Finite,
}
}
@ -220,22 +217,17 @@ fn complete_infinite_iter(cx: &LateContext, expr: &Expr) -> Finiteness {
}
}
if method.name == "last" && args.len() == 1 {
let not_double_ended = get_trait_def_id(cx,
&paths::DOUBLE_ENDED_ITERATOR)
.map_or(false, |id| {
!implements_trait(cx, cx.tables.expr_ty(&args[0]), id, &[])
});
let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR)
.map_or(false, |id| !implements_trait(cx, cx.tables.expr_ty(&args[0]), id, &[]));
if not_double_ended {
return is_infinite(cx, &args[0]);
}
}
},
ExprBinary(op, ref l, ref r) => {
if op.node.is_comparison() {
return is_infinite(cx, l).and(is_infinite(cx, r)).and(
MaybeInfinite,
);
}
ExprBinary(op, ref l, ref r) => if op.node.is_comparison() {
return is_infinite(cx, l)
.and(is_infinite(cx, r))
.and(MaybeInfinite);
}, // TODO: ExprLoop + Match
_ => (),
}

View File

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

View File

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

View File

@ -2,7 +2,7 @@
use rustc::lint::*;
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;
/// **What it does:** Checks for large size differences between variants on
@ -34,7 +34,9 @@ pub struct LargeEnumVariant {
impl LargeEnumVariant {
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);
if let ItemEnum(ref def, _) = item.node {
let ty = cx.tcx.type_of(did);
let adt = ty.ty_adt_def().expect(
"already checked whether this is an enum",
);
let adt = ty.ty_adt_def()
.expect("already checked whether this is an enum");
let mut smallest_variant: Option<(_, _)> = None;
let mut largest_variant: Option<(_, _)> = None;
@ -90,8 +91,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeEnumVariant {
|db| {
if variant.fields.len() == 1 {
let span = match def.variants[i].node.data {
VariantData::Struct(ref fields, _) |
VariantData::Tuple(ref fields, _) => fields[0].ty.span,
VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => {
fields[0].ty.span
},
VariantData::Unit(_) => unreachable!(),
};
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 is_named_self(cx: &LateContext, item: &TraitItemRef, name: &str) -> bool {
item.name == name &&
if let AssociatedItemKind::Method { has_self } = item.kind {
has_self &&
{
item.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
has_self && {
let did = cx.tcx.hir.local_def_id(item.id.node_id);
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()
.flat_map(|&i| cx.tcx.associated_items(i))
.any(|i| {
i.kind == ty::AssociatedKind::Method &&
i.method_has_self_argument &&
i.name == "is_empty" &&
i.kind == ty::AssociatedKind::Method && i.method_has_self_argument && i.name == "is_empty" &&
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 is_named_self(cx: &LateContext, item: &ImplItemRef, name: &str) -> bool {
item.name == name &&
if let AssociatedItemKind::Method { has_self } = item.kind {
has_self &&
{
item.name == name && if let AssociatedItemKind::Method { has_self } = item.kind {
has_self && {
let did = cx.tcx.hir.local_def_id(item.id.node_id);
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) {
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]) {
span_lint_and_sugg(
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.
fn has_is_empty_impl(cx: &LateContext, id: DefId) -> bool {
cx.tcx.inherent_impls(id).iter().any(|imp| {
cx.tcx.associated_items(*imp).any(
|item| is_is_empty(cx, &item),
)
cx.tcx
.associated_items(*imp)
.any(|item| is_is_empty(cx, &item))
})
}
let ty = &walk_ptrs_ty(cx.tables.expr_ty(expr));
match ty.sty {
ty::TyDynamic(..) => {
cx.tcx
ty::TyDynamic(..) => cx.tcx
.associated_items(ty.ty_to_def_id().expect("trait impl not found"))
.any(|item| is_is_empty(cx, &item))
},
ty::TyProjection(_) => {
ty.ty_to_def_id().map_or(
false,
|id| has_is_empty_impl(cx, id),
)
},
.any(|item| is_is_empty(cx, &item)),
ty::TyProjection(_) => 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::TyArray(..) | ty::TySlice(..) | ty::TyStr => true,
_ => false,

View File

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

View File

@ -2,10 +2,10 @@ use reexport::*;
use rustc::lint::*;
use rustc::hir::def::Def;
use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_ty, walk_ty_param_bound, walk_fn_decl, walk_generics, NestedVisitorMap};
use std::collections::{HashSet, HashMap};
use rustc::hir::intravisit::{walk_fn_decl, walk_generics, walk_ty, walk_ty_param_bound, NestedVisitorMap, Visitor};
use std::collections::{HashMap, HashSet};
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;
/// **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 {
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);
if checker.lifetimes_used_in_body {
return false;
@ -192,9 +194,9 @@ fn could_use_elision<'a, 'tcx: 'a>(
// no output lifetimes, check distinctness of input lifetimes
// only unnamed and static, ok
let unnamed_and_static = input_lts.iter().all(|lt| {
*lt == RefLt::Unnamed || *lt == RefLt::Static
});
let unnamed_and_static = input_lts
.iter()
.all(|lt| *lt == RefLt::Unnamed || *lt == RefLt::Static);
if unnamed_and_static {
return false;
}
@ -210,8 +212,8 @@ fn could_use_elision<'a, 'tcx: 'a>(
match (&input_lts[0], &output_lts[0]) {
(&RefLt::Named(n1), &RefLt::Named(n2)) if n1 == n2 => true,
(&RefLt::Named(_), &RefLt::Unnamed) => true,
_ => false, // already elided, different named lifetimes
// or something static going on
_ => false, /* already elided, different named lifetimes
* or something static going on */
}
} else {
false
@ -277,7 +279,11 @@ impl<'v, 't> RefVisitor<'v, 't> {
}
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) {
@ -285,8 +291,7 @@ impl<'v, 't> RefVisitor<'v, 't> {
if !last_path_segment.parenthesized && last_path_segment.lifetimes.is_empty() {
let hir_id = self.cx.tcx.hir.node_to_hir_id(ty.id);
match self.cx.tables.qpath_def(qpath, hir_id) {
Def::TyAlias(def_id) |
Def::Struct(def_id) => {
Def::TyAlias(def_id) | Def::Struct(def_id) => {
let generics = self.cx.tcx.generics_of(def_id);
for _ in generics.regions.as_slice() {
self.record(&None);
@ -318,12 +323,10 @@ impl<'a, 'tcx> Visitor<'tcx> for RefVisitor<'a, 'tcx> {
TyPath(ref path) => {
self.collect_anonymous_lifetimes(path, ty);
},
TyImplTrait(ref param_bounds) => {
for bound in param_bounds {
TyImplTrait(ref param_bounds) => for bound in param_bounds {
if let RegionTyParamBound(_) = *bound {
self.record(&None);
}
}
},
TyTraitObject(ref bounds, ref lt) => {
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
match visitor.into_vec() {
None => return false,
Some(lts) => {
for lt in lts {
Some(lts) => for lt in lts {
if !allowed_lts.contains(&lt) {
return true;
}
}
},
}
},

View File

@ -4,7 +4,7 @@
use rustc::lint::*;
use syntax::ast::*;
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
/// not contain underscores.
@ -195,33 +195,27 @@ enum WarningType {
impl WarningType {
pub fn display(&self, grouping_hint: &str, cx: &EarlyContext, span: &syntax_pos::Span) {
match *self {
WarningType::UnreadableLiteral => {
span_help_and_lint(
WarningType::UnreadableLiteral => span_help_and_lint(
cx,
UNREADABLE_LITERAL,
*span,
"long literal lacking separators",
&format!("consider: {}", grouping_hint),
)
},
WarningType::LargeDigitGroups => {
span_help_and_lint(
),
WarningType::LargeDigitGroups => span_help_and_lint(
cx,
LARGE_DIGIT_GROUPS,
*span,
"digit groups should be smaller",
&format!("consider: {}", grouping_hint),
)
},
WarningType::InconsistentDigitGrouping => {
span_help_and_lint(
),
WarningType::InconsistentDigitGrouping => span_help_and_lint(
cx,
INCONSISTENT_DIGIT_GROUPING,
*span,
"digits grouped inconsistently by underscores",
&format!("consider: {}", grouping_hint),
)
},
),
};
}
}

View File

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

View File

@ -2,8 +2,8 @@ use rustc::lint::*;
use rustc::hir::*;
use rustc::ty;
use syntax::ast;
use utils::{is_adjusted, match_qpath, match_trait_method, match_type, remove_blocks, paths, snippet,
span_help_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, iter_input_pats};
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};
/// **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) => {
if match_qpath(path, &paths::CLONE) {
ExprPath(ref path) => if match_qpath(path, &paths::CLONE) {
let type_name = get_type_name(cx, expr, &args[0]).unwrap_or("_");
span_help_and_lint(
cx,
@ -87,7 +86,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
),
&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::codemap::Span;
use utils::paths;
use utils::{match_type, snippet, span_note_and_lint, span_lint_and_then, span_lint_and_sugg, in_external_macro,
expr_block, walk_ptrs_ty, is_expn_of, remove_blocks, is_allowed};
use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_type, remove_blocks, snippet,
span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
use utils::sugg::Sugg;
/// **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 {
let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
(false, false) => {
Some(format!(
(false, false) => Some(format!(
"if {} {} else {}",
snippet(cx, ex.span, "b"),
expr_block(cx, true_expr, None, ".."),
expr_block(cx, false_expr, None, "..")
))
},
(false, true) => {
Some(format!(
)),
(false, true) => Some(format!(
"if {} {}",
snippet(cx, ex.span, "b"),
expr_block(cx, true_expr, None, "..")
))
},
)),
(true, false) => {
let test = Sugg::hir(cx, ex, "..");
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) {
if has_only_ref_pats(arms) {
if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
span_lint_and_then(cx,
span_lint_and_then(
cx,
MATCH_REF_PATS,
expr.span,
"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 template = match_template(expr.span, source, &inner);
db.span_suggestion(expr.span, "try", template);
});
},
);
} else {
span_lint_and_then(
cx,
@ -471,24 +468,18 @@ fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
ranges
.iter()
.filter_map(|range| match range.node {
(ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => {
Some(SpannedRange {
(ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => Some(SpannedRange {
span: range.span,
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,
node: (start, Bound::Excluded(end)),
})
},
(ConstVal::Integral(start), Bound::Unbounded) => {
Some(SpannedRange {
}),
(ConstVal::Integral(start), Bound::Unbounded) => Some(SpannedRange {
span: range.span,
node: (start, Bound::Unbounded),
})
},
}),
_ => None,
})
.collect()
@ -540,8 +531,7 @@ where
impl<'a, T: Copy> Kind<'a, T> {
fn range(&self) -> &'a SpannedRange<T> {
match *self {
Kind::Start(_, r) |
Kind::End(_, r) => r,
Kind::Start(_, r) | Kind::End(_, r) => r,
}
}
@ -562,22 +552,16 @@ where
impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
fn cmp(&self, other: &Self) -> Ordering {
match (self.value(), other.value()) {
(Bound::Included(a), Bound::Included(b)) |
(Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
(Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
// Range patterns cannot be unbounded (yet)
(Bound::Unbounded, _) |
(_, Bound::Unbounded) => unimplemented!(),
(Bound::Included(a), Bound::Excluded(b)) => {
match a.cmp(&b) {
(Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
(Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
Ordering::Equal => Ordering::Greater,
other => other,
}
},
(Bound::Excluded(a), Bound::Included(b)) => {
match a.cmp(&b) {
(Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
Ordering::Equal => Ordering::Less,
other => other,
}
},
}
}
@ -594,10 +578,8 @@ where
for (a, b) in values.iter().zip(values.iter().skip(1)) {
match (a, b) {
(&Kind::Start(_, ra), &Kind::End(_, rb)) => {
if ra.node != rb.node {
(&Kind::Start(_, ra), &Kind::End(_, rb)) => if ra.node != rb.node {
return Some((ra, rb));
}
},
(&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
_ => 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() {
Some(def) => def.has_dtor(cx.tcx),
_ => false,
}
{
} {
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::fmt;
use syntax::codemap::Span;
use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, match_qpath, match_trait_method,
match_type, method_chain_args, return_ty, same_tys, snippet, span_lint, span_lint_and_then,
span_lint_and_sugg, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, last_path_segment,
single_segment_path, match_def_path, is_self, is_self_ty, iter_input_pats, match_path};
use utils::{get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_self, is_self_ty,
iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
match_type, method_chain_args, return_ty, same_tys, single_segment_path, snippet, span_lint,
span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth};
use utils::paths;
use utils::sugg;
@ -618,12 +618,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
}
match self_ty.sty {
ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => {
for &(method, pos) in &PATTERN_METHODS {
ty::TyRef(_, ty) if ty.ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
if method_call.name == method && args.len() > 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) {
let arg_ty = cx.tables.expr_ty(arg);
let default_trait_id =
if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
default_trait_id
} else {
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)
let know_types: &[(&[_], _, &[_], _)] =
&[
let know_types: &[(&[_], _, &[_], _)] = &[
(&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
(&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
(&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 {
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::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => {
if may_slice(cx, inner) {
ty::TyRef(_, ty::TypeAndMut { ty: inner, .. }) => if may_slice(cx, inner) {
sugg::Sugg::hir_opt(cx, expr)
} else {
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| {
generics.ty_params.iter().any(|param| {
param.name == seg.name &&
param.bounds.iter().any(|bound| {
if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
param
.bounds
.iter()
.any(|bound| if let hir::TyParamBound::TraitTyParamBound(ref ptr, ..) = *bound {
let path = &ptr.trait_ref.path;
match_path(path, name) &&
path.segments.last().map_or(
false,
|s| if s.parameters.parenthesized {
path.segments
.last()
.map_or(false, |s| if s.parameters.parenthesized {
false
} else {
s.parameters.types.len() == 1 &&
(is_self_ty(&s.parameters.types[0]) || is_ty(&*s.parameters.types[0], self_ty))
},
)
})
} else {
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 {
match (&ty.node, &self_ty.node) {
(&hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
&hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path))) => {
ty_path.segments.iter().map(|seg| seg.name).eq(
self_ty_path.segments.iter().map(|seg| seg.name),
)
},
(
&hir::TyPath(hir::QPath::Resolved(_, ref ty_path)),
&hir::TyPath(hir::QPath::Resolved(_, ref self_ty_path)),
) => ty_path
.segments
.iter()
.map(|seg| seg.name)
.eq(self_ty_path.segments.iter().map(|seg| seg.name)),
_ => false,
}
}

View File

@ -1,7 +1,7 @@
use consts::{Constant, constant_simple};
use consts::{constant_simple, Constant};
use rustc::lint::*;
use rustc::hir::*;
use std::cmp::{PartialOrd, Ordering};
use std::cmp::{Ordering, PartialOrd};
use utils::{match_def_path, paths, span_lint};
/// **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;
}
match (outer_max, outer_c.partial_cmp(&inner_c)) {
(_, None) |
(MinMax::Max, Some(Ordering::Less)) |
(MinMax::Min, Some(Ordering::Greater)) => (),
(_, None) | (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");
},

View File

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

View File

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

View File

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

View File

@ -70,7 +70,14 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
expr.span,
"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(
self.cx,
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) {
if let hir::TyRptr(_,
if let hir::TyRptr(
_,
hir::MutTy {
ty: ref pty,
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(
self.cx,
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",
);
}
}
intravisit::walk_ty(self, ty);

View File

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

View File

@ -2,7 +2,7 @@
//!
//! 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::hir::Expr;
use syntax::ast;

View File

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

View File

@ -3,10 +3,10 @@
//! This lint is **warn** by default
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::adjustment::{Adjustment, Adjust};
use utils::{span_lint, in_macro};
use rustc::ty::adjustment::{Adjust, Adjustment};
use utils::{in_macro, span_lint};
/// **What it does:** Checks for address of operations (`&`) that are going to
/// 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 ty::TyRef(..) = cx.tables.expr_ty(inner).sty {
for adj3 in cx.tables.expr_adjustments(e).windows(3) {
if let [
Adjustment { kind: Adjust::Deref(_), .. },
Adjustment { kind: Adjust::Deref(_), .. },
Adjustment { kind: Adjust::Borrow(_), .. }
] = *adj3 {
span_lint(cx,
if let [Adjustment {
kind: Adjust::Deref(_),
..
}, Adjustment {
kind: Adjust::Deref(_),
..
}, Adjustment {
kind: Adjust::Borrow(_),
..
}] = *adj3
{
span_lint(
cx,
NEEDLESS_BORROW,
e.span,
"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
use rustc::lint::*;
use rustc::hir::{MutImmutable, Pat, PatKind, BindingAnnotation};
use utils::{span_lint_and_then, in_macro, snippet};
use rustc::hir::{BindingAnnotation, MutImmutable, Pat, PatKind};
use utils::{in_macro, snippet, span_lint_and_then};
/// **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 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
/// 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 {
block.stmts.get(0).map_or(false, |stmt| match stmt.node {
ast::StmtKind::Semi(ref e) |
ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::Continue(_) = e.node {
ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => if let ast::ExprKind::Continue(_) = e.node {
true
} else {
false
}
},
_ => false,
})
@ -222,8 +219,7 @@ where
F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
{
match stmt.node {
ast::StmtKind::Semi(ref e) |
ast::StmtKind::Expr(ref e) => {
ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
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) {
// snip is the whole *help* message that appears after the warning.
// message is the warning message.
// expr is the expression which the lint warning message refers to.
let (snip, message, expr) = match typ {
LintType::ContinueInsideElseBlock => {
(
LintType::ContinueInsideElseBlock => (
suggestion_snippet_for_continue_inside_else(ctx, data, header),
MSG_REDUNDANT_ELSE_BLOCK,
data.else_expr,
)
},
LintType::ContinueInsideThenBlock => {
(
),
LintType::ContinueInsideThenBlock => (
suggestion_snippet_for_continue_inside_if(ctx, data, header),
MSG_ELSE_BLOCK_NOT_NEEDED,
data.if_expr,
)
},
),
};
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_pos::Span;
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,
multispan_sugg, paths};
use std::collections::{HashSet, HashMap};
use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
snippet, span_lint_and_then};
use std::collections::{HashMap, HashSet};
/// **What it does:** Checks for functions taking arguments by value, but not
/// consuming them in its
@ -62,8 +62,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
}
match kind {
FnKind::ItemFn(.., attrs) => {
for a in attrs {
FnKind::ItemFn(.., attrs) => for a in attrs {
if_let_chain!{[
a.meta_item_list().is_some(),
let Some(name) = a.name(),
@ -71,7 +70,6 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
], {
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);
for ((input, &ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
// Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
// This is needed due to the `Borrow<T> for T` blanket impl.
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)
.any(|tpred| {
tpred.input_types().nth(1).expect(
"Borrow trait must have an parameter",
) != ty
tpred
.input_types()
.nth(1)
.expect("Borrow trait must have an parameter") != ty
});
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 {
loop {
match cmt.cat.clone() {
mc::Categorization::Downcast(c, _) |
mc::Categorization::Interior(c, _) => {
mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {
cmt = c;
},
_ => return cmt,

View File

@ -115,9 +115,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NewWithoutDefault {
return;
}
if decl.inputs.is_empty() && name == "new" && cx.access_levels.is_reachable(id) {
let self_ty = cx.tcx.type_of(
cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)),
);
let self_ty = cx.tcx
.type_of(cx.tcx.hir.local_def_id(cx.tcx.hir.get_parent(id)));
if_let_chain!{[
same_tys(cx, self_ty, return_ty(cx, id)),
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::hir::def::Def;
use rustc::hir::{Expr, Expr_, Stmt, StmtSemi, BlockCheckMode, UnsafeSource, BiAnd, BiOr};
use utils::{in_macro, span_lint, snippet_opt, span_lint_and_sugg};
use rustc::hir::{BiAnd, BiOr, BlockCheckMode, Expr, Expr_, Stmt, StmtSemi, UnsafeSource};
use utils::{in_macro, snippet_opt, span_lint, span_lint_and_sugg};
use std::ops::Deref;
/// **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;
}
match expr.node {
Expr_::ExprLit(..) |
Expr_::ExprClosure(.., _) |
Expr_::ExprPath(..) => true,
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_::ExprLit(..) | Expr_::ExprClosure(.., _) | Expr_::ExprPath(..) => true,
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_::ExprRepeat(ref inner, _) |
Expr_::ExprCast(ref inner, _) |
Expr_::ExprType(ref inner, _) |
@ -61,29 +59,24 @@ fn has_no_effect(cx: &LateContext, expr: &Expr) -> bool {
Expr_::ExprAddrOf(_, ref inner) |
Expr_::ExprBox(ref inner) => has_no_effect(cx, inner),
Expr_::ExprStruct(_, ref fields, ref base) => {
fields.iter().all(|field| has_no_effect(cx, &field.expr)) &&
match *base {
fields.iter().all(|field| has_no_effect(cx, &field.expr)) && match *base {
Some(ref base) => has_no_effect(cx, base),
None => true,
}
},
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);
match def {
Def::Struct(..) |
Def::Variant(..) |
Def::StructCtor(..) |
Def::VariantCtor(..) => args.iter().all(|arg| has_no_effect(cx, arg)),
Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
args.iter().all(|arg| has_no_effect(cx, arg))
},
_ => false,
}
} else {
false
}
},
Expr_::ExprBlock(ref block) => {
block.stmts.is_empty() &&
if let Some(ref expr) = block.expr {
block.stmts.is_empty() && if let Some(ref expr) = block.expr {
has_no_effect(cx, expr)
} else {
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 => {
Some(vec![&**a, &**b])
},
Expr_::ExprArray(ref v) |
Expr_::ExprTup(ref v) => Some(v.iter().collect()),
Expr_::ExprArray(ref v) | Expr_::ExprTup(ref v) => Some(v.iter().collect()),
Expr_::ExprRepeat(ref inner, _) |
Expr_::ExprCast(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_::ExprAddrOf(_, ref inner) |
Expr_::ExprBox(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
Expr_::ExprStruct(_, ref fields, ref base) => {
Some(
Expr_::ExprStruct(_, ref fields, ref base) => Some(
fields
.iter()
.map(|f| &f.expr)
.chain(base)
.map(Deref::deref)
.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);
match def {
Def::Struct(..) |
Def::Variant(..) |
Def::StructCtor(..) |
Def::VariantCtor(..) => Some(args.iter().collect()),
Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
Some(args.iter().collect())
},
_ => None,
}
} else {
None
}
},
Expr_::ExprBlock(ref block) => {
if block.stmts.is_empty() {

View File

@ -3,8 +3,8 @@ use syntax::codemap::Span;
use syntax::symbol::InternedString;
use syntax::ast::*;
use syntax::attr;
use syntax::visit::{Visitor, walk_block, walk_pat, walk_expr};
use utils::{span_lint_and_then, in_macro, span_lint};
use syntax::visit::{walk_block, walk_expr, walk_pat, Visitor};
use utils::{in_macro, span_lint, span_lint_and_then};
/// **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) {
match pat.node {
PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name),
PatKind::Struct(_, ref fields, _) => {
for field in fields {
PatKind::Struct(_, ref fields, _) => for field in fields {
if !field.node.is_shorthand {
self.visit_pat(&field.node.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 {
list.iter().any(|&name| {
interned_name.starts_with(name) || interned_name.ends_with(name)
})
list.iter()
.any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
}
impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
@ -157,21 +154,21 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
} else {
let mut interned_chars = interned_name.chars();
let mut existing_chars = existing_name.interned.chars();
let first_i = interned_chars.next().expect(
"we know we have at least one char",
);
let first_e = existing_chars.next().expect(
"we know we have at least one char",
);
let first_i = interned_chars
.next()
.expect("we know we have at least one char");
let first_e = existing_chars
.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();
if eq_or_numeric((first_i, first_e)) {
let last_i = interned_chars.next_back().expect(
"we know we have at least two chars",
);
let last_e = existing_chars.next_back().expect(
"we know we have at least two chars",
);
let last_i = interned_chars
.next_back()
.expect("we know we have at least two chars");
let last_e = existing_chars
.next_back()
.expect("we know we have at least two chars");
if eq_or_numeric((last_i, last_e)) {
if interned_chars
.zip(existing_chars)
@ -181,12 +178,12 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
continue;
}
} else {
let second_last_i = interned_chars.next_back().expect(
"we know we have at least three chars",
);
let second_last_e = existing_chars.next_back().expect(
"we know we have at least three chars",
);
let second_last_i = interned_chars
.next_back()
.expect("we know we have at least three chars");
let second_last_e = existing_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 == '_' ||
!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);
}
} else {
let second_i = interned_chars.next().expect(
"we know we have at least two chars",
);
let second_e = existing_chars.next().expect(
"we know we have at least two chars",
);
let second_i = interned_chars
.next()
.expect("we know we have at least two chars");
let second_e = existing_chars
.next()
.expect("we know we have at least two chars");
if !eq_or_numeric((second_i, second_e)) || second_i == '_' ||
!interned_chars.zip(existing_chars).all(eq_or_numeric)
{

View File

@ -1,6 +1,6 @@
use rustc::lint::*;
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.
///

View File

@ -1,4 +1,4 @@
use rustc::hir::{Expr, ExprMethodCall, ExprLit};
use rustc::hir::{Expr, ExprLit, ExprMethodCall};
use rustc::lint::*;
use syntax::ast::LitKind;
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
if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 2 {
let argument_option = match arguments[1].node {
ExprLit(ref span) => {
if let Spanned { node: LitKind::Bool(lit), .. } = **span {
if lit { Argument::True } else { Argument::False }
if let Spanned {
node: LitKind::Bool(lit),
..
} = **span
{
if lit {
Argument::True
} else {
Argument::False
}
} else {
return; // The function is called with a literal
// which is not a boolean literal. This is theoretically

View File

@ -1,7 +1,7 @@
use rustc::hir::*;
use rustc::lint::*;
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!`.
///

View File

@ -1,7 +1,7 @@
use rustc::lint::*;
use syntax::ast::*;
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
/// 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 ExprKind::Lit(ref lit) = slf.node {
match lit.node {
LitKind::Int(..) |
LitKind::Float(..) |
LitKind::FloatUnsuffixed(..) => {
LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
span_lint_and_sugg(
cx,
PRECEDENCE,

View File

@ -1,8 +1,8 @@
use rustc::hir::*;
use rustc::hir::map::Node::{NodeItem, NodeImplItem};
use rustc::hir::map::Node::{NodeImplItem, NodeItem};
use rustc::lint::*;
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;
/// **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();
for (arg, ty) in decl.inputs.iter().zip(fn_ty.inputs()) {
if let ty::TyRef(_,
if let ty::TyRef(
_,
ty::TypeAndMut {
ty,
mutbl: MutImmutable,
}) = ty.sty
},
) = ty.sty
{
if match_type(cx, ty, &paths::VEC) {
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 Some((out, MutMutable, _)) = get_rptr_lm(ty) {
let mut immutables = vec![];
for (_, ref mutbl, ref argspan) in
decl.inputs.iter().filter_map(|ty| get_rptr_lm(ty)).filter(
|&(lt, _, _)| lt.name == out.name,
)
for (_, ref mutbl, ref argspan) in decl.inputs
.iter()
.filter_map(|ty| get_rptr_lm(ty))
.filter(|&(lt, _, _)| lt.name == out.name)
{
if *mutbl == MutMutable {
return;

View File

@ -1,7 +1,7 @@
use rustc::lint::*;
use rustc::hir::*;
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,
/// which never terminates.
@ -54,7 +54,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StepByZero {
// Range with step_by(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;
if let Some((Constant::Int(Usize(us)), _)) = constant(cx, &args[1]) {
if us.as_u64(cx.sess().target.uint_type) == 0 {

View File

@ -1,6 +1,6 @@
use syntax::ast::{Expr, ExprKind, UnOp};
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.
///

View File

@ -7,9 +7,9 @@ use rustc::ty::subst::Substs;
use std::collections::HashSet;
use std::error::Error;
use syntax::ast::{LitKind, NodeId};
use syntax::codemap::{Span, BytePos};
use syntax::codemap::{BytePos, Span};
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
/// (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 {
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::Concat(ref exprs) => {
match exprs.len() {
2 => {
match (&exprs[0], &exprs[1]) {
Expr::Concat(ref exprs) => match exprs.len() {
2 => match (&exprs[0], &exprs[1]) {
(&Expr::StartText, &Expr::EndText) => Some("consider using `str::is_empty`"),
(&Expr::StartText, &Expr::Literal { .. }) => Some("consider using `str::starts_with`"),
(&Expr::Literal { .. }, &Expr::EndText) => Some("consider using `str::ends_with`"),
_ => None,
}
},
3 => {
if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) =
(&exprs[0], &exprs[1], &exprs[2])
{
3 => if let (&Expr::StartText, &Expr::Literal { .. }, &Expr::EndText) = (&exprs[0], &exprs[1], &exprs[2]) {
Some("consider using `==` on `str`s")
} else {
None
}
},
_ => None,
}
},
_ => None,
}
@ -205,8 +197,7 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
if let LitKind::Str(ref r, _) = lit.node {
let r = &r.as_str();
match builder.parse(r) {
Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) {
Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
span_help_and_lint(
cx,
TRIVIAL_REGEX,
@ -214,7 +205,6 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
"trivial regex",
&format!("consider using {}", repl),
);
}
},
Err(e) => {
span_lint(
@ -228,8 +218,7 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
}
} else if let Some(r) = const_str(cx, expr) {
match builder.parse(&r) {
Ok(r) => {
if let Some(repl) = is_trivial_regex(&r) {
Ok(r) => if let Some(repl) = is_trivial_regex(&r) {
span_help_and_lint(
cx,
TRIVIAL_REGEX,
@ -237,7 +226,6 @@ fn check_regex(cx: &LateContext, expr: &Expr, utf8: bool) {
"trivial regex",
&format!("consider using {}", repl),
);
}
},
Err(e) => {
span_lint(

View File

@ -3,7 +3,7 @@ use syntax::ast;
use syntax::codemap::{Span, Spanned};
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.
///
@ -50,8 +50,7 @@ impl ReturnPass {
fn check_block_return(&mut self, cx: &EarlyContext, block: &ast::Block) {
if let Some(stmt) = block.stmts.last() {
match stmt.node {
ast::StmtKind::Expr(ref expr) |
ast::StmtKind::Semi(ref expr) => {
ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
self.check_final_expr(cx, expr, Some(stmt.span));
},
_ => (),
@ -81,10 +80,8 @@ impl ReturnPass {
self.check_final_expr(cx, elsexpr, None);
},
// a match expr, check all arms
ast::ExprKind::Match(_, ref arms) => {
for arm in arms {
ast::ExprKind::Match(_, ref arms) => for arm in arms {
self.check_final_expr(cx, &arm.body, Some(arm.body.span));
}
},
_ => (),
}
@ -140,8 +137,7 @@ impl LintPass for ReturnPass {
impl EarlyLintPass for ReturnPass {
fn check_fn(&mut self, cx: &EarlyContext, kind: FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
match kind {
FnKind::ItemFn(.., block) |
FnKind::Method(.., block) => self.check_block_return(cx, block),
FnKind::ItemFn(.., block) | FnKind::Method(.., block) => self.check_block_return(cx, block),
FnKind::Closure(body) => self.check_final_expr(cx, body, Some(body.span)),
}
}

View File

@ -1,6 +1,6 @@
use rustc::lint::*;
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.
///

View File

@ -4,7 +4,7 @@ use rustc::hir::*;
use rustc::hir::intravisit::FnKind;
use rustc::ty;
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
/// 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 {
match stmt.node {
StmtDecl(ref decl, _) => check_decl(cx, decl, bindings),
StmtExpr(ref e, _) |
StmtSemi(ref e, _) => check_expr(cx, e, bindings),
StmtExpr(ref e, _) | StmtSemi(ref e, _) => check_expr(cx, e, bindings),
}
}
if let Some(ref o) = block.expr {
@ -185,14 +184,14 @@ fn check_pat<'a, 'tcx>(
check_pat(cx, p, init, span, bindings);
}
},
PatKind::Struct(_, ref pfields, _) => {
if let Some(init_struct) = init {
PatKind::Struct(_, ref pfields, _) => if let Some(init_struct) = init {
if let ExprStruct(_, ref efields, _) = init_struct.node {
for field in pfields {
let name = field.node.name;
let efield = efields.iter().find(|f| f.name.node == name).map(
|f| &*f.expr,
);
let efield = efields
.iter()
.find(|f| f.name.node == name)
.map(|f| &*f.expr);
check_pat(cx, &field.node.pat, efield, span, bindings);
}
} else {
@ -204,10 +203,8 @@ fn check_pat<'a, 'tcx>(
for field in pfields {
check_pat(cx, &field.node.pat, None, span, bindings);
}
}
},
PatKind::Tuple(ref inner, _) => {
if let Some(init_tup) = init {
PatKind::Tuple(ref inner, _) => if let Some(init_tup) = init {
if let ExprTup(ref tup) = init_tup.node {
for (i, p) in inner.iter().enumerate() {
check_pat(cx, p, Some(&tup[i]), p.span, bindings);
@ -221,10 +218,8 @@ fn check_pat<'a, 'tcx>(
for p in inner {
check_pat(cx, p, None, span, bindings);
}
}
},
PatKind::Box(ref inner) => {
if let Some(initp) = init {
PatKind::Box(ref inner) => if let Some(initp) = init {
if let ExprBox(ref inner_init) = initp.node {
check_pat(cx, inner, Some(&**inner_init), span, bindings);
} else {
@ -232,7 +227,6 @@ fn check_pat<'a, 'tcx>(
}
} else {
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>>),
@ -292,13 +286,14 @@ fn lint_shadow<'a, 'tcx: 'a>(
},
);
}
} else {
span_lint_and_then(cx,
span_lint_and_then(
cx,
SHADOW_UNRELATED,
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;
}
match expr.node {
ExprUnary(_, ref e) |
ExprField(ref e, _) |
ExprTupField(ref e, _) |
ExprAddrOf(_, ref e) |
ExprBox(ref e) => check_expr(cx, e, bindings),
ExprBlock(ref block) |
ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
ExprUnary(_, ref e) | ExprField(ref e, _) | ExprTupField(ref e, _) | ExprAddrOf(_, ref e) | ExprBox(ref e) => {
check_expr(cx, e, bindings)
},
ExprBlock(ref block) | ExprLoop(ref block, _, _) => check_block(cx, block, bindings),
// ExprCall
// ExprMethodCall
ExprArray(ref v) | ExprTup(ref v) => {
for e in v {
ExprArray(ref v) | ExprTup(ref v) => for e in v {
check_expr(cx, e, bindings)
}
},
ExprIf(ref cond, ref then, ref otherwise) => {
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_expr(cx, &cx.tcx.hir.body(body_id).value, bindings);
},
TyPtr(MutTy { ty: ref mty, .. }) |
TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
TyTup(ref tup) => {
for t in tup {
TyPtr(MutTy { ty: ref mty, .. }) | TyRptr(_, MutTy { ty: ref mty, .. }) => check_ty(cx, mty, bindings),
TyTup(ref tup) => for t in tup {
check_ty(cx, t, 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 {
match expr.node {
ExprBox(ref inner) |
ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
ExprBox(ref inner) | ExprAddrOf(_, ref inner) => is_self_shadow(name, inner),
ExprBlock(ref block) => {
block.stmts.is_empty() &&
block.expr.as_ref().map_or(
false,
|e| is_self_shadow(name, e),
)
block
.expr
.as_ref()
.map_or(false, |e| is_self_shadow(name, e))
},
ExprUnary(op, ref inner) => (UnDeref == op) && is_self_shadow(name, inner),
ExprPath(QPath::Resolved(_, ref path)) => path_eq_name(name, path),

View File

@ -1,6 +1,6 @@
use rustc::lint::*;
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
/// can be better written

View File

@ -2,7 +2,7 @@ use rustc::hir::*;
use rustc::lint::*;
use syntax::codemap::Spanned;
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
/// `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),
ExprBlock(ref block) => {
block.stmts.is_empty() &&
block.expr.as_ref().map_or(
false,
|expr| is_add(cx, expr, target),
)
block
.expr
.as_ref()
.map_or(false, |expr| is_add(cx, expr, target))
},
_ => 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) {
use std::ascii::AsciiExt;
use syntax::ast::LitKind;
use utils::{snippet, in_macro};
use utils::{in_macro, snippet};
if let ExprMethodCall(ref path, _, ref args) = e.node {
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) {
if let ExprAssign(ref target, _) = expr.node {
match target.node {
ExprField(ref base, _) |
ExprTupField(ref base, _) => {
if is_temporary(base) && !is_adjusted(cx, base) {
ExprField(ref base, _) | ExprTupField(ref base, _) => if is_temporary(base) && !is_adjusted(cx, base) {
span_lint(cx, TEMPORARY_ASSIGNMENT, expr.span, "assignment to temporary");
}
},
_ => (),
}

View File

@ -1,7 +1,7 @@
use rustc::lint::*;
use rustc::ty::{self, Ty};
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;
/// **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);
match (&from_ty.sty, &to_ty.sty) {
_ if from_ty == to_ty => {
span_lint(
_ if from_ty == to_ty => span_lint(
cx,
USELESS_TRANSMUTE,
e.span,
&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,
USELESS_TRANSMUTE,
e.span,
@ -118,11 +115,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
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,
USELESS_TRANSMUTE,
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.span_suggestion(e.span, "try", arg.as_ty(&to_ty.to_string()).to_string());
},
)
},
),
(&ty::TyFloat(_), &ty::TyRef(..)) |
(&ty::TyFloat(_), &ty::TyRawPtr(_)) |
(&ty::TyChar, &ty::TyRef(..)) |
(&ty::TyChar, &ty::TyRawPtr(_)) => {
span_lint(
(&ty::TyChar, &ty::TyRawPtr(_)) => span_lint(
cx,
WRONG_TRANSMUTE,
e.span,
&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,
CROSSPOINTER_TRANSMUTE,
e.span,
@ -153,18 +143,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
from_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,
CROSSPOINTER_TRANSMUTE,
e.span,
&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,
TRANSMUTE_PTR_TO_REF,
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());
},
)
},
),
_ => return,
};
}

View File

@ -1,16 +1,16 @@
use reexport::*;
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::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::Substs;
use std::cmp::Ordering;
use syntax::ast::{IntTy, UintTy, FloatTy};
use syntax::ast::{FloatTy, IntTy, UintTy};
use syntax::attr::IntType;
use syntax::codemap::Span;
use utils::{comparisons, higher, in_external_macro, in_macro, match_def_path, snippet, span_help_and_lint, span_lint,
span_lint_and_sugg, opt_def_id, last_path_segment, type_size, match_path};
use utils::{comparisons, higher, in_external_macro, in_macro, last_path_segment, match_def_path, match_path,
opt_def_id, snippet, span_help_and_lint, span_lint, span_lint_and_sugg, type_size};
use utils::paths;
/// 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) {
match item.node {
TraitItemKind::Const(ref ty, _) |
TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => check_ty(cx, ty, false),
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 {
QPath::Resolved(Some(ref ty), ref p) => {
check_ty(cx, ty, is_local);
for ty in p.segments.iter().flat_map(
|seg| seg.parameters.types.iter(),
)
for ty in p.segments
.iter()
.flat_map(|seg| seg.parameters.types.iter())
{
check_ty(cx, ty, is_local);
}
},
QPath::Resolved(None, ref p) => {
for ty in p.segments.iter().flat_map(
|seg| seg.parameters.types.iter(),
)
QPath::Resolved(None, ref p) => for ty in p.segments
.iter()
.flat_map(|seg| seg.parameters.types.iter())
{
check_ty(cx, ty, is_local);
}
},
QPath::TypeRelative(ref ty, ref seg) => {
check_ty(cx, ty, is_local);
@ -248,13 +245,9 @@ fn check_ty(cx: &LateContext, ast_ty: &hir::Ty, is_local: bool) {
}
},
// recurse
TySlice(ref ty) |
TyArray(ref ty, _) |
TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
TyTup(ref tys) => {
for ty in tys {
TySlice(ref ty) | TyArray(ref ty, _) | TyPtr(MutTy { ref ty, .. }) => check_ty(cx, ty, is_local),
TyTup(ref tys) => for ty in tys {
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
fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
match typ.sty {
ty::TyInt(i) => {
match i {
ty::TyInt(i) => match i {
IntTy::Is => tcx.data_layout.pointer_size.bits(),
IntTy::I8 => 8,
IntTy::I16 => 16,
IntTy::I32 => 32,
IntTy::I64 => 64,
IntTy::I128 => 128,
}
},
ty::TyUint(i) => {
match i {
ty::TyUint(i) => match i {
UintTy::Us => tcx.data_layout.pointer_size.bits(),
UintTy::U8 => 8,
UintTy::U16 => 16,
UintTy::U32 => 32,
UintTy::U64 => 64,
UintTy::U128 => 128,
}
},
_ => 0,
}
@ -555,8 +544,7 @@ fn int_ty_to_nbits(typ: Ty, tcx: TyCtxt) -> u64 {
fn is_isize_or_usize(typ: Ty) -> bool {
match typ.sty {
ty::TyInt(IntTy::Is) |
ty::TyUint(UintTy::Us) => true,
ty::TyInt(IntTy::Is) | ty::TyUint(UintTy::Us) => true,
_ => 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 (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
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,
ArchSuffix::None,
to_nbits == from_nbits && cast_unsigned_to_signed,
ArchSuffix::None,
)
},
(true, false) => {
(
),
(true, false) => (
to_nbits <= 32,
if to_nbits == 32 {
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,
ArchSuffix::_32,
)
},
(false, true) => {
(
),
(false, true) => (
from_nbits == 64,
ArchSuffix::_32,
cast_unsigned_to_signed,
@ -647,8 +630,7 @@ fn check_truncation_and_wrapping(cx: &LateContext, expr: &Expr, cast_from: Ty, c
} else {
ArchSuffix::_32
},
)
},
),
};
if span_truncation {
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 from_nbits = int_ty_to_nbits(cast_from, 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 &&
!cast_signed_to_unsigned
if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
{
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 {
let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
if let ExprLit(ref lit) = ex.node {
use syntax::ast::{LitKind, LitIntType};
use syntax::ast::{LitIntType, LitKind};
match lit.node {
LitKind::Int(_, LitIntType::Unsuffixed) |
LitKind::FloatUnsuffixed(_) => {},
_ => {
if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
_ => if cast_from.sty == cast_to.sty && !in_external_macro(cx, expr.span) {
span_lint(
cx,
UNNECESSARY_CAST,
expr.span,
&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);
},
(false, false) => {
if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) =
(&cast_from.sty, &cast_to.sty)
if let (&ty::TyFloat(FloatTy::F64), &ty::TyFloat(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty)
{
span_lint(
cx,
@ -786,8 +763,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
"casting f64 to f32 may truncate the value",
);
}
if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) =
(&cast_from.sty, &cast_to.sty)
if let (&ty::TyFloat(FloatTy::F32), &ty::TyFloat(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty)
{
span_lossless_lint(cx, expr, ex, cast_from, cast_to);
}
@ -823,7 +799,9 @@ pub struct TypeComplexityPass {
impl TypeComplexityPass {
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) {
match item.node {
ItemStatic(ref ty, _, _) |
ItemConst(ref ty, _) => self.check_type(cx, ty),
ItemStatic(ref ty, _, _) | ItemConst(ref ty, _) => self.check_type(cx, ty),
// 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) {
match item.node {
TraitItemKind::Const(ref ty, _) |
TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
TraitItemKind::Method(MethodSig { ref decl, .. }, TraitMethod::Required(_)) => self.check_fndecl(cx, decl),
// 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) {
match item.node {
ImplItemKind::Const(ref ty, _) |
ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
// methods are covered by check_fn
_ => (),
}
@ -938,9 +913,9 @@ impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
TyBareFn(..) => (50 * self.nest, 1),
TyTraitObject(ref param_bounds, _) => {
let has_lifetime_parameters = param_bounds.iter().any(
|bound| !bound.bound_lifetimes.is_empty(),
);
let has_lifetime_parameters = param_bounds
.iter()
.any(|bound| !bound.bound_lifetimes.is_empty());
if has_lifetime_parameters {
// complex trait bounds like A<'a, 'b>
(50 * self.nest, 1)
@ -1187,14 +1162,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
let conclusion = match result {
AlwaysFalse => "this comparison is always false".to_owned(),
AlwaysTrue => "this comparison is always true".to_owned(),
InequalityImpossible => {
format!(
InequalityImpossible => format!(
"the case where the two sides are not equal never occurs, consider using {} == {} \
instead",
snippet(cx, lhs.span, "lhs"),
snippet(cx, rhs.span, "rhs")
)
},
),
};
let help = format!(
@ -1264,9 +1237,8 @@ impl FullInt {
impl PartialEq for FullInt {
fn eq(&self, other: &Self) -> bool {
self.partial_cmp(other).expect(
"partial_cmp only returns Some(_)",
) == Ordering::Equal
self.partial_cmp(other)
.expect("partial_cmp only returns Some(_)") == Ordering::Equal
}
}
@ -1282,9 +1254,8 @@ impl PartialOrd for FullInt {
}
impl Ord for FullInt {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).expect(
"partial_cmp for FullInt can never return None",
)
self.partial_cmp(other)
.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;
}
match pre_cast_ty.sty {
ty::TyInt(int_ty) => {
Some(match int_ty {
ty::TyInt(int_ty) => Some(match int_ty {
IntTy::I8 => (FullInt::S(i128::from(i8::min_value())), FullInt::S(i128::from(i8::max_value()))),
IntTy::I16 => (
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::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::U16 => (
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::Us => (FullInt::U(usize::min_value() as u128), FullInt::U(usize::max_value() as u128)),
})
},
}),
_ => None,
}
} 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 substs = Substs::identity_for_item(cx.tcx, parent_def_id);
match ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables).eval(expr) {
Ok(val) => {
if let Integral(const_int) = val {
Ok(val) => if let Integral(const_int) = val {
match const_int.int_type() {
IntType::SignedInt(_) => Some(FullInt::S(const_int.to_u128_unchecked() as i128)),
IntType::UnsignedInt(_) => Some(FullInt::U(const_int.to_u128_unchecked())),
}
} else {
None
}
},
Err(_) => None,
}
@ -1402,42 +1367,32 @@ fn upcast_comparison_bounds_err(
err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
}
} else if match rel {
Rel::Lt => {
if invert {
Rel::Lt => if invert {
norm_rhs_val < lb
} else {
ub < norm_rhs_val
}
},
Rel::Le => {
if invert {
Rel::Le => if invert {
norm_rhs_val <= lb
} else {
ub <= norm_rhs_val
}
},
Rel::Eq | Rel::Ne => unreachable!(),
}
{
} {
err_upcast_comparison(cx, span, lhs, true)
} else if match rel {
Rel::Lt => {
if invert {
Rel::Lt => if invert {
norm_rhs_val >= ub
} else {
lb >= norm_rhs_val
}
},
Rel::Le => {
if invert {
Rel::Le => if invert {
norm_rhs_val > ub
} else {
lb > norm_rhs_val
}
},
Rel::Eq | Rel::Ne => unreachable!(),
}
{
} {
err_upcast_comparison(cx, span, lhs, false)
}
}
@ -1447,7 +1402,6 @@ fn upcast_comparison_bounds_err(
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
if let ExprBinary(ref cmp, ref lhs, ref rhs) = expr.node {
let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
val

View File

@ -3,7 +3,7 @@ use rustc::hir::*;
use syntax::ast::{LitKind, NodeId};
use syntax::codemap::Span;
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.
///

View File

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

View File

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

View File

@ -1,6 +1,6 @@
use rustc::lint::*;
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 syntax::ast;
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> {
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
match expr.node {
hir::ExprBreak(destination, _) |
hir::ExprAgain(destination) => {
if let Some(label) = destination.ident {
hir::ExprBreak(destination, _) | hir::ExprAgain(destination) => if let Some(label) = destination.ident {
self.labels.remove(&label.node.name.as_str());
}
},
hir::ExprLoop(_, Some(label), _) |
hir::ExprWhile(_, _, Some(label)) => {
hir::ExprLoop(_, Some(label), _) | hir::ExprWhile(_, _, Some(label)) => {
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::intravisit::{Visitor, walk_path, NestedVisitorMap};
use utils::{span_lint_and_then, in_macro};
use rustc::hir::intravisit::{walk_path, NestedVisitorMap, Visitor};
use utils::{in_macro, span_lint_and_then};
use syntax::ast::NodeId;
use syntax_pos::symbol::keywords::SelfType;

View File

@ -5,9 +5,9 @@
use rustc::lint::*;
use rustc::hir;
use rustc::hir::{Expr, QPath, Expr_};
use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
use syntax::ast::{self, Attribute, NodeId, LitKind, DUMMY_NODE_ID};
use rustc::hir::{Expr, Expr_, QPath};
use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
use syntax::ast::{self, Attribute, LitKind, NodeId, DUMMY_NODE_ID};
use syntax::codemap::Span;
use std::collections::HashMap;
@ -386,15 +386,13 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor {
println!("Again(ref {}) = {},", destination_pat, current);
// FIXME: implement label printing
},
Expr_::ExprRet(ref opt_value) => {
if let Some(ref value) = *opt_value {
Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
let value_pat = self.next("value");
println!("Ret(Some(ref {})) = {},", value_pat, current);
self.current = value_pat;
self.visit_expr(value);
} else {
println!("Ret(None) = {},", current);
}
},
Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
println!("InlineAsm(_, ref input, ref output) = {},", current);
@ -445,10 +443,8 @@ impl<'tcx> Visitor<'tcx> for PrintVisitor {
fn has_attr(attrs: &[Attribute]) -> bool {
attrs.iter().any(|attr| {
attr.check_name("clippy") &&
attr.meta_item_list().map_or(false, |list| {
list.len() == 1 &&
match list[0].node {
attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
list.len() == 1 && match list[0].node {
ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
ast::NestedMetaItemKind::Literal(_) => false,
}
@ -458,18 +454,15 @@ fn has_attr(attrs: &[Attribute]) -> bool {
fn print_path(path: &QPath, first: &mut bool) {
match *path {
QPath::Resolved(_, ref path) => {
for segment in &path.segments {
QPath::Resolved(_, ref path) => for segment in &path.segments {
if *first {
*first = false;
} else {
print!(", ");
}
print!("{:?}", segment.name.as_str());
}
},
QPath::TypeRelative(ref ty, ref segment) => {
match ty.node {
QPath::TypeRelative(ref ty, ref segment) => match ty.node {
hir::Ty_::TyPath(ref inner_path) => {
print_path(inner_path, first);
if *first {
@ -480,7 +473,6 @@ fn print_path(path: &QPath, first: &mut bool) {
print!("{:?}", segment.name.as_str());
},
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()) {
if arg.name() == "conf_file" {
return match arg.node {
ast::MetaItemKind::Word |
ast::MetaItemKind::List(_) => 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::Word | ast::MetaItemKind::List(_) => {
Err(("`conf_file` must be a named value", arg.span))
},
ast::MetaItemKind::NameValue(ref value) => if let ast::LitKind::Str(ref file, _) = value.node {
Ok(Some(file.to_string().into()))
} else {
Err(("`conf_file` value must be a string", value.span))
}
},
};
}
@ -45,7 +44,7 @@ pub enum Error {
/// The expected type.
&'static str,
/// The type we got instead.
&'static str
&'static str,
),
/// There is an unknown key is the file.
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)),
// Return the error if it's something other than `NotFound`; otherwise we didn't
// find the project file yet, and continue searching.
Err(e) => {
if e.kind() != io::ErrorKind::NotFound {
Err(e) => if e.kind() != io::ErrorKind::NotFound {
return Err(e);
}
},
_ => (),
}

View File

@ -6,7 +6,7 @@
use rustc::hir;
use rustc::lint::LateContext;
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.
pub fn binop(op: hir::BinOp_) -> ast::BinOpKind {
@ -73,8 +73,9 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
None
}
},
hir::ExprStruct(ref path, ref fields, None) => {
if match_qpath(path, &paths::RANGE_FROM_STD) || match_qpath(path, &paths::RANGE_FROM) {
hir::ExprStruct(ref path, ref fields, None) => if match_qpath(path, &paths::RANGE_FROM_STD) ||
match_qpath(path, &paths::RANGE_FROM)
{
Some(Range {
start: get_field("start", fields),
end: None,
@ -92,9 +93,7 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
end: get_field("end", fields),
limits: ast::RangeLimits::HalfOpen,
})
} else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) ||
match_qpath(path, &paths::RANGE_TO_INCLUSIVE)
{
} else if match_qpath(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_qpath(path, &paths::RANGE_TO_INCLUSIVE) {
Some(Range {
start: None,
end: get_field("end", fields),
@ -108,7 +107,6 @@ pub fn range(expr: &hir::Expr) -> Option<Range> {
})
} else {
None
}
},
_ => None,
}

View File

@ -46,8 +46,9 @@ impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
false
}
},
(&StmtExpr(ref l, _), &StmtExpr(ref r, _)) |
(&StmtSemi(ref l, _), &StmtSemi(ref r, _)) => self.eq_expr(l, r),
(&StmtExpr(ref l, _), &StmtExpr(ref r, _)) | (&StmtSemi(ref l, _), &StmtSemi(ref r, _)) => {
self.eq_expr(l, r)
},
_ => 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())
},
(&ExprMatch(ref le, ref la, ref ls), &ExprMatch(ref re, ref ra, ref rs)) => {
ls == rs && self.eq_expr(le, re) &&
over(la, ra, |l, r| {
ls == rs && self.eq_expr(le, re) && over(la, ra, |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))
})
@ -257,9 +257,8 @@ fn both<X, F>(l: &Option<X>, r: &Option<X>, mut eq_fn: F) -> bool
where
F: FnMut(&X, &X) -> bool,
{
l.as_ref().map_or_else(|| r.is_none(), |x| {
r.as_ref().map_or(false, |y| eq_fn(x, y))
})
l.as_ref()
.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`.

View File

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

View File

@ -1,11 +1,11 @@
use rustc::lint::*;
use rustc::hir::*;
use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
use utils::{paths, match_qpath, span_lint};
use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use utils::{match_qpath, paths, span_lint};
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 std::collections::{HashSet, HashMap};
use std::collections::{HashMap, HashSet};
/// **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 {
fn check_crate(&mut self, cx: &EarlyContext, krate: &AstCrate) {
if let Some(utils) = krate.module.items.iter().find(
|item| item.ident.name == "utils",
)
if let Some(utils) = krate
.module
.items
.iter()
.find(|item| item.ident.name == "utils")
{
if let ItemKind::Mod(ref utils_mod) = utils.node {
if let Some(paths) = utils_mod.items.iter().find(
|item| item.ident.name == "paths",
)
if let Some(paths) = utils_mod
.items
.iter()
.find(|item| item.ident.name == "paths")
{
if let ItemKind::Mod(ref paths_mod) = paths.node {
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 {
if let TyRptr(ref lt,
if let TyRptr(
ref lt,
MutTy {
ty: ref inner,
mutbl: MutImmutable,
}) = ty.node
},
) = ty.node
{
if lt.is_elided() {
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::intravisit::{NestedVisitorMap, Visitor};
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::traits;
use rustc::ty::{self, TyCtxt, Ty};
use rustc::ty::{self, Ty, TyCtxt};
use rustc::mir::transform::MirSource;
use rustc_errors;
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 {
let parent_id = cx.tcx.hir.get_parent(id);
match MirSource::from_node(cx.tcx, parent_id) {
MirSource::GeneratorDrop(_) |
MirSource::Fn(_) => false,
MirSource::Const(_) |
MirSource::Static(..) |
MirSource::Promoted(..) => true,
MirSource::GeneratorDrop(_) | MirSource::Fn(_) => false,
MirSource::Const(_) | MirSource::Static(..) | MirSource::Promoted(..) => true,
}
}
/// Returns true if this `expn_info` was expanded by any macro.
pub fn in_macro(span: Span) -> bool {
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,
_ => 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
info.callee.span.map_or(true, |span| {
// no snippet = external macro or compiler-builtin expansion
cx.sess().codemap().span_to_snippet(span).ok().map_or(
true,
|code| {
!code.starts_with("macro_rules")
},
)
cx.sess()
.codemap()
.span_to_snippet(span)
.ok()
.map_or(true, |code| !code.starts_with("macro_rules"))
})
}
span.ctxt().outer().expn_info().map_or(false, |info| {
in_macro_ext(cx, &info)
})
span.ctxt()
.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.
@ -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);
apb.names.len() == path.len() &&
apb.names.into_iter().zip(path.iter()).all(
|(a, &b)| *a == *b,
)
apb.names
.into_iter()
.zip(path.iter())
.all(|(a, &b)| *a == *b)
}
/// 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 {
match *path {
QPath::Resolved(_, ref path) => {
path.segments.last().expect(
"A path must have at least one segment",
)
},
QPath::Resolved(_, ref path) => path.segments
.last()
.expect("A path must have at least one segment"),
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 {
match *path {
QPath::Resolved(_, ref path) => match_path(path, segments),
QPath::TypeRelative(ref ty, ref segment) => {
match ty.node {
QPath::TypeRelative(ref ty, ref segment) => match ty.node {
TyPath(ref inner_path) => {
!segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)]) &&
segment.name == segments[segments.len() - 1]
},
_ => false,
}
},
}
}
pub fn match_path(path: &Path, segments: &[&str]) -> bool {
path.segments.iter().rev().zip(segments.iter().rev()).all(
|(a, b)| a.name == *b,
)
path.segments
.iter()
.rev()
.zip(segments.iter().rev())
.all(|(a, b)| a.name == *b)
}
/// 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"])
/// ```
pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
path.segments.iter().rev().zip(segments.iter().rev()).all(
|(a, b)| a.identifier.name == *b,
)
path.segments
.iter()
.rev()
.zip(segments.iter().rev())
.all(|(a, b)| a.identifier.name == *b)
}
/// 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 crates = cstore.crates();
let krate = crates.iter().find(
|&&krate| cstore.crate_name(krate) == path[0],
);
let krate = crates
.iter()
.find(|&&krate| cstore.crate_name(krate) == path[0]);
if let Some(krate) = krate {
let krate = DefId {
krate: *krate,
@ -336,14 +335,9 @@ pub fn implements_trait<'a, 'tcx>(
ty_params: &[Ty<'tcx>],
) -> bool {
let ty = cx.tcx.erase_regions(&ty);
let obligation = cx.tcx.predicate_for_trait_def(
cx.param_env,
traits::ObligationCause::dummy(),
trait_id,
0,
ty,
ty_params,
);
let obligation =
cx.tcx
.predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
cx.tcx.infer_ctxt().enter(|infcx| {
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 {
return None;
}
map.find(parent_id).and_then(
|node| if let Node::NodeExpr(parent) =
node
{
map.find(parent_id)
.and_then(|node| if let Node::NodeExpr(parent) = node {
Some(parent)
} else {
None
},
)
})
}
pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
let map = &cx.tcx.hir;
let enclosing_node = map.get_enclosing_scope(node).and_then(|enclosing_id| {
map.find(enclosing_id)
});
let enclosing_node = map.get_enclosing_scope(node)
.and_then(|enclosing_id| map.find(enclosing_id));
if let Some(node) = enclosing_node {
match node {
Node::NodeBlock(block) => Some(block),
Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => {
match cx.tcx.hir.body(eid).value.node {
Node::NodeItem(&Item {
node: ItemFn(_, _, _, _, _, eid),
..
}) => match cx.tcx.hir.body(eid).value.node {
ExprBlock(ref block) => Some(block),
_ => None,
}
},
_ => None,
}
@ -704,9 +695,9 @@ impl LimitStack {
Self { stack: vec![limit] }
}
pub fn limit(&self) -> u64 {
*self.stack.last().expect(
"there should always be a value in the stack",
)
*self.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) {
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`.
pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
loop {
let span_name_span = span.ctxt().outer().expn_info().map(|ei| {
(ei.callee.name(), ei.call_site)
});
let span_name_span = span.ctxt()
.outer()
.expn_info()
.map(|ei| (ei.callee.name(), ei.call_site));
match span_name_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
/// `is_direct_expn_of`.
pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
let span_name_span = span.ctxt().outer().expn_info().map(|ei| {
(ei.callee.name(), ei.call_site)
});
let span_name_span = span.ctxt()
.outer()
.expn_info()
.map(|ei| (ei.callee.name(), ei.call_site));
match span_name_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;
}
}
if up { last_i } else { s.len() }
if up {
last_i
} else {
s.len()
}
}
/// 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
// not for type parameters.
pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
cx.tcx.infer_ctxt().enter(|infcx| {
infcx.can_eq(cx.param_env, a, b).is_ok()
})
cx.tcx
.infer_ctxt()
.enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
}
/// 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 {
PatKind::Binding(..) |
PatKind::Wild => false,
PatKind::Box(ref pat) |
PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
PatKind::Lit(..) |
PatKind::Range(..) => true,
PatKind::Binding(..) | PatKind::Wild => false,
PatKind::Box(ref pat) | 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::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
PatKind::Struct(ref qpath, ref fields, _) => {
if is_enum_variant(cx, qpath, pat.hir_id) {
PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
true
} else {
are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
}
},
PatKind::TupleStruct(ref qpath, ref pats, _) => {
if is_enum_variant(cx, qpath, pat.hir_id) {
PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
true
} else {
are_refutable(cx, pats.iter().map(|pat| &**pat))
}
},
PatKind::Slice(ref head, ref middle, ref tail) => {
are_refutable(
PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
cx,
head.iter().chain(middle).chain(tail.iter()).map(
|pat| &**pat,
head.iter()
.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> {
ty.layout(cx.tcx, cx.param_env).ok().map(|layout| {
layout.size(cx.tcx).bytes()
})
ty.layout(cx.tcx, cx.param_env)
.ok()
.map(|layout| layout.size(cx.tcx).bytes())
}
/// 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> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match *self {
Sugg::NonParen(ref s) |
Sugg::MaybeParen(ref s) |
Sugg::BinOp(_, ref s) => s.fmt(f),
Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
}
}
}
@ -178,12 +176,10 @@ impl<'a> Sugg<'a> {
match self {
Sugg::NonParen(..) => self,
// (x) and (x).y() both don't need additional parens
Sugg::MaybeParen(sugg) => {
if sugg.starts_with('(') && sugg.ends_with(')') {
Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
Sugg::MaybeParen(sugg)
} else {
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 rhs = ParenHelper::new(rhs_paren, rhs);
let sugg = match op {
AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | 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::Add |
AssocOp::BitAnd |
AssocOp::BitOr |
AssocOp::BitXor |
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::Assign => format!("{} = {}", lhs, rhs),
AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
@ -343,7 +351,16 @@ fn associativity(op: &AssocOp) -> Associativity {
match *op {
Inplace | Assign | AssignOp(_) => Associativity::Right,
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,
DotDot | DotDotDot => Associativity::None,
}
@ -393,9 +410,8 @@ fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
/// before it on its line.
fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
let lo = cx.sess().codemap().lookup_char_pos(span.lo());
if let Some(line) = lo.file.get_line(
lo.line - 1, /* line numbers in `Loc` are 1-based */
)
if let Some(line) = lo.file
.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
{
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]`

View File

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

View File

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

View File

@ -1,12 +1,11 @@
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use syntax::codemap::Span;
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 rustc_plugin::Registry;

View File

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

View File

@ -29,6 +29,8 @@ fn compile_test() {
prepare_env();
run_mode("run-pass", "run-pass");
run_mode("ui", "ui");
#[cfg(target_os = "windows")] run_mode("ui-windows", "ui");
#[cfg(not(target_os = "windows"))] run_mode("ui-posix", "ui");
#[cfg(target_os = "windows")]
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 test;
use std::env::{var, set_var};
use std::env::{set_var, var};
use std::path::PathBuf;
use test::TestPaths;

View File

@ -1,14 +1,12 @@
#![feature(plugin)]
#![plugin(clippy)]
#![allow(warnings)]
// this should compile in a reasonable amount of time
fn rust_type_id(name: &str) {
if "bool" == &name[..] || "uint" == &name[..] || "u8" == &name[..] || "u16" == &name[..] ||
"u32" == &name[..] || "f32" == &name[..] || "f64" == &name[..] || "i8" == &name[..] ||
"i16" == &name[..] || "i32" == &name[..] ||
"i64" == &name[..] || "Self" == &name[..] || "str" == &name[..]
if "bool" == &name[..] || "uint" == &name[..] || "u8" == &name[..] || "u16" == &name[..] || "u32" == &name[..] ||
"f32" == &name[..] || "f64" == &name[..] || "i8" == &name[..] || "i16" == &name[..] ||
"i32" == &name[..] || "i64" == &name[..] || "Self" == &name[..] || "str" == &name[..]
{
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(
&[
overlapping(&[
sp(1, Bound::Included(4)),
sp(5, Bound::Included(6)),
sp(10, Bound::Included(11)),
],
)
sp(10, Bound::Included(11))
],)
);
assert_eq!(
Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
@ -35,12 +33,10 @@ fn test_overlapping() {
);
assert_eq!(
Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
overlapping(
&[
overlapping(&[
sp(1, Bound::Included(4)),
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
// lint that don't belong in utils.
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]
#[cfg_attr(rustfmt, rustfmt_skip)]