Skip to content

Commit 510fb81

Browse files
matthiaskrgrcalebcartwright
authored andcommitted
fix a bunch of clippy warnings
clippy::bind_instead_of_map clippy::branches_sharing_code clippy::collapsible_match clippy::inconsistent_struct_constructor clippy::int_plus_one clippy::iter_count clippy::iter_nth_zero clippy::manual_range_contains clippy::match_like_matches_macro clippy::needless::collect clippy::needless_question_mark clippy::needless_return clippy::op_ref clippy::option_as_ref_deref clippy::ptr_arg clippy::redundant_clone clippy::redundant_closure clippy::redundant_static_lifetimes clippy::search_is_some clippy::#single_char_add_str clippy::single_char_pattern clippy::single_component_path_imports clippy::single_match clippy::skip_while_next clippy::unnecessary_lazy_evaluations clippy::unnecessary_unwrap clippy::useless_conversion clippy::useless_format
1 parent 2837ca5 commit 510fb81

27 files changed

+130
-205
lines changed

Diff for: src/attr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ fn format_derive(
183183
} else if let SeparatorTactic::Always = context.config.trailing_comma() {
184184
// Retain the trailing comma.
185185
result.push_str(&item_str);
186-
} else if item_str.ends_with(",") {
186+
} else if item_str.ends_with(',') {
187187
// Remove the trailing comma.
188188
result.push_str(&item_str[..item_str.len() - 1]);
189189
} else {

Diff for: src/cargo-fmt/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -405,8 +405,8 @@ fn get_targets_recursive(
405405
.packages
406406
.iter()
407407
.find(|p| p.name == dependency.name && p.source.is_none());
408-
let manifest_path = if dependency_package.is_some() {
409-
PathBuf::from(&dependency_package.unwrap().manifest_path)
408+
let manifest_path = if let Some(dep_pkg) = dependency_package {
409+
PathBuf::from(&dep_pkg.manifest_path)
410410
} else {
411411
let mut package_manifest_path = PathBuf::from(&package.manifest_path);
412412
package_manifest_path.pop();

Diff for: src/chains.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,7 @@ impl ChainItem {
231231
}
232232

233233
fn is_comment(&self) -> bool {
234-
match self.kind {
235-
ChainItemKind::Comment(..) => true,
236-
_ => false,
237-
}
234+
matches!(self.kind, ChainItemKind::Comment(..))
238235
}
239236

240237
fn rewrite_method_call(

Diff for: src/closures.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -336,23 +336,23 @@ pub(crate) fn rewrite_last_closure(
336336

337337
// We force to use block for the body of the closure for certain kinds of expressions.
338338
if is_block_closure_forced(context, body) {
339-
return rewrite_closure_with_block(body, &prefix, context, body_shape).and_then(
339+
return rewrite_closure_with_block(body, &prefix, context, body_shape).map(
340340
|body_str| {
341341
match fn_decl.output {
342342
ast::FnRetTy::Default(..) if body_str.lines().count() <= 7 => {
343343
// If the expression can fit in a single line, we need not force block
344344
// closure. However, if the closure has a return type, then we must
345345
// keep the blocks.
346346
match rewrite_closure_expr(body, &prefix, context, shape) {
347-
Some(ref single_line_body_str)
347+
Some(single_line_body_str)
348348
if !single_line_body_str.contains('\n') =>
349349
{
350-
Some(single_line_body_str.clone())
350+
single_line_body_str
351351
}
352-
_ => Some(body_str),
352+
_ => body_str,
353353
}
354354
}
355-
_ => Some(body_str),
355+
_ => body_str,
356356
}
357357
},
358358
);
@@ -377,10 +377,7 @@ pub(crate) fn rewrite_last_closure(
377377
pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
378378
args.iter()
379379
.filter_map(OverflowableItem::to_expr)
380-
.filter(|expr| match expr.kind {
381-
ast::ExprKind::Closure(..) => true,
382-
_ => false,
383-
})
380+
.filter(|expr| matches!(expr.kind, ast::ExprKind::Closure(..)))
384381
.count()
385382
> 1
386383
}

Diff for: src/comment.rs

+9-12
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,7 @@ impl<'a> CommentStyle<'a> {
6767

6868
/// Returns `true` if the commenting style is for documentation.
6969
pub(crate) fn is_doc_comment(&self) -> bool {
70-
match *self {
71-
CommentStyle::TripleSlash | CommentStyle::Doc => true,
72-
_ => false,
73-
}
70+
matches!(*self, CommentStyle::TripleSlash | CommentStyle::Doc)
7471
}
7572

7673
pub(crate) fn opener(&self) -> &'a str {
@@ -689,8 +686,8 @@ impl<'a> CommentRewrite<'a> {
689686

690687
self.code_block_attr = None;
691688
self.item_block = None;
692-
if line.starts_with("```") {
693-
self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
689+
if let Some(stripped) = line.strip_prefix("```") {
690+
self.code_block_attr = Some(CodeBlockAttribute::new(stripped))
694691
} else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
695692
let ib = ItemizedBlock::new(&line);
696693
self.item_block = Some(ib);
@@ -948,8 +945,8 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s
948945
{
949946
(&line[4..], true)
950947
} else if let CommentStyle::Custom(opener) = *style {
951-
if line.starts_with(opener) {
952-
(&line[opener.len()..], true)
948+
if let Some(ref stripped) = line.strip_prefix(opener) {
949+
(stripped, true)
953950
} else {
954951
(&line[opener.trim_end().len()..], false)
955952
}
@@ -968,8 +965,8 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s
968965
|| line.starts_with("**")
969966
{
970967
(&line[2..], line.chars().nth(1).unwrap() == ' ')
971-
} else if line.starts_with('*') {
972-
(&line[1..], false)
968+
} else if let Some(stripped) = line.strip_prefix('*') {
969+
(stripped, false)
973970
} else {
974971
(line, line.starts_with(' '))
975972
}
@@ -1682,8 +1679,8 @@ impl<'a> Iterator for CommentReducer<'a> {
16821679
fn remove_comment_header(comment: &str) -> &str {
16831680
if comment.starts_with("///") || comment.starts_with("//!") {
16841681
&comment[3..]
1685-
} else if comment.starts_with("//") {
1686-
&comment[2..]
1682+
} else if let Some(ref stripped) = comment.strip_prefix("//") {
1683+
stripped
16871684
} else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
16881685
|| comment.starts_with("/*!")
16891686
{

Diff for: src/config/file_lines.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ impl str::FromStr for FileLines {
305305
let mut m = HashMap::new();
306306
for js in v {
307307
let (s, r) = JsonSpan::into_tuple(js)?;
308-
m.entry(s).or_insert_with(|| vec![]).push(r);
308+
m.entry(s).or_insert_with(Vec::new).push(r);
309309
}
310310
Ok(FileLines::from_ranges(m))
311311
}
@@ -322,7 +322,7 @@ impl JsonSpan {
322322
fn into_tuple(self) -> Result<(FileName, Range), FileLinesError> {
323323
let (lo, hi) = self.range;
324324
let canonical = canonicalize_path_string(&self.file)
325-
.ok_or_else(|| FileLinesError::CannotCanonicalize(self.file))?;
325+
.ok_or(FileLinesError::CannotCanonicalize(self.file))?;
326326
Ok((canonical, Range::new(lo, hi)))
327327
}
328328
}

Diff for: src/config/license.rs

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use std::fs::File;
33
use std::io;
44
use std::io::Read;
55

6-
use regex;
76
use regex::Regex;
87

98
#[derive(Debug)]

Diff for: src/emitter/diff.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ impl Emitter for DiffEmitter {
4545
return Ok(EmitterResult { has_diff: true });
4646
}
4747

48-
return Ok(EmitterResult { has_diff });
48+
Ok(EmitterResult { has_diff })
4949
}
5050
}
5151

Diff for: src/expr.rs

+10-20
Original file line numberDiff line numberDiff line change
@@ -261,15 +261,12 @@ pub(crate) fn format_expr(
261261
}
262262

263263
fn needs_space_after_range(rhs: &ast::Expr) -> bool {
264-
match rhs.kind {
265-
// Don't format `.. ..` into `....`, which is invalid.
266-
//
267-
// This check is unnecessary for `lhs`, because a range
268-
// starting from another range needs parentheses as `(x ..) ..`
269-
// (`x .. ..` is a range from `x` to `..`).
270-
ast::ExprKind::Range(None, _, _) => true,
271-
_ => false,
272-
}
264+
// Don't format `.. ..` into `....`, which is invalid.
265+
//
266+
// This check is unnecessary for `lhs`, because a range
267+
// starting from another range needs parentheses as `(x ..) ..`
268+
// (`x .. ..` is a range from `x` to `..`).
269+
matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
273270
}
274271

275272
let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
@@ -529,7 +526,7 @@ pub(crate) fn rewrite_block_with_visitor(
529526

530527
let inner_attrs = attrs.map(inner_attributes);
531528
let label_str = rewrite_label(label);
532-
visitor.visit_block(block, inner_attrs.as_ref().map(|a| &**a), has_braces);
529+
visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
533530
let visitor_context = visitor.get_context();
534531
context
535532
.skipped_range
@@ -593,7 +590,7 @@ pub(crate) fn rewrite_cond(
593590
String::from("\n") + &shape.indent.block_only().to_string(context.config);
594591
control_flow
595592
.rewrite_cond(context, shape, &alt_block_sep)
596-
.and_then(|rw| Some(rw.0))
593+
.map(|rw| rw.0)
597594
}),
598595
}
599596
}
@@ -1155,18 +1152,11 @@ pub(crate) fn is_empty_block(
11551152
}
11561153

11571154
pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool {
1158-
match stmt.kind {
1159-
ast::StmtKind::Expr(..) => true,
1160-
_ => false,
1161-
}
1155+
matches!(stmt.kind, ast::StmtKind::Expr(..))
11621156
}
11631157

11641158
pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool {
1165-
if let ast::BlockCheckMode::Unsafe(..) = block.rules {
1166-
true
1167-
} else {
1168-
false
1169-
}
1159+
matches!(block.rules, ast::BlockCheckMode::Unsafe(..))
11701160
}
11711161

11721162
pub(crate) fn rewrite_literal(

Diff for: src/formatting/newline_style.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ fn convert_to_windows_newlines(formatted_text: &String) -> String {
7777
transformed
7878
}
7979

80-
fn convert_to_unix_newlines(formatted_text: &String) -> String {
80+
fn convert_to_unix_newlines(formatted_text: &str) -> String {
8181
formatted_text.replace(WINDOWS_NEWLINE, UNIX_NEWLINE)
8282
}
8383

Diff for: src/imports.rs

+11-19
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ impl UseTree {
374374
UseTreeKind::Nested(ref list) => {
375375
// Extract comments between nested use items.
376376
// This needs to be done before sorting use items.
377-
let items: Vec<_> = itemize_list(
377+
let items = itemize_list(
378378
context.snippet_provider,
379379
list.iter().map(|(tree, _)| tree),
380380
"}",
@@ -385,16 +385,16 @@ impl UseTree {
385385
context.snippet_provider.span_after(a.span, "{"),
386386
a.span.hi(),
387387
false,
388-
)
389-
.collect();
388+
);
389+
390390
// in case of a global path and the nested list starts at the root,
391391
// e.g., "::{foo, bar}"
392392
if a.prefix.segments.len() == 1 && leading_modsep {
393393
result.path.push(UseSegment::Ident("".to_owned(), None));
394394
}
395395
result.path.push(UseSegment::List(
396396
list.iter()
397-
.zip(items.into_iter())
397+
.zip(items)
398398
.map(|(t, list_item)| {
399399
Self::from_ast(context, &t.0, Some(list_item), None, None, None)
400400
})
@@ -466,11 +466,8 @@ impl UseTree {
466466

467467
// Normalise foo::self as bar -> foo as bar.
468468
if let UseSegment::Slf(_) = last {
469-
match self.path.last() {
470-
Some(UseSegment::Ident(_, None)) => {
471-
aliased_self = true;
472-
}
473-
_ => {}
469+
if let Some(UseSegment::Ident(_, None)) = self.path.last() {
470+
aliased_self = true;
474471
}
475472
}
476473

@@ -572,9 +569,8 @@ impl UseTree {
572569
match self.path.clone().last().unwrap() {
573570
UseSegment::List(list) => {
574571
if list.len() == 1 && list[0].path.len() == 1 {
575-
match list[0].path[0] {
576-
UseSegment::Slf(..) => return vec![self],
577-
_ => (),
572+
if let UseSegment::Slf(..) = list[0].path[0] {
573+
return vec![self];
578574
};
579575
}
580576
let prefix = &self.path[..self.path.len() - 1];
@@ -790,13 +786,9 @@ fn rewrite_nested_use_tree(
790786
}
791787
}
792788
let has_nested_list = use_tree_list.iter().any(|use_segment| {
793-
use_segment
794-
.path
795-
.last()
796-
.map_or(false, |last_segment| match last_segment {
797-
UseSegment::List(..) => true,
798-
_ => false,
799-
})
789+
use_segment.path.last().map_or(false, |last_segment| {
790+
matches!(last_segment, UseSegment::List(..))
791+
})
800792
});
801793

802794
let remaining_width = if has_nested_list {

Diff for: src/issues.rs

+3-11
Original file line numberDiff line numberDiff line change
@@ -126,11 +126,7 @@ impl BadIssueSeeker {
126126
return Seeking::Number {
127127
issue: Issue {
128128
issue_type: IssueType::Todo,
129-
missing_number: if let ReportTactic::Unnumbered = self.report_todo {
130-
true
131-
} else {
132-
false
133-
},
129+
missing_number: matches!(self.report_todo, ReportTactic::Unnumbered),
134130
},
135131
part: NumberPart::OpenParen,
136132
};
@@ -144,11 +140,7 @@ impl BadIssueSeeker {
144140
return Seeking::Number {
145141
issue: Issue {
146142
issue_type: IssueType::Fixme,
147-
missing_number: if let ReportTactic::Unnumbered = self.report_fixme {
148-
true
149-
} else {
150-
false
151-
},
143+
missing_number: matches!(self.report_fixme, ReportTactic::Unnumbered),
152144
},
153145
part: NumberPart::OpenParen,
154146
};
@@ -196,7 +188,7 @@ impl BadIssueSeeker {
196188
}
197189
}
198190
NumberPart::Number => {
199-
if c >= '0' && c <= '9' {
191+
if ('0'..='9').contains(&c) {
200192
part = NumberPart::CloseParen;
201193
} else {
202194
return IssueClassification::Bad(issue);

0 commit comments

Comments
 (0)