Skip to content

Commit 7862051

Browse files
authored
Merge pull request rust-lang#3504 from matthiaskrgr/clippy_2
fix a bunch of clippy warnings
2 parents 896394a + 4352681 commit 7862051

19 files changed

+45
-45
lines changed

src/chains.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,7 @@ impl<'a> ChainFormatterShared<'a> {
550550
let almost_total = if extendable {
551551
prev_last_line_width
552552
} else {
553-
self.rewrites.iter().map(|a| a.len()).sum()
553+
self.rewrites.iter().map(String::len).sum()
554554
} + last.tries;
555555
let one_line_budget = if self.child_count == 1 {
556556
shape.width

src/closures.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ pub fn rewrite_last_closure(
353353
/// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
354354
pub fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
355355
args.iter()
356-
.filter_map(|arg| arg.to_expr())
356+
.filter_map(OverflowableItem::to_expr)
357357
.filter(|expr| match expr.node {
358358
ast::ExprKind::Closure(..) => true,
359359
_ => false,

src/comment.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1243,7 +1243,7 @@ where
12431243
},
12441244
CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
12451245
CharClassesStatus::Normal => match chr {
1246-
'r' => match self.base.peek().map(|c| c.get_char()) {
1246+
'r' => match self.base.peek().map(RichChar::get_char) {
12471247
Some('#') | Some('"') => {
12481248
char_kind = FullCodeCharKind::InString;
12491249
CharClassesStatus::RawStringPrefix(0)

src/config/file_lines.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ impl FileLines {
191191

192192
/// Returns an iterator over the files contained in `self`.
193193
pub fn files(&self) -> Files<'_> {
194-
Files(self.0.as_ref().map(|m| m.keys()))
194+
Files(self.0.as_ref().map(HashMap::keys))
195195
}
196196

197197
/// Returns JSON representation as accepted by the `--file-lines JSON` arg.

src/config/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ impl Config {
244244
}
245245
}
246246

247-
return Ok(None);
247+
Ok(None)
248248
}
249249

250250
match resolve_project_file(dir)? {
@@ -260,7 +260,7 @@ impl Config {
260260
let mut err = String::new();
261261
let table = parsed
262262
.as_table()
263-
.ok_or(String::from("Parsed config was not table"))?;
263+
.ok_or_else(|| String::from("Parsed config was not table"))?;
264264
for key in table.keys() {
265265
if !Config::is_valid_name(key) {
266266
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
@@ -358,7 +358,7 @@ fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
358358
config_path_not_found(path.to_str().unwrap())
359359
}
360360
}
361-
path => Ok(path.map(|p| p.to_owned())),
361+
path => Ok(path.map(ToOwned::to_owned)),
362362
}
363363
}
364364

src/formatting.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ impl FormattingError {
263263
.and_then(|fl| {
264264
fl.file
265265
.get_line(fl.lines[0].line_index)
266-
.map(|l| l.into_owned())
266+
.map(std::borrow::Cow::into_owned)
267267
})
268268
.unwrap_or_else(String::new),
269269
}
@@ -653,7 +653,7 @@ fn parse_crate(
653653
return Ok(c);
654654
}
655655
}
656-
Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(|d| d.emit()),
656+
Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
657657
Err(_) => {
658658
// Note that if you see this message and want more information,
659659
// then run the `parse_crate_mod` function above without

src/git-rustfmt/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ fn uncommitted_files() -> Vec<String> {
9898
stdout
9999
.lines()
100100
.filter(|s| s.ends_with(".rs"))
101-
.map(|s| s.to_owned())
101+
.map(std::borrow::ToOwned::to_owned)
102102
.collect()
103103
}
104104

src/imports.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -492,10 +492,7 @@ impl UseTree {
492492

493493
// Recursively normalize elements of a list use (including sorting the list).
494494
if let UseSegment::List(list) = last {
495-
let mut list = list
496-
.into_iter()
497-
.map(|ut| ut.normalize())
498-
.collect::<Vec<_>>();
495+
let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
499496
list.sort();
500497
last = UseSegment::List(list);
501498
}

src/items.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,7 +1358,7 @@ fn format_tuple_struct(
13581358
context
13591359
.snippet_provider
13601360
.opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1361-
.unwrap_or(last_arg_span.hi())
1361+
.unwrap_or_else(|| last_arg_span.hi())
13621362
};
13631363

13641364
let where_clause_str = match struct_parts.generics {
@@ -2143,7 +2143,7 @@ fn rewrite_fn_base(
21432143
indent
21442144
} else {
21452145
if context.config.version() == Version::Two {
2146-
if arg_str.len() != 0 || !no_args_and_over_max_width {
2146+
if !arg_str.is_empty() || !no_args_and_over_max_width {
21472147
result.push(' ');
21482148
}
21492149
} else {
@@ -2284,7 +2284,7 @@ fn rewrite_args(
22842284
span: Span,
22852285
variadic: bool,
22862286
) -> Option<String> {
2287-
if args.len() == 0 {
2287+
if args.is_empty() {
22882288
let comment = context
22892289
.snippet(mk_sp(
22902290
span.lo(),

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,7 @@ fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSni
445445
let block_len = formatted
446446
.snippet
447447
.rfind('}')
448-
.unwrap_or(formatted.snippet.len());
448+
.unwrap_or_else(|| formatted.snippet.len());
449449
let mut is_indented = true;
450450
for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
451451
if !is_first {

src/lists.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ where
389389
result.push('\n');
390390
result.push_str(indent_str);
391391
// This is the width of the item (without comments).
392-
line_len = item.item.as_ref().map_or(0, |str| str.len());
392+
line_len = item.item.as_ref().map_or(0, String::len);
393393
}
394394
} else {
395395
result.push(' ');
@@ -646,7 +646,7 @@ pub fn get_comment_end(
646646
if let Some(i) = block_open_index {
647647
match post_snippet.find('/') {
648648
Some(j) if j < i => block_open_index = None,
649-
_ if post_snippet[..i].chars().last() == Some('/') => block_open_index = None,
649+
_ if post_snippet[..i].ends_with('/') => block_open_index = None,
650650
_ => (),
651651
}
652652
}
@@ -811,7 +811,7 @@ where
811811
pub fn total_item_width(item: &ListItem) -> usize {
812812
comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
813813
+ comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
814-
+ item.item.as_ref().map_or(0, |str| str.len())
814+
+ item.item.as_ref().map_or(0, String::len)
815815
}
816816

817817
fn comment_len(comment: Option<&str>) -> usize {

src/macros.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -933,8 +933,7 @@ impl MacroArgParser {
933933

934934
/// Returns a collection of parsed macro def's arguments.
935935
pub fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
936-
let stream: TokenStream = tokens.into();
937-
let mut iter = stream.trees();
936+
let mut iter = tokens.trees();
938937

939938
while let Some(tok) = iter.next() {
940939
match tok {
@@ -1045,18 +1044,17 @@ fn wrap_macro_args_inner(
10451044
// FIXME: Use multi-line when every thing does not fit on one line.
10461045
fn format_macro_args(
10471046
context: &RewriteContext<'_>,
1048-
toks: TokenStream,
1047+
token_stream: TokenStream,
10491048
shape: Shape,
10501049
) -> Option<String> {
10511050
if !context.config.format_macro_matchers() {
1052-
let token_stream: TokenStream = toks.into();
10531051
let span = span_for_token_stream(&token_stream);
10541052
return Some(match span {
10551053
Some(span) => context.snippet(span).to_owned(),
10561054
None => String::new(),
10571055
});
10581056
}
1059-
let parsed_args = MacroArgParser::new().parse(toks)?;
1057+
let parsed_args = MacroArgParser::new().parse(token_stream)?;
10601058
wrap_macro_args(context, &parsed_args, shape)
10611059
}
10621060

@@ -1140,7 +1138,7 @@ fn next_space(tok: &Token) -> SpaceState {
11401138
/// failed).
11411139
pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> {
11421140
if &mac.node.path.to_string() == "try" {
1143-
let ts: TokenStream = mac.node.tts.clone().into();
1141+
let ts: TokenStream = mac.node.tts.clone();
11441142
let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
11451143

11461144
Some(ast::Expr {
@@ -1194,7 +1192,7 @@ impl MacroParser {
11941192
TokenTree::Token(..) => return None,
11951193
TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
11961194
};
1197-
let args = tok.joint().into();
1195+
let args = tok.joint();
11981196
match self.toks.next()? {
11991197
TokenTree::Token(_, Token::FatArrow) => {}
12001198
_ => return None,

src/reorder.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
3232
(&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
3333
// `extern crate foo as bar;`
3434
// ^^^ Comparing this.
35-
let a_orig_name = a_name.map_or_else(|| a.ident.as_str(), |symbol| symbol.as_str());
36-
let b_orig_name = b_name.map_or_else(|| b.ident.as_str(), |symbol| symbol.as_str());
35+
let a_orig_name =
36+
a_name.map_or_else(|| a.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
37+
let b_orig_name =
38+
b_name.map_or_else(|| b.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
3739
let result = a_orig_name.cmp(&b_orig_name);
3840
if result != Ordering::Equal {
3941
return result;

src/source_file.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ where
6969
// original text for `FileName::Stdin`.
7070
let original_text = source_map
7171
.and_then(|x| x.get_source_file(&filename.into()))
72-
.and_then(|x| x.src.as_ref().map(|x| x.to_string()));
72+
.and_then(|x| x.src.as_ref().map(ToString::to_string));
7373
let original_text = match original_text {
7474
Some(ori) => ori,
7575
None => fs::read_to_string(ensure_real_path(filename))?,

src/source_map.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ impl<'a> SpanUtils for SnippetProvider<'a> {
7171

7272
impl LineRangeUtils for SourceMap {
7373
fn lookup_line_range(&self, span: Span) -> LineRange {
74-
let snippet = self.span_to_snippet(span).unwrap_or(String::new());
74+
let snippet = self.span_to_snippet(span).unwrap_or_default();
7575
let lo = self.lookup_line(span.lo()).unwrap();
7676
let hi = self.lookup_line(span.hi()).unwrap();
7777

src/string.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,11 +338,13 @@ fn is_new_line(grapheme: &str) -> bool {
338338
}
339339

340340
fn is_whitespace(grapheme: &str) -> bool {
341-
grapheme.chars().all(|c| c.is_whitespace())
341+
grapheme.chars().all(char::is_whitespace)
342342
}
343343

344344
fn is_punctuation(grapheme: &str) -> bool {
345-
grapheme.chars().all(|c| c.is_punctuation_other())
345+
grapheme
346+
.chars()
347+
.all(UnicodeCategories::is_punctuation_other)
346348
}
347349

348350
fn graphemes_width(graphemes: &[&str]) -> usize {

src/test/mod.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ struct TestSetting {
3434
impl Default for TestSetting {
3535
fn default() -> Self {
3636
TestSetting {
37-
stack_size: 8388608, // 8MB
37+
stack_size: 8_388_608, // 8MB
3838
}
3939
}
4040
}
@@ -90,12 +90,13 @@ fn verify_config_used(path: &Path, config_name: &str) {
9090
if path.extension().map_or(false, |f| f == "rs") {
9191
// check if "// rustfmt-<config_name>:" appears in the file.
9292
let filebuf = BufReader::new(
93-
fs::File::open(&path).expect(&format!("couldn't read file {}", path.display())),
93+
fs::File::open(&path)
94+
.unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
9495
);
9596
assert!(
9697
filebuf
9798
.lines()
98-
.map(|l| l.unwrap())
99+
.map(Result::unwrap)
99100
.take_while(|l| l.starts_with("//"))
100101
.any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
101102
format!(
@@ -249,7 +250,7 @@ fn assert_output(source: &Path, expected_filename: &Path) {
249250
let mut failures = HashMap::new();
250251
failures.insert(source.to_owned(), compare);
251252
print_mismatches_default_message(failures);
252-
assert!(false, "Text does not match expected output");
253+
panic!("Text does not match expected output");
253254
}
254255
}
255256

@@ -565,8 +566,8 @@ fn get_config(config_file: Option<&Path>) -> Config {
565566

566567
// Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
567568
fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
568-
let file =
569-
fs::File::open(file_name).expect(&format!("couldn't read file {}", file_name.display()));
569+
let file = fs::File::open(file_name)
570+
.unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
570571
let reader = BufReader::new(file);
571572
let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
572573
let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
@@ -962,10 +963,10 @@ fn configuration_snippet_tests() {
962963
fn get_code_blocks() -> Vec<ConfigCodeBlock> {
963964
let mut file_iter = BufReader::new(
964965
fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
965-
.expect(&format!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
966+
.unwrap_or_else(|_| panic!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
966967
)
967968
.lines()
968-
.map(|l| l.unwrap())
969+
.map(Result::unwrap)
969970
.enumerate();
970971
let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
971972
let mut hash_set = Config::hash_set();
@@ -988,7 +989,7 @@ fn configuration_snippet_tests() {
988989
let blocks = get_code_blocks();
989990
let failures = blocks
990991
.iter()
991-
.map(|b| b.formatted_is_idempotent())
992+
.map(ConfigCodeBlock::formatted_is_idempotent)
992993
.fold(0, |acc, r| acc + (!r as u32));
993994

994995
// Display results.

src/vertical.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ pub fn rewrite_with_alignment<T: AlignedItem>(
135135

136136
let snippet = context.snippet(missing_span);
137137
if snippet.trim_start().starts_with("//") {
138-
let offset = snippet.lines().next().map_or(0, |l| l.len());
138+
let offset = snippet.lines().next().map_or(0, str::len);
139139
// 2 = "," + "\n"
140140
init_hi + BytePos(offset as u32 + 2)
141141
} else if snippet.trim_start().starts_with("/*") {

src/visitor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
146146
if let Some(first_stmt) = b.stmts.first() {
147147
let hi = inner_attrs
148148
.and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
149-
.unwrap_or(first_stmt.span().lo());
149+
.unwrap_or_else(|| first_stmt.span().lo());
150150

151151
let snippet = self.snippet(mk_sp(self.last_pos, hi));
152152
let len = CommentCodeSlices::new(snippet)

0 commit comments

Comments
 (0)