diff --git a/src/bin/main.rs b/src/bin/main.rs index 88281d296be..aaf71c6203c 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -439,15 +439,15 @@ fn print_version() { fn determine_operation(matches: &Matches) -> Result { if matches.opt_present("h") { - let topic = matches.opt_str("h"); - if topic.is_none() { + let Some(topic) = matches.opt_str("h") else { return Ok(Operation::Help(HelpOp::None)); - } else if topic == Some("config".to_owned()) { + }; + if topic == "config" { return Ok(Operation::Help(HelpOp::Config)); - } else if topic == Some("file-lines".to_owned()) && is_nightly() { + } else if topic == "file-lines" && is_nightly() { return Ok(Operation::Help(HelpOp::FileLines)); } else { - return Err(OperationError::UnknownHelpTopic(topic.unwrap())); + return Err(OperationError::UnknownHelpTopic(topic)); } } let mut free_matches = matches.free.iter(); @@ -523,9 +523,11 @@ struct GetOptsOptions { impl GetOptsOptions { pub fn from_matches(matches: &Matches) -> Result { - let mut options = GetOptsOptions::default(); - options.verbose = matches.opt_present("verbose"); - options.quiet = matches.opt_present("quiet"); + let mut options = Self { + verbose: matches.opt_present("verbose"), + quiet: matches.opt_present("quiet"), + ..Self::default() + }; if options.verbose && options.quiet { return Err(format_err!("Can't use both `--verbose` and `--quiet`")); } diff --git a/src/chains.rs b/src/chains.rs index 010e661d292..8944029199a 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -202,7 +202,7 @@ impl ChainItemKind { fn is_tup_field_access(expr: &ast::Expr) -> bool { match expr.kind { ast::ExprKind::Field(_, ref field) => { - field.name.to_string().chars().all(|c| c.is_digit(10)) + field.name.to_string().bytes().all(|c| c.is_ascii_digit()) } _ => false, } diff --git a/src/comment.rs b/src/comment.rs index 2ffd9c245fa..64c3dc77203 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -118,7 +118,7 @@ impl<'a> CommentStyle<'a> { } } - pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) { + pub(crate) fn to_str_tuplet(self) -> (&'a str, &'a str, &'a str) { (self.opener(), self.closer(), self.line_start()) } } @@ -990,11 +990,12 @@ fn is_table_item(mut s: &str) -> bool { // This function may return false positive, but should get its job done in most cases (i.e. // markdown tables with two column delimiters). s = s.trim_start(); - return s.starts_with('|') + + s.starts_with('|') && match s.rfind('|') { Some(0) | None => false, _ => true, - }; + } } /// Given the span, rewrite the missing comment inside it if available. diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 7551241fc00..12031451f91 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -477,7 +477,7 @@ macro_rules! create_config { } } - #[allow(unreachable_pub)] + #[allow(unreachable_pub, clippy::cmp_owned)] /// Returns `true` if the config key was explicitly set and is the default value. pub fn is_default(&self, key: &str) -> bool { $( diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index e584ae7704e..d6fb128fa33 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -163,7 +163,7 @@ impl fmt::Display for FileLines { Some(map) => { for (file_name, ranges) in map.iter() { write!(f, "{file_name}: ")?; - write!(f, "{}\n", ranges.iter().format(", "))?; + writeln!(f, "{}", ranges.iter().format(", "))?; } } }; diff --git a/src/config/options.rs b/src/config/options.rs index fcef879ab44..471475f655b 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -1,4 +1,5 @@ #![allow(unused_imports)] +#![allow(clippy::enum_variant_names)] use std::collections::{hash_set, HashSet}; use std::fmt; @@ -153,9 +154,11 @@ pub enum ReportTactic { /// What Rustfmt should emit. Mostly corresponds to the `--emit` command line /// option. +#[derive(Default)] #[config_type] pub enum EmitMode { /// Emits to files. + #[default] Files, /// Writes the output to stdout. Stdout, @@ -308,12 +311,6 @@ impl ::std::str::FromStr for WidthHeuristics { } } -impl Default for EmitMode { - fn default() -> EmitMode { - EmitMode::Files - } -} - /// A set of directories, files and modules that rustfmt should ignore. #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct IgnoreList { @@ -417,10 +414,12 @@ pub trait CliOptions { } /// The edition of the syntax and semntics of code (RFC 2052). +#[derive(Default)] #[config_type] pub enum Edition { #[value = "2015"] #[doc_hint = "2015"] + #[default] /// Edition 2015. Edition2015, #[value = "2018"] @@ -437,12 +436,6 @@ pub enum Edition { Edition2024, } -impl Default for Edition { - fn default() -> Edition { - Edition::Edition2015 - } -} - impl From for rustc_span::edition::Edition { fn from(edition: Edition) -> Self { match edition { diff --git a/src/emitter/json.rs b/src/emitter/json.rs index 565e8ceb1c3..a55e2664d9d 100644 --- a/src/emitter/json.rs +++ b/src/emitter/json.rs @@ -136,7 +136,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); @@ -181,7 +181,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); diff --git a/src/expr.rs b/src/expr.rs index f18129cb256..76a2f1f9f12 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -274,10 +274,10 @@ pub(crate) fn format_expr( ast::RangeLimits::Closed => "..=", }; - fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool { + fn needs_space_before_range(lhs: &ast::Expr) -> bool { match lhs.kind { ast::ExprKind::Lit(token_lit) => lit_ends_in_dot(&token_lit), - ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr), + ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(expr), _ => false, } } @@ -296,7 +296,7 @@ pub(crate) fn format_expr( format!( "{}{}{}", - lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))), + lhs.map_or("", |lhs| space_if(needs_space_before_range(lhs))), delim, rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))), ) @@ -1573,11 +1573,11 @@ fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool !has_base && fields.iter().all(|field| !field.is_shorthand) } -fn rewrite_struct_lit<'a>( +fn rewrite_struct_lit( context: &RewriteContext<'_>, path: &ast::Path, qself: &Option>, - fields: &'a [ast::ExprField], + fields: &[ast::ExprField], struct_rest: &ast::StructRest, attrs: &[ast::Attribute], span: Span, @@ -1620,14 +1620,14 @@ fn rewrite_struct_lit<'a>( one_line_width, )? } else { - let field_iter = fields.iter().map(StructLitField::Regular).chain( - match struct_rest { + let field_iter = fields + .iter() + .map(StructLitField::Regular) + .chain(match struct_rest { ast::StructRest::Base(expr) => Some(StructLitField::Base(expr)), ast::StructRest::Rest(span) => Some(StructLitField::Rest(*span)), ast::StructRest::None => None, - } - .into_iter(), - ); + }); let span_lo = |item: &StructLitField<'_>| match *item { StructLitField::Regular(field) => field.span().lo(), diff --git a/src/formatting.rs b/src/formatting.rs index 7af8bc783f3..c46528c9983 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -533,7 +533,7 @@ impl<'a> FormatLines<'a> { } // Iterate over the chars in the file map. - fn iterate(&mut self, text: &mut String) { + fn iterate(&mut self, text: &mut str) { for (kind, c) in CharClasses::new(text.chars()) { if c == '\r' { continue; diff --git a/src/items.rs b/src/items.rs index 851d42a2fa4..d55e27c13da 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1224,7 +1224,7 @@ pub(crate) fn format_trait( let item_snippet = context.snippet(item.span); if let Some(lo) = item_snippet.find('/') { // 1 = `{` - let comment_hi = if generics.params.len() > 0 { + let comment_hi = if !generics.params.is_empty() { generics.span.lo() - BytePos(1) } else { body_lo - BytePos(1) @@ -1663,11 +1663,11 @@ struct TyAliasRewriteInfo<'c, 'g>( Span, ); -pub(crate) fn rewrite_type_alias<'a, 'b>( +pub(crate) fn rewrite_type_alias( ty_alias_kind: &ast::TyAlias, - context: &RewriteContext<'a>, + context: &RewriteContext<'_>, indent: Indent, - visitor_kind: &ItemVisitorKind<'b>, + visitor_kind: &ItemVisitorKind<'_>, span: Span, ) -> Option { use ItemVisitorKind::*; diff --git a/src/lib.rs b/src/lib.rs index 8311f081b8a..f95b3b01340 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -516,7 +516,7 @@ impl<'b, T: Write + 'b> Session<'b, T> { pub(crate) fn create_emitter<'a>(config: &Config) -> Box { match config.emit_mode() { EmitMode::Files if config.make_backup() => { - Box::new(emitter::FilesWithBackupEmitter::default()) + >::default() } EmitMode::Files => Box::new(emitter::FilesEmitter::new( config.print_misformatted_file_names(), @@ -524,9 +524,9 @@ pub(crate) fn create_emitter<'a>(config: &Config) -> Box { EmitMode::Stdout | EmitMode::Coverage => { Box::new(emitter::StdoutEmitter::new(config.verbose())) } - EmitMode::Json => Box::new(emitter::JsonEmitter::default()), - EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()), - EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()), + EmitMode::Json => >::default(), + EmitMode::ModifiedLines => >::default(), + EmitMode::Checkstyle => >::default(), EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())), } } diff --git a/src/macros.rs b/src/macros.rs index 09ec1da2bd0..7ef20fc8827 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -436,7 +436,7 @@ pub(crate) fn rewrite_macro_def( shape }; - if parsed_def.branches.len() == 0 { + if parsed_def.branches.is_empty() { let lo = context.snippet_provider.span_before(span, "{"); result += " "; result += &rewrite_empty_macro_def_body(context, span.with_lo(lo), shape)?; diff --git a/src/matches.rs b/src/matches.rs index f1b9a8fa9e6..995a60db9cd 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -194,7 +194,7 @@ fn rewrite_match_arms( context.snippet_provider, arms.iter() .zip(is_last_iter) - .zip(beginning_verts.into_iter()) + .zip(beginning_verts) .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)), "}", "|", diff --git a/src/overflow.rs b/src/overflow.rs index f085221af79..75c18dd8404 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -442,8 +442,8 @@ impl<'a> Context<'a> { }; if let Some(rewrite) = rewrite { - // splitn(2, *).next().unwrap() is always safe. - let rewrite_first_line = Some(rewrite.splitn(2, '\n').next().unwrap().to_owned()); + // split(*).next().unwrap() never panics. + let rewrite_first_line = Some(rewrite.split('\n').next().unwrap().to_owned()); last_list_item.item = rewrite_first_line; Some(rewrite) } else { @@ -735,7 +735,7 @@ fn last_item_shape( shape: Shape, args_max_width: usize, ) -> Option { - if items.len() == 1 && !lists.get(0)?.is_nested_call() { + if items.len() == 1 && !lists.first()?.is_nested_call() { return Some(shape); } let offset = items @@ -786,7 +786,7 @@ pub(crate) fn maybe_get_args_offset( config: &Config, ) -> Option<(bool, usize)> { if let Some(&(_, num_args_before)) = args - .get(0)? + .first()? .special_cases(config) .find(|&&(s, _)| s == callee_str) { diff --git a/src/parse/macros/lazy_static.rs b/src/parse/macros/lazy_static.rs index 8b1dc6694d6..28b39ccfa03 100644 --- a/src/parse/macros/lazy_static.rs +++ b/src/parse/macros/lazy_static.rs @@ -6,10 +6,12 @@ use rustc_span::symbol::{self, kw}; use crate::rewrite::RewriteContext; +type LazyStaticItem = (ast::Visibility, symbol::Ident, P, P); + pub(crate) fn parse_lazy_static( context: &RewriteContext<'_>, ts: TokenStream, -) -> Option, P)>> { +) -> Option> { let mut result = vec![]; let mut parser = super::build_parser(context, ts); macro_rules! parse_or { diff --git a/src/parse/macros/mod.rs b/src/parse/macros/mod.rs index 2dd2622174f..3f51720e6f9 100644 --- a/src/parse/macros/mod.rs +++ b/src/parse/macros/mod.rs @@ -14,7 +14,7 @@ pub(crate) mod asm; pub(crate) mod cfg_if; pub(crate) mod lazy_static; -fn build_stream_parser<'a>(sess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> { +fn build_stream_parser(sess: &ParseSess, tokens: TokenStream) -> Parser<'_> { stream_to_parser(sess, tokens, MACRO_ARGUMENTS) } @@ -47,17 +47,17 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { parse_macro_arg!( Expr, |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(), - |x: ptr::P| Some(x) + Some ); parse_macro_arg!( Ty, |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(), - |x: ptr::P| Some(x) + Some ); parse_macro_arg!( Pat, |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat_no_top_alt(None, None), - |x: ptr::P| Some(x) + Some ); // `parse_item` returns `Option>`. parse_macro_arg!( diff --git a/src/shape.rs b/src/shape.rs index 4376fd12b52..f7a501a6415 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -65,15 +65,15 @@ impl Indent { self.block_indent + self.alignment } - pub(crate) fn to_string(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string(self, config: &Config) -> Cow<'static, str> { self.to_string_inner(config, 1) } - pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string_with_newline(self, config: &Config) -> Cow<'static, str> { self.to_string_inner(config, 0) } - fn to_string_inner(&self, config: &Config, offset: usize) -> Cow<'static, str> { + fn to_string_inner(self, config: &Config, offset: usize) -> Cow<'static, str> { let (num_tabs, num_spaces) = if config.hard_tabs() { (self.block_indent / config.tab_spaces(), self.alignment) } else { @@ -272,7 +272,7 @@ impl Shape { Shape { width, ..*self } } - pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string_with_newline(self, config: &Config) -> Cow<'static, str> { let mut offset_indent = self.indent; offset_indent.alignment = self.offset; offset_indent.to_string_inner(config, 0) diff --git a/src/string.rs b/src/string.rs index 1d8901ce61f..c4b8f95310e 100644 --- a/src/string.rs +++ b/src/string.rs @@ -61,9 +61,9 @@ impl<'a> StringFormat<'a> { } } -pub(crate) fn rewrite_string<'a>( +pub(crate) fn rewrite_string( orig: &str, - fmt: &StringFormat<'a>, + fmt: &StringFormat<'_>, newline_max_chars: usize, ) -> Option { let max_width_with_indent = fmt.max_width_with_indent()?; @@ -315,18 +315,13 @@ fn break_string(max_width: usize, trim_end: bool, line_end: &str, input: &[&str] // Found a whitespace and what is on its left side is big enough. Some(index) if index >= MIN_STRING => break_at(index), // No whitespace found, try looking for a punctuation instead - _ => match (0..max_width_index_in_input) - .rev() - .skip_while(|pos| !is_valid_linebreak(input, *pos)) - .next() - { + _ => match (0..max_width_index_in_input).rfind(|&pos| is_valid_linebreak(input, pos)) { // Found a punctuation and what is on its left side is big enough. Some(index) if index >= MIN_STRING => break_at(index), // Either no boundary character was found to the left of `input[max_chars]`, or the line // got too small. We try searching for a boundary character to the right. _ => match (max_width_index_in_input..input.len()) - .skip_while(|pos| !is_valid_linebreak(input, *pos)) - .next() + .find(|&pos| is_valid_linebreak(input, pos)) { // A boundary was found after the line limit Some(index) => break_at(index), diff --git a/src/test/configuration_snippet.rs b/src/test/configuration_snippet.rs index 80b61c88a00..33aaf167f16 100644 --- a/src/test/configuration_snippet.rs +++ b/src/test/configuration_snippet.rs @@ -138,13 +138,7 @@ impl ConfigCodeBlock { /// True if the code block starts with #![rustfmt::skip] fn fmt_skip(&self) -> bool { - self.code_block - .as_ref() - .unwrap() - .lines() - .nth(0) - .unwrap_or("") - == "#![rustfmt::skip]" + self.code_block.as_ref().unwrap().lines().next() == Some("#![rustfmt::skip]") } fn has_parsing_errors(&self, session: &Session<'_, T>) -> bool { diff --git a/src/utils.rs b/src/utils.rs index 642b6603b1e..241e3b45d1e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -198,13 +198,13 @@ pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool { /// The width of the first line in s. #[inline] pub(crate) fn first_line_width(s: &str) -> usize { - unicode_str_width(s.splitn(2, '\n').next().unwrap_or("")) + unicode_str_width(s.split('\n').next().unwrap_or("")) } /// The width of the last line in s. #[inline] pub(crate) fn last_line_width(s: &str) -> usize { - unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or("")) + unicode_str_width(s.rsplit('\n').next().unwrap_or("")) } /// The total used width of the last line. diff --git a/src/visitor.rs b/src/visitor.rs index 0a4947c8bb4..297bc5325e2 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -273,7 +273,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let comment_snippet = self.snippet(span); let align_to_right = if unindent_comment && contains_comment(comment_snippet) { - let first_lines = comment_snippet.splitn(2, '/').next().unwrap_or(""); + let first_lines = comment_snippet.split('/').next().unwrap_or(""); last_line_width(first_lines) > last_line_width(comment_snippet) } else { false