Used clippy to clean itself

This commit is contained in:
JarredAllen 2020-05-31 15:37:21 -07:00
parent 5e20475e47
commit 5150277a4f
19 changed files with 67 additions and 154 deletions

View File

@ -481,15 +481,11 @@ fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
}
fn is_relevant_block(cx: &LateContext<'_>, tables: &ty::TypeckTables<'_>, block: &Block<'_>) -> bool {
if let Some(stmt) = block.stmts.first() {
match &stmt.kind {
block.stmts.first().map_or(block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e)), |stmt| match &stmt.kind {
StmtKind::Local(_) => true,
StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr),
_ => false,
}
} else {
block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e))
}
})
}
fn is_relevant_expr(cx: &LateContext<'_>, tables: &ty::TypeckTables<'_>, expr: &Expr<'_>) -> bool {
@ -499,11 +495,7 @@ fn is_relevant_expr(cx: &LateContext<'_>, tables: &ty::TypeckTables<'_>, expr: &
ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
ExprKind::Call(path_expr, _) => {
if let ExprKind::Path(qpath) = &path_expr.kind {
if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
!match_def_path(cx, fun_id, &paths::BEGIN_PANIC)
} else {
true
}
tables.qpath_res(qpath, path_expr.hir_id).opt_def_id().map_or(true, |fun_id| !match_def_path(cx, fun_id, &paths::BEGIN_PANIC))
} else {
true
}

View File

@ -135,13 +135,9 @@ impl<'tcx> Visitor<'tcx> for ArmVisitor<'_, 'tcx> {
}
}
impl<'tcx> ArmVisitor<'_, 'tcx> {
impl<'tcx, 'l> ArmVisitor<'tcx, 'l> {
fn same_mutex(&self, cx: &LateContext<'_>, op_mutex: &Expr<'_>) -> bool {
if let Some(arm_mutex) = self.found_mutex {
SpanlessEq::new(cx).eq_expr(op_mutex, arm_mutex)
} else {
false
}
self.found_mutex.map_or(false, |arm_mutex| SpanlessEq::new(cx).eq_expr(op_mutex, arm_mutex))
}
}

View File

@ -303,14 +303,10 @@ fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
let ty = &walk_ptrs_ty(cx.tables().expr_ty(expr));
match ty.kind {
ty::Dynamic(ref tt, ..) => {
if let Some(principal) = tt.principal() {
cx.tcx
tt.principal().map_or(false, |principal| cx.tcx
.associated_items(principal.def_id())
.in_definition_order()
.any(|item| is_is_empty(cx, &item))
} else {
false
}
.any(|item| is_is_empty(cx, &item)))
},
ty::Projection(ref proj) => has_is_empty_impl(cx, proj.item_def_id),
ty::Adt(id, _) => has_is_empty_impl(cx, id.did),

View File

@ -264,10 +264,11 @@ impl LiteralDigitGrouping {
let (part, mistyped_suffixes, missing_char) = if let Some((_, exponent)) = &mut num_lit.exponent {
(exponent, &["32", "64"][..], 'f')
} else if let Some(fraction) = &mut num_lit.fraction {
(fraction, &["32", "64"][..], 'f')
} else {
(&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i')
num_lit.fraction.as_mut().map_or(
(&mut num_lit.integer, &["8", "16", "32", "64"][..], 'i'),
|fraction| (fraction, &["32", "64"][..], 'f')
)
};
let mut split = part.rsplit('_');

View File

@ -687,11 +687,7 @@ fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
}
},
ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => {
if let Some(ref e) = *e {
combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
} else {
NeverLoopResult::AlwaysBreak
}
e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak))
},
ExprKind::InlineAsm(ref asm) => asm
.operands
@ -1882,11 +1878,7 @@ fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
// IntoIterator is currently only implemented for array sizes <= 32 in rustc
match ty.kind {
ty::Array(_, n) => {
if let Some(val) = n.try_eval_usize(cx.tcx, cx.param_env) {
(0..=32).contains(&val)
} else {
false
}
n.try_eval_usize(cx.tcx, cx.param_env).map_or(false, |val| (0..=32).contains(&val))
},
_ => false,
}
@ -1899,11 +1891,7 @@ fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<
return None;
}
if let StmtKind::Local(ref local) = block.stmts[0].kind {
if let Some(expr) = local.init {
Some(expr)
} else {
None
}
local.init.map(|expr| expr)
} else {
None
}
@ -2023,15 +2011,11 @@ impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
if let PatKind::Binding(.., ident, _) = local.pat.kind {
self.name = Some(ident.name);
self.state = if let Some(ref init) = local.init {
if is_integer_const(&self.cx, init, 0) {
self.state = local.init.as_ref().map_or(VarState::Declared, |init| if is_integer_const(&self.cx, init, 0) {
VarState::Warn
} else {
VarState::Declared
}
} else {
VarState::Declared
}
})
}
}
}

