fix clippy warnings

clippy::needless_return
clippy::redundant_closure
clippy::or_fun_call
clippy::len_zero
clippy::expect_fun_call
clippy::assertions_on_constants
clippy::identity_conversion
clippy::chars_last_cmp
This commit is contained in:
Matthias Krüger 2019-04-11 13:48:13 +02:00
parent 896394a7a5
commit 4352681d62
19 changed files with 45 additions and 45 deletions

View File

@ -550,7 +550,7 @@ impl<'a> ChainFormatterShared<'a> {
let almost_total = if extendable {
prev_last_line_width
} else {
self.rewrites.iter().map(|a| a.len()).sum()
self.rewrites.iter().map(String::len).sum()
} + last.tries;
let one_line_budget = if self.child_count == 1 {
shape.width

View File

@ -353,7 +353,7 @@ pub fn rewrite_last_closure(
/// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`.
pub fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool {
args.iter()
.filter_map(|arg| arg.to_expr())
.filter_map(OverflowableItem::to_expr)
.filter(|expr| match expr.node {
ast::ExprKind::Closure(..) => true,
_ => false,

View File

@ -1243,7 +1243,7 @@ where
},
CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
CharClassesStatus::Normal => match chr {
'r' => match self.base.peek().map(|c| c.get_char()) {
'r' => match self.base.peek().map(RichChar::get_char) {
Some('#') | Some('"') => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::RawStringPrefix(0)

View File

@ -191,7 +191,7 @@ impl FileLines {
/// Returns an iterator over the files contained in `self`.
pub fn files(&self) -> Files<'_> {
Files(self.0.as_ref().map(|m| m.keys()))
Files(self.0.as_ref().map(HashMap::keys))
}
/// Returns JSON representation as accepted by the `--file-lines JSON` arg.

View File

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

View File

@ -263,7 +263,7 @@ impl FormattingError {
.and_then(|fl| {
fl.file
.get_line(fl.lines[0].line_index)
.map(|l| l.into_owned())
.map(std::borrow::Cow::into_owned)
})
.unwrap_or_else(String::new),
}
@ -653,7 +653,7 @@ fn parse_crate(
return Ok(c);
}
}
Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(|d| d.emit()),
Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
Err(_) => {
// Note that if you see this message and want more information,
// then run the `parse_crate_mod` function above without

View File

@ -98,7 +98,7 @@ fn uncommitted_files() -> Vec<String> {
stdout
.lines()
.filter(|s| s.ends_with(".rs"))
.map(|s| s.to_owned())
.map(std::borrow::ToOwned::to_owned)
.collect()
}

View File

@ -492,10 +492,7 @@ impl UseTree {
// Recursively normalize elements of a list use (including sorting the list).
if let UseSegment::List(list) = last {
let mut list = list
.into_iter()
.map(|ut| ut.normalize())
.collect::<Vec<_>>();
let mut list = list.into_iter().map(UseTree::normalize).collect::<Vec<_>>();
list.sort();
last = UseSegment::List(list);
}

View File

@ -1358,7 +1358,7 @@ fn format_tuple_struct(
context
.snippet_provider
.opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
.unwrap_or(last_arg_span.hi())
.unwrap_or_else(|| last_arg_span.hi())
};
let where_clause_str = match struct_parts.generics {
@ -2143,7 +2143,7 @@ fn rewrite_fn_base(
indent
} else {
if context.config.version() == Version::Two {
if arg_str.len() != 0 || !no_args_and_over_max_width {
if !arg_str.is_empty() || !no_args_and_over_max_width {
result.push(' ');
}
} else {
@ -2284,7 +2284,7 @@ fn rewrite_args(
span: Span,
variadic: bool,
) -> Option<String> {
if args.len() == 0 {
if args.is_empty() {
let comment = context
.snippet(mk_sp(
span.lo(),

View File

@ -445,7 +445,7 @@ fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSni
let block_len = formatted
.snippet
.rfind('}')
.unwrap_or(formatted.snippet.len());
.unwrap_or_else(|| formatted.snippet.len());
let mut is_indented = true;
for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
if !is_first {

View File

@ -389,7 +389,7 @@ where
result.push('\n');
result.push_str(indent_str);
// This is the width of the item (without comments).
line_len = item.item.as_ref().map_or(0, |str| str.len());
line_len = item.item.as_ref().map_or(0, String::len);
}
} else {
result.push(' ');
@ -646,7 +646,7 @@ pub fn get_comment_end(
if let Some(i) = block_open_index {
match post_snippet.find('/') {
Some(j) if j < i => block_open_index = None,
_ if post_snippet[..i].chars().last() == Some('/') => block_open_index = None,
_ if post_snippet[..i].ends_with('/') => block_open_index = None,
_ => (),
}
}
@ -811,7 +811,7 @@ where
pub fn total_item_width(item: &ListItem) -> usize {
comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
+ comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
+ item.item.as_ref().map_or(0, |str| str.len())
+ item.item.as_ref().map_or(0, String::len)
}
fn comment_len(comment: Option<&str>) -> usize {

View File

@ -933,8 +933,7 @@ impl MacroArgParser {
/// Returns a collection of parsed macro def's arguments.
pub fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
let stream: TokenStream = tokens.into();
let mut iter = stream.trees();
let mut iter = tokens.trees();
while let Some(tok) = iter.next() {
match tok {
@ -1045,18 +1044,17 @@ fn wrap_macro_args_inner(
// FIXME: Use multi-line when every thing does not fit on one line.
fn format_macro_args(
context: &RewriteContext<'_>,
toks: TokenStream,
token_stream: TokenStream,
shape: Shape,
) -> Option<String> {
if !context.config.format_macro_matchers() {
let token_stream: TokenStream = toks.into();
let span = span_for_token_stream(&token_stream);
return Some(match span {
Some(span) => context.snippet(span).to_owned(),
None => String::new(),
});
}
let parsed_args = MacroArgParser::new().parse(toks)?;
let parsed_args = MacroArgParser::new().parse(token_stream)?;
wrap_macro_args(context, &parsed_args, shape)
}
@ -1140,7 +1138,7 @@ fn next_space(tok: &Token) -> SpaceState {
/// failed).
pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> {
if &mac.node.path.to_string() == "try" {
let ts: TokenStream = mac.node.tts.clone().into();
let ts: TokenStream = mac.node.tts.clone();
let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
Some(ast::Expr {
@ -1194,7 +1192,7 @@ impl MacroParser {
TokenTree::Token(..) => return None,
TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
};
let args = tok.joint().into();
let args = tok.joint();
match self.toks.next()? {
TokenTree::Token(_, Token::FatArrow) => {}
_ => return None,

View File

@ -32,8 +32,10 @@ fn compare_items(a: &ast::Item, b: &ast::Item) -> Ordering {
(&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => {
// `extern crate foo as bar;`
// ^^^ Comparing this.
let a_orig_name = a_name.map_or_else(|| a.ident.as_str(), |symbol| symbol.as_str());
let b_orig_name = b_name.map_or_else(|| b.ident.as_str(), |symbol| symbol.as_str());
let a_orig_name =
a_name.map_or_else(|| a.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
let b_orig_name =
b_name.map_or_else(|| b.ident.as_str(), syntax_pos::symbol::Symbol::as_str);
let result = a_orig_name.cmp(&b_orig_name);
if result != Ordering::Equal {
return result;

View File

@ -69,7 +69,7 @@ where
// original text for `FileName::Stdin`.
let original_text = source_map
.and_then(|x| x.get_source_file(&filename.into()))
.and_then(|x| x.src.as_ref().map(|x| x.to_string()));
.and_then(|x| x.src.as_ref().map(ToString::to_string));
let original_text = match original_text {
Some(ori) => ori,
None => fs::read_to_string(ensure_real_path(filename))?,

View File

@ -71,7 +71,7 @@ impl<'a> SpanUtils for SnippetProvider<'a> {
impl LineRangeUtils for SourceMap {
fn lookup_line_range(&self, span: Span) -> LineRange {
let snippet = self.span_to_snippet(span).unwrap_or(String::new());
let snippet = self.span_to_snippet(span).unwrap_or_default();
let lo = self.lookup_line(span.lo()).unwrap();
let hi = self.lookup_line(span.hi()).unwrap();

View File

@ -338,11 +338,13 @@ fn is_new_line(grapheme: &str) -> bool {
}
fn is_whitespace(grapheme: &str) -> bool {
grapheme.chars().all(|c| c.is_whitespace())
grapheme.chars().all(char::is_whitespace)
}
fn is_punctuation(grapheme: &str) -> bool {
grapheme.chars().all(|c| c.is_punctuation_other())
grapheme
.chars()
.all(UnicodeCategories::is_punctuation_other)
}
fn graphemes_width(graphemes: &[&str]) -> usize {

View File

@ -34,7 +34,7 @@ struct TestSetting {
impl Default for TestSetting {
fn default() -> Self {
TestSetting {
stack_size: 8388608, // 8MB
stack_size: 8_388_608, // 8MB
}
}
}
@ -90,12 +90,13 @@ fn verify_config_used(path: &Path, config_name: &str) {
if path.extension().map_or(false, |f| f == "rs") {
// check if "// rustfmt-<config_name>:" appears in the file.
let filebuf = BufReader::new(
fs::File::open(&path).expect(&format!("couldn't read file {}", path.display())),
fs::File::open(&path)
.unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
);
assert!(
filebuf
.lines()
.map(|l| l.unwrap())
.map(Result::unwrap)
.take_while(|l| l.starts_with("//"))
.any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
format!(
@ -249,7 +250,7 @@ fn assert_output(source: &Path, expected_filename: &Path) {
let mut failures = HashMap::new();
failures.insert(source.to_owned(), compare);
print_mismatches_default_message(failures);
assert!(false, "Text does not match expected output");
panic!("Text does not match expected output");
}
}
@ -565,8 +566,8 @@ fn get_config(config_file: Option<&Path>) -> Config {
// Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
let file =
fs::File::open(file_name).expect(&format!("couldn't read file {}", file_name.display()));
let file = fs::File::open(file_name)
.unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
let reader = BufReader::new(file);
let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
@ -962,10 +963,10 @@ fn configuration_snippet_tests() {
fn get_code_blocks() -> Vec<ConfigCodeBlock> {
let mut file_iter = BufReader::new(
fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
.expect(&format!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
.unwrap_or_else(|_| panic!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
)
.lines()
.map(|l| l.unwrap())
.map(Result::unwrap)
.enumerate();
let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
let mut hash_set = Config::hash_set();
@ -988,7 +989,7 @@ fn configuration_snippet_tests() {
let blocks = get_code_blocks();
let failures = blocks
.iter()
.map(|b| b.formatted_is_idempotent())
.map(ConfigCodeBlock::formatted_is_idempotent)
.fold(0, |acc, r| acc + (!r as u32));
// Display results.

View File

@ -135,7 +135,7 @@ pub fn rewrite_with_alignment<T: AlignedItem>(
let snippet = context.snippet(missing_span);
if snippet.trim_start().starts_with("//") {
let offset = snippet.lines().next().map_or(0, |l| l.len());
let offset = snippet.lines().next().map_or(0, str::len);
// 2 = "," + "\n"
init_hi + BytePos(offset as u32 + 2)
} else if snippet.trim_start().starts_with("/*") {

View File

@ -146,7 +146,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
if let Some(first_stmt) = b.stmts.first() {
let hi = inner_attrs
.and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
.unwrap_or(first_stmt.span().lo());
.unwrap_or_else(|| first_stmt.span().lo());
let snippet = self.snippet(mk_sp(self.last_pos, hi));
let len = CommentCodeSlices::new(snippet)