View File

@ -2461,11 +2461,7 @@ fn derefs_to_slice<'tcx>(
ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
ty::Array(_, size) => {
if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
size < 32
} else {
false
}
size.try_eval_usize(cx.tcx, cx.param_env).map_or(false, |size| size < 32)
},
ty::Ref(_, inner, _) => may_slice(cx, inner),
_ => false,

View File

@ -78,11 +78,7 @@ fn check_expression<'tcx>(cx: &LateContext<'tcx>, arg_id: hir::HirId, expr: &'tc
(true, true)
},
hir::ExprKind::Block(ref block, _) => {
if let Some(expr) = &block.expr {
check_expression(cx, arg_id, &expr)
} else {
(false, false)
}
block.expr.as_ref().map_or((false, false), |expr| check_expression(cx, arg_id, &expr))
},
hir::ExprKind::Match(_, arms, _) => {
let mut found_mapping = false;

View File

@ -86,16 +86,19 @@ fn fetch_const<'a>(cx: &LateContext<'_>, args: &'a [Expr<'a>], m: MinMax) -> Opt
if args.len() != 2 {
return None;
}
if let Some(c) = constant_simple(cx, cx.tables(), &args[0]) {
if constant_simple(cx, cx.tables(), &args[1]).is_none() {
// otherwise ignore
Some((m, c, &args[1]))
constant_simple(cx, cx.tables, &args[0]).map_or_else(
|| if let Some(c) = constant_simple(cx, cx.tables(), &args[1]) {
Some((m, c, &args[0]))
} else {
None
},
|c| {
if constant_simple(cx, cx.tables, &args[1]).is_none() {
// otherwise ignore
Some((c, &args[1]))
} else {
None
}
}
} else if let Some(c) = constant_simple(cx, cx.tables(), &args[1]) {
Some((m, c, &args[0]))
} else {
None
}
).map(|(c, arg)| (m, c, arg))
}

View File

@ -682,16 +682,12 @@ fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left:
/// `unused_variables`'s idea
/// of what it means for an expression to be "used".
fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
if let Some(parent) = get_parent_expr(cx, expr) {
match parent.kind {
get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => {
SpanlessEq::new(cx).eq_expr(rhs, expr)
},
_ => is_used(cx, parent),
}
} else {
true
}
})
}
/// Tests whether an expression is in a macro expansion (e.g., something

View File

@ -37,6 +37,7 @@ declare_clippy_lint! {
///
/// ```rust
/// # let optional: Option<u32> = Some(0);
/// # fn do_complicated_function() -> u32 { 5 };
/// let _ = if let Some(foo) = optional {
/// foo
/// } else {
@ -54,9 +55,10 @@ declare_clippy_lint! {
///
/// ```rust
/// # let optional: Option<u32> = Some(0);
/// # fn do_complicated_function() -> u32 { 5 };
/// let _ = optional.map_or(5, |foo| foo);
/// let _ = optional.map_or_else(||{
/// let y = do_complicated_function;
/// let y = do_complicated_function();
/// y*y
/// }, |foo| foo);
/// ```

View File

@ -259,15 +259,10 @@ fn is_unit_expr(expr: &ast::Expr) -> bool {
fn lint_unneeded_unit_return(cx: &EarlyContext<'_>, ty: &ast::Ty, span: Span) {
let (ret_span, appl) = if let Ok(fn_source) = cx.sess().source_map().span_to_snippet(span.with_hi(ty.span.hi())) {
if let Some(rpos) = fn_source.rfind("->") {
#[allow(clippy::cast_possible_truncation)]
(
fn_source.rfind("->").map_or((ty.span, Applicability::MaybeIncorrect), |rpos| (
ty.span.with_lo(BytePos(span.lo().0 + rpos as u32)),
Applicability::MachineApplicable,
)
} else {
(ty.span, Applicability::MaybeIncorrect)
}
))
} else {
(ty.span, Applicability::MaybeIncorrect)
};

View File

@ -164,15 +164,11 @@ fn check_local<'tcx>(cx: &LateContext<'tcx>, local: &'tcx Local<'_>, bindings: &
}
fn is_binding(cx: &LateContext<'_>, pat_id: HirId) -> bool {
let var_ty = cx.tables().node_type_opt(pat_id);
if let Some(var_ty) = var_ty {
match var_ty.kind {
let var_ty = cx.tables.node_type_opt(pat_id);
var_ty.map_or(false, |var_ty| match var_ty.kind {
ty::Adt(..) => false,
_ => true,
}
} else {
false
}
})
}
fn check_pat<'tcx>(

View File

@ -1205,16 +1205,14 @@ fn span_lossless_lint(cx: &LateContext<'_>, expr: &Expr<'_>, op: &Expr<'_>, cast
// has parens on the outside, they are no longer needed.
let mut applicability = Applicability::MachineApplicable;
let opt = snippet_opt(cx, op.span);
let sugg = if let Some(ref snip) = opt {
if should_strip_parens(op, snip) {
let sugg = opt.as_ref().map_or_else(|| {
applicability = Applicability::HasPlaceholders;
".."
}, |snip| if should_strip_parens(op, snip) {
&snip[1..snip.len() - 1]
} else {
snip.as_str()
}
} else {
applicability = Applicability::HasPlaceholders;
".."
};
});
span_lint_and_sugg(
cx,

View File

@ -167,14 +167,10 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf {
if let TyKind::Path(QPath::Resolved(_, ref item_path)) = item_type.kind;
then {
let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
let should_check = if let Some(ref params) = *parameters {
!params.parenthesized && !params.args.iter().any(|arg| match arg {
let should_check = parameters.as_ref().map_or(true, |params| !params.parenthesized && !params.args.iter().any(|arg| match arg {
GenericArg::Lifetime(_) => true,
_ => false,
})
} else {
true
};
}));
if should_check {
let visitor = &mut UseSelfVisitor {

View File

@ -65,8 +65,7 @@ pub fn get_attr<'a>(
};
let attr_segments = &attr.path.segments;
if attr_segments.len() == 2 && attr_segments[0].ident.to_string() == "clippy" {
if let Some(deprecation_status) =
BUILTIN_ATTRIBUTES
BUILTIN_ATTRIBUTES
.iter()
.find_map(|(builtin_name, deprecation_status)| {
if *builtin_name == attr_segments[1].ident.to_string() {
@ -74,8 +73,10 @@ pub fn get_attr<'a>(
} else {
None
}
})
{
}).map_or_else(|| {
sess.span_err(attr_segments[1].ident.span, "Usage of unknown attribute");
false
}, |deprecation_status| {
let mut diag = sess.struct_span_err(attr_segments[1].ident.span, "Usage of deprecated attribute");
match *deprecation_status {
DeprecationStatus::Deprecated => {
@ -97,10 +98,7 @@ pub fn get_attr<'a>(
attr_segments[1].ident.to_string() == name
},
}
} else {
sess.span_err(attr_segments[1].ident.span, "Usage of unknown attribute");
false
}
})
} else {
false
}

View File

@ -153,11 +153,7 @@ pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symb
pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
let def_id = cx.tables().type_dependent_def_id(expr.hir_id).unwrap();
let trt_id = cx.tcx.trait_of_item(def_id);
if let Some(trt_id) = trt_id {
match_def_path(cx, trt_id, path)
} else {
false
}
trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
}
/// Checks if an expression references a variable of the given name.
@ -600,21 +596,13 @@ pub fn snippet_block_with_applicability<'a, T: LintContext>(
/// // ^^^^^^^^^^
/// ```
pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
if let Some(first_char_pos) = first_char_in_first_line(cx, span) {
span.with_lo(first_char_pos)
} else {
span
}
first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
}
fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
let line_span = line_span(cx, span);
if let Some(snip) = snippet_opt(cx, line_span) {
snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos))
} else {
None
}
snippet_opt(cx, line_span).and_then(|snip| snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos)))
}
/// Returns the indentation of the line of a span
@ -626,11 +614,7 @@ fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePo
/// // ^^ -- will return 4
/// ```
pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
if let Some(snip) = snippet_opt(cx, line_span(cx, span)) {
snip.find(|c: char| !c.is_whitespace())
} else {
None
}
snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
}
/// Extends the span to the beginning of the spans line, incl. whitespaces.
@ -738,8 +722,7 @@ pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Optio
let enclosing_node = map
.get_enclosing_scope(hir_id)
.and_then(|enclosing_id| map.find(enclosing_id));
if let Some(node) = enclosing_node {
match node {
enclosing_node.and_then(|node| match node {
Node::Block(block) => Some(block),
Node::Item(&Item {
kind: ItemKind::Fn(_, _, eid),
@ -753,10 +736,7 @@ pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Optio
_ => None,
},
_ => None,
}
} else {
None
}
})
}
/// Returns the base type for HIR references and pointers.
@ -1328,11 +1308,7 @@ pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
_ => None,
};
if let Some(did) = did {
must_use_attr(&cx.tcx.get_attrs(did)).is_some()
} else {
false
}
did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
}
pub fn is_no_std_crate(krate: &Crate<'_>) -> bool {

View File

@ -200,12 +200,10 @@ impl<'a> NumericLiteral<'a> {
fn split_suffix<'a>(src: &'a str, lit_kind: &LitKind) -> (&'a str, Option<&'a str>) {
debug_assert!(lit_kind.is_numeric());
if let Some(suffix_length) = lit_suffix_length(lit_kind) {
lit_suffix_length(lit_kind).map_or((src, None), |suffix_length| {
let (unsuffixed, suffix) = src.split_at(src.len() - suffix_length);
(unsuffixed, Some(suffix))
} else {
(src, None)
}
})
}
fn lit_suffix_length(lit_kind: &LitKind) -> Option<usize> {

View File

@ -492,8 +492,7 @@ fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
/// before it on its line.
fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
let lo = cx.sess().source_map().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((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */).and_then(|line| 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]`.
if lo.col == CharPos(pos) {
Some(line[..pos].into())
@ -502,10 +501,7 @@ fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
}
} else {
None
}
} else {
None
}
})
}
/// Convenience extension trait for `DiagnosticBuilder`.

View File

@ -297,12 +297,10 @@ impl EarlyLintPass for Write {
if let (Some(fmt_str), expr) = self.check_tts(cx, &mac.args.inner_tokens(), true) {
if fmt_str.symbol == Symbol::intern("") {
let mut applicability = Applicability::MachineApplicable;
let suggestion = if let Some(e) = expr {
snippet_with_applicability(cx, e.span, "v", &mut applicability)
} else {
let suggestion = expr.map_or_else(|| {
applicability = Applicability::HasPlaceholders;
Cow::Borrowed("v")
};
}, |e| snippet_with_applicability(cx, e.span, "v", &mut Applicability::MachineApplicable));
span_lint_and_sugg(
cx,