diff --git a/src/attr.rs b/src/attr.rs index e2104617fdc..9cc515bd987 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,7 +260,7 @@ impl Rewrite for ast::MetaItemInner { fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) { // Look at before and after comment and see if there are any empty lines. let comment_begin = comment.find('/'); - let len = comment_begin.unwrap_or_else(|| comment.len()); + let len = comment_begin.unwrap_or(comment.len()); let mlb = count_newlines(&comment[..len]) > 1; let mla = if comment_begin.is_none() { mlb diff --git a/src/bin/main.rs b/src/bin/main.rs index b72bad873d9..ed37aebbf65 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -746,8 +746,7 @@ impl CliOptions for GetOptsOptions { fn version(&self) -> Option { self.inline_config .get("version") - .map(|version| Version::from_str(version).ok()) - .flatten() + .and_then(|version| Version::from_str(version).ok()) } } @@ -818,7 +817,7 @@ mod test { options.inline_config = HashMap::from([("version".to_owned(), "Two".to_owned())]); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); + assert!(config.overflow_delimited_expr()); } #[nightly_only_test] @@ -828,7 +827,7 @@ mod test { let config_file = Some(Path::new("tests/config/style-edition/just-version")); let config = get_config(config_file, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); + assert!(config.overflow_delimited_expr()); } #[nightly_only_test] @@ -873,7 +872,7 @@ mod test { ]); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); + assert!(config.overflow_delimited_expr()); } #[nightly_only_test] @@ -939,7 +938,7 @@ mod test { options.style_edition = Some(StyleEdition::Edition2024); let config = get_config(None, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), true); + assert!(config.overflow_delimited_expr()); } #[nightly_only_test] @@ -949,7 +948,7 @@ mod test { let config_file = Some(Path::new("tests/config/style-edition/overrides")); let config = get_config(config_file, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), false); + assert!(!config.overflow_delimited_expr()); } #[nightly_only_test] @@ -961,6 +960,6 @@ mod test { HashMap::from([("overflow_delimited_expr".to_owned(), "false".to_owned())]); let config = get_config(config_file, Some(options)); assert_eq!(config.style_edition(), StyleEdition::Edition2024); - assert_eq!(config.overflow_delimited_expr(), false); + assert!(!config.overflow_delimited_expr()); } } diff --git a/src/chains.rs b/src/chains.rs index 50a129b695f..be0beea79cd 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -213,7 +213,7 @@ impl ChainItemKind { fn is_tup_field_access(expr: &ast::Expr) -> bool { match expr.kind { ast::ExprKind::Field(_, ref field) => { - field.name.as_str().chars().all(|c| c.is_digit(10)) + field.name.as_str().chars().all(|c| c.is_ascii_digit()) } _ => false, } @@ -288,7 +288,7 @@ impl Rewrite for ChainItem { ChainItemKind::Parent { ref expr, parens: true, - } => crate::expr::rewrite_paren(context, &expr, shape, expr.span)?, + } => crate::expr::rewrite_paren(context, expr, shape, expr.span)?, ChainItemKind::Parent { ref expr, parens: false, @@ -353,7 +353,7 @@ impl ChainItem { format!("::<{}>", type_list.join(", ")) }; let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str); - rewrite_call(context, &callee_str, &args, span, shape) + rewrite_call(context, &callee_str, args, span, shape) } } @@ -843,7 +843,7 @@ impl<'a> ChainFormatterBlock<'a> { } } -impl<'a> ChainFormatter for ChainFormatterBlock<'a> { +impl ChainFormatter for ChainFormatterBlock<'_> { fn format_root( &mut self, parent: &ChainItem, @@ -931,7 +931,7 @@ impl<'a> ChainFormatterVisual<'a> { } } -impl<'a> ChainFormatter for ChainFormatterVisual<'a> { +impl ChainFormatter for ChainFormatterVisual<'_> { fn format_root( &mut self, parent: &ChainItem, diff --git a/src/closures.rs b/src/closures.rs index 296b7407e40..34353fe39b8 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -124,9 +124,10 @@ fn needs_block( prefix: &str, context: &RewriteContext<'_>, ) -> bool { - let has_attributes = block.stmts.first().map_or(false, |first_stmt| { - !get_attrs_from_stmt(first_stmt).is_empty() - }); + let has_attributes = block + .stmts + .first() + .is_some_and(|first_stmt| !get_attrs_from_stmt(first_stmt).is_empty()); is_unsafe_block(block) || block.stmts.len() > 1 @@ -434,9 +435,8 @@ pub(crate) fn rewrite_last_closure( // When overflowing the closure which consists of a single control flow expression, // force to use block if its condition uses multi line. - let is_multi_lined_cond = rewrite_cond(context, body, body_shape).map_or(false, |cond| { - cond.contains('\n') || cond.len() > body_shape.width - }); + let is_multi_lined_cond = rewrite_cond(context, body, body_shape) + .is_some_and(|cond| cond.contains('\n') || cond.len() > body_shape.width); if is_multi_lined_cond { return rewrite_closure_with_block(body, &prefix, context, body_shape); } diff --git a/src/comment.rs b/src/comment.rs index 709031dda44..d08b8842076 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -990,11 +990,11 @@ 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. @@ -1521,7 +1521,7 @@ impl<'a> LineClasses<'a> { } } -impl<'a> Iterator for LineClasses<'a> { +impl Iterator for LineClasses<'_> { type Item = (FullCodeCharKind, String); fn next(&mut self) -> Option { @@ -1797,7 +1797,7 @@ impl<'a> CommentReducer<'a> { } } -impl<'a> Iterator for CommentReducer<'a> { +impl Iterator for CommentReducer<'_> { type Item = char; fn next(&mut self) -> Option { @@ -2007,10 +2007,10 @@ mod test { #[test] fn test_contains_comment() { - assert_eq!(contains_comment("abc"), false); - assert_eq!(contains_comment("abc // qsdf"), true); - assert_eq!(contains_comment("abc /* kqsdf"), true); - assert_eq!(contains_comment("abc \" /* */\" qsdf"), false); + assert!(!contains_comment("abc")); + assert!(contains_comment("abc // qsdf")); + assert!(contains_comment("abc /* kqsdf")); + assert!(!contains_comment("abc \" /* */\" qsdf")); } #[test] diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index c53ec6371e9..823e6747efc 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/mod.rs b/src/config/mod.rs index 742b99c15ef..64943ba6bce 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -327,7 +327,7 @@ impl Config { style_edition: Option, version: Option, ) -> Result { - let mut file = File::open(&file_path)?; + let mut file = File::open(file_path)?; let mut toml = String::new(); file.read_to_string(&mut toml)?; Config::from_toml_for_style_edition(&toml, file_path, edition, style_edition, version) @@ -715,8 +715,8 @@ mod test { fn test_was_set() { let config = Config::from_toml("hard_tabs = true", Path::new("./rustfmt.toml")).unwrap(); - assert_eq!(config.was_set().hard_tabs(), true); - assert_eq!(config.was_set().verbose(), false); + assert!(config.was_set().hard_tabs()); + assert!(!config.was_set().verbose()); } const PRINT_DOCS_STABLE_OPTION: &str = "stable_option Default: false"; @@ -732,9 +732,9 @@ mod test { Config::print_docs(&mut output, false); let s = str::from_utf8(&output).unwrap(); - assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); - assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false); - assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); + assert!(s.contains(PRINT_DOCS_STABLE_OPTION)); + assert!(!s.contains(PRINT_DOCS_UNSTABLE_OPTION)); + assert!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION)); } #[test] @@ -745,9 +745,9 @@ mod test { Config::print_docs(&mut output, true); let s = str::from_utf8(&output).unwrap(); - assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); - assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true); - assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); + assert!(s.contains(PRINT_DOCS_STABLE_OPTION)); + assert!(s.contains(PRINT_DOCS_UNSTABLE_OPTION)); + assert!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION)); } #[test] @@ -966,9 +966,9 @@ make_backup = false config.set().unstable_features(true); // When we don't set the config from toml or command line options it // doesn't get marked as set by the user. - assert_eq!(config.was_set().unstable_features(), false); + assert!(!config.was_set().unstable_features()); config.set().unstable_features(true); - assert_eq!(config.unstable_features(), true); + assert!(config.unstable_features()); } #[nightly_only_test] @@ -976,22 +976,22 @@ make_backup = false fn test_unstable_from_toml() { let config = Config::from_toml("unstable_features = true", Path::new("./rustfmt.toml")).unwrap(); - assert_eq!(config.was_set().unstable_features(), true); - assert_eq!(config.unstable_features(), true); + assert!(config.was_set().unstable_features()); + assert!(config.unstable_features()); } #[test] fn test_set_cli() { let mut config = Config::default(); - assert_eq!(config.was_set().edition(), false); - assert_eq!(config.was_set_cli().edition(), false); + assert!(!config.was_set().edition()); + assert!(!config.was_set_cli().edition()); config.set().edition(Edition::Edition2021); - assert_eq!(config.was_set().edition(), false); - assert_eq!(config.was_set_cli().edition(), false); + assert!(!config.was_set().edition()); + assert!(!config.was_set_cli().edition()); config.set_cli().edition(Edition::Edition2021); - assert_eq!(config.was_set().edition(), false); - assert_eq!(config.was_set_cli().edition(), true); - assert_eq!(config.was_set_cli().emit_mode(), false); + assert!(!config.was_set().edition()); + assert!(config.was_set_cli().edition()); + assert!(!config.was_set_cli().emit_mode()); } #[cfg(test)] @@ -1365,7 +1365,7 @@ make_backup = false let versions = vec!["0.0.0", "0.0.1", "0.1.0"]; for version in versions { - let toml = format!("required_version=\"{}\"", version.to_string()); + let toml = format!("required_version=\"{}\"", version); let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap(); assert!(!config.version_meets_requirement()); @@ -1389,8 +1389,7 @@ make_backup = false for minor in current_version.minor..0 { let toml = format!( "required_version=\"^{}.{}.0\"", - current_version.major.to_string(), - minor.to_string() + current_version.major, minor ); let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap(); @@ -1434,7 +1433,7 @@ make_backup = false #[nightly_only_test] #[test] fn test_required_version_exact_boundary() { - let toml = format!("required_version=\"{}\"", get_current_version().to_string()); + let toml = format!("required_version=\"{}\"", get_current_version()); let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap(); assert!(config.version_meets_requirement()); @@ -1443,10 +1442,7 @@ make_backup = false #[nightly_only_test] #[test] fn test_required_version_pre_release() { - let toml = format!( - "required_version=\"^{}-alpha\"", - get_current_version().to_string() - ); + let toml = format!("required_version=\"^{}-alpha\"", get_current_version()); let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap(); assert!(config.version_meets_requirement()); @@ -1455,10 +1451,7 @@ make_backup = false #[nightly_only_test] #[test] fn test_required_version_with_build_metadata() { - let toml = format!( - "required_version=\"{}+build.1\"", - get_current_version().to_string() - ); + let toml = format!("required_version=\"{}+build.1\"", get_current_version()); let config = Config::from_toml(&toml, Path::new("./rustfmt.toml")).unwrap(); diff --git a/src/config/options.rs b/src/config/options.rs index 3f86999c30b..cb39b1a13f2 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -170,9 +170,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, @@ -325,12 +327,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)] pub struct IgnoreList { @@ -440,11 +436,13 @@ pub trait CliOptions { } /// The edition of the syntax and semantics of code (RFC 2052). +#[derive(Default)] #[config_type] pub enum Edition { #[value = "2015"] #[doc_hint = "2015"] /// Edition 2015. + #[default] Edition2015, #[value = "2018"] #[doc_hint = "2018"] @@ -460,12 +458,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/checkstyle.rs b/src/emitter/checkstyle.rs index c320c16bd1d..c01a58371bb 100644 --- a/src/emitter/checkstyle.rs +++ b/src/emitter/checkstyle.rs @@ -95,7 +95,7 @@ mod tests { let lib_original = ["fn greet() {", "println!(\"Greetings!\");", "}"]; let lib_formatted = ["fn greet() {", " println!(\"Greetings!\");", "}"]; let mut writer = Vec::new(); - let mut emitter = CheckstyleEmitter::default(); + let mut emitter = CheckstyleEmitter; let _ = emitter.emit_header(&mut writer); let _ = emitter .emit_formatted_file( diff --git a/src/emitter/checkstyle/xml.rs b/src/emitter/checkstyle/xml.rs index d1d9af70857..10539df6921 100644 --- a/src/emitter/checkstyle/xml.rs +++ b/src/emitter/checkstyle/xml.rs @@ -4,7 +4,7 @@ use std::fmt::{self, Display}; /// This is needed for checkstyle output. pub(super) struct XmlEscaped<'a>(pub(super) &'a str); -impl<'a> Display for XmlEscaped<'a> { +impl Display for XmlEscaped<'_> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { for char in self.0.chars() { match char { diff --git a/src/emitter/diff.rs b/src/emitter/diff.rs index 4e48c59ea29..584b03e6ea5 100644 --- a/src/emitter/diff.rs +++ b/src/emitter/diff.rs @@ -68,7 +68,7 @@ mod tests { }, ) .unwrap(); - assert_eq!(result.has_diff, false); + assert!(!result.has_diff); assert_eq!(writer.len(), 0); } diff --git a/src/emitter/json.rs b/src/emitter/json.rs index 8c84ff72d04..96e51429769 100644 --- a/src/emitter/json.rs +++ b/src/emitter/json.rs @@ -137,7 +137,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); @@ -182,7 +182,7 @@ mod tests { ], }; - let _ = emitter + emitter .add_misformatted_file(&FileName::Real(PathBuf::from(file)), vec![mismatch]) .unwrap(); @@ -206,7 +206,7 @@ mod tests { ) .unwrap(); let _ = emitter.emit_footer(&mut writer); - assert_eq!(result.has_diff, false); + assert!(!result.has_diff); assert_eq!(&writer[..], "[]\n".as_bytes()); } @@ -279,7 +279,7 @@ mod tests { ], }]) .unwrap(); - assert_eq!(result.has_diff, true); + assert!(result.has_diff); assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes()); } diff --git a/src/expr.rs b/src/expr.rs index 0c5752380f6..a3fcde32a3f 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -90,7 +90,7 @@ pub(crate) fn format_expr( ) -> RewriteResult { skip_out_of_file_lines_range_err!(context, expr.span); - if contains_skip(&*expr.attrs) { + if contains_skip(&expr.attrs) { return Ok(context.snippet(expr.span()).to_owned()); } let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) { @@ -112,12 +112,10 @@ pub(crate) fn format_expr( ast::ExprKind::Lit(token_lit) => { if let Ok(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) { Ok(expr_rw) + } else if let LitKind::StrRaw(_) = token_lit.kind { + Ok(context.snippet(expr.span).trim().into()) } else { - if let LitKind::StrRaw(_) = token_lit.kind { - Ok(context.snippet(expr.span).trim().into()) - } else { - Err(RewriteError::Unknown) - } + Err(RewriteError::Unknown) } } ast::ExprKind::Call(ref callee, ref args) => { @@ -302,9 +300,7 @@ pub(crate) fn format_expr( shape, SeparatorPlace::Front, ), - ast::ExprKind::Index(ref expr, ref index, _) => { - rewrite_index(&**expr, &**index, context, shape) - } + ast::ExprKind::Index(ref expr, ref index, _) => rewrite_index(expr, index, context, shape), ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair( &**expr, &*repeats.value, @@ -358,8 +354,8 @@ pub(crate) fn format_expr( default_sp_delim(Some(lhs), Some(rhs)) }; rewrite_pair( - &*lhs, - &*rhs, + lhs, + rhs, PairParts::infix(&sp_delim), context, shape, @@ -372,7 +368,7 @@ pub(crate) fn format_expr( } else { default_sp_delim(None, Some(rhs)) }; - rewrite_unary_prefix(context, &sp_delim, &*rhs, shape) + rewrite_unary_prefix(context, &sp_delim, rhs, shape) } (Some(lhs), None) => { let sp_delim = if context.config.spaces_around_ranges() { @@ -380,7 +376,7 @@ pub(crate) fn format_expr( } else { default_sp_delim(Some(lhs), None) }; - rewrite_unary_suffix(context, &sp_delim, &*lhs, shape) + rewrite_unary_suffix(context, &sp_delim, lhs, shape) } (None, None) => Ok(delim.to_owned()), } @@ -502,7 +498,7 @@ fn rewrite_empty_block( } let label_str = rewrite_label(context, label); - if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) { + if attrs.is_some_and(|a| !inner_attributes(a).is_empty()) { return None; } @@ -909,7 +905,7 @@ fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool { leading_whitespaces > start_column } -impl<'a> ControlFlow<'a> { +impl ControlFlow<'_> { fn rewrite_pat_expr( &self, context: &RewriteContext<'_>, @@ -936,7 +932,7 @@ impl<'a> ControlFlow<'a> { let comments_span = mk_sp(comments_lo, expr.span.lo()); return rewrite_assign_rhs_with_comments( context, - &format!("{}{}{}", matcher, pat_string, self.connector), + format!("{}{}{}", matcher, pat_string, self.connector), expr, cond_shape, &RhsAssignKind::Expr(&expr.kind, expr.span), @@ -1131,7 +1127,7 @@ pub(crate) fn rewrite_else_kw_with_comments( ) } -impl<'a> Rewrite for ControlFlow<'a> { +impl Rewrite for ControlFlow<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -1249,7 +1245,7 @@ pub(crate) fn is_simple_block( block.stmts.len() == 1 && stmt_is_expr(&block.stmts[0]) && !block_contains_comment(context, block) - && attrs.map_or(true, |a| a.is_empty()) + && attrs.is_none_or(|a| a.is_empty()) } /// Checks whether a block contains at most one statement or expression, and no @@ -1261,7 +1257,7 @@ pub(crate) fn is_simple_block_stmt( ) -> bool { block.stmts.len() <= 1 && !block_contains_comment(context, block) - && attrs.map_or(true, |a| a.is_empty()) + && attrs.is_none_or(|a| a.is_empty()) } fn block_has_statements(block: &ast::Block) -> bool { @@ -1280,7 +1276,7 @@ pub(crate) fn is_empty_block( ) -> bool { !block_has_statements(block) && !block_contains_comment(context, block) - && attrs.map_or(true, |a| inner_attributes(a).is_empty()) + && attrs.is_none_or(|a| inner_attributes(a).is_empty()) } pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool { @@ -1485,7 +1481,7 @@ pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool { | ast::ExprKind::Unary(_, ref expr) => is_simple_expr(expr), ast::ExprKind::Index(ref lhs, ref rhs, _) => is_simple_expr(lhs) && is_simple_expr(rhs), ast::ExprKind::Repeat(ref lhs, ref rhs) => { - is_simple_expr(lhs) && is_simple_expr(&*rhs.value) + is_simple_expr(lhs) && is_simple_expr(&rhs.value) } _ => false, } @@ -1719,11 +1715,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, @@ -1767,14 +1763,14 @@ fn rewrite_struct_lit<'a>( ) .unknown_error()? } else { - let field_iter = fields.iter().map(StructLitField::Regular).chain( - match struct_rest { - ast::StructRest::Base(expr) => Some(StructLitField::Base(&**expr)), + 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(), @@ -2095,7 +2091,7 @@ pub(crate) enum RhsAssignKind<'ast> { Ty, } -impl<'ast> RhsAssignKind<'ast> { +impl RhsAssignKind<'_> { // TODO(calebcartwright) // Preemptive addition for handling RHS with chains, not yet utilized. // It may make more sense to construct the chain first and then check @@ -2279,7 +2275,7 @@ fn choose_rhs( match (orig_rhs, new_rhs) { (Ok(ref orig_rhs), Ok(ref new_rhs)) - if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) => + if !filtered_str_fits(new_rhs, context.config.max_width(), new_shape) => { Ok(format!("{before_space_str}{orig_rhs}")) } @@ -2412,22 +2408,22 @@ mod test { #[test] fn test_last_line_offsetted() { let lines = "one\n two"; - assert_eq!(last_line_offsetted(2, lines), true); - assert_eq!(last_line_offsetted(4, lines), false); - assert_eq!(last_line_offsetted(6, lines), false); + assert!(last_line_offsetted(2, lines)); + assert!(!last_line_offsetted(4, lines)); + assert!(!last_line_offsetted(6, lines)); let lines = "one two"; - assert_eq!(last_line_offsetted(2, lines), false); - assert_eq!(last_line_offsetted(0, lines), false); + assert!(!last_line_offsetted(2, lines)); + assert!(!last_line_offsetted(0, lines)); let lines = "\ntwo"; - assert_eq!(last_line_offsetted(2, lines), false); - assert_eq!(last_line_offsetted(0, lines), false); + assert!(!last_line_offsetted(2, lines)); + assert!(!last_line_offsetted(0, lines)); let lines = "one\n two three"; - assert_eq!(last_line_offsetted(2, lines), true); + assert!(last_line_offsetted(2, lines)); let lines = "one\n two three"; - assert_eq!(last_line_offsetted(2, lines), false); + assert!(!last_line_offsetted(2, lines)); } #[test] diff --git a/src/format_report_formatter.rs b/src/format_report_formatter.rs index 08889c712a5..83ac86ec9b0 100644 --- a/src/format_report_formatter.rs +++ b/src/format_report_formatter.rs @@ -44,7 +44,7 @@ pub struct FormatReportFormatter<'a> { enable_colors: bool, } -impl<'a> Display for FormatReportFormatter<'a> { +impl Display for FormatReportFormatter<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let errors_by_file = &self.report.internal.borrow().0; @@ -65,7 +65,7 @@ impl<'a> Display for FormatReportFormatter<'a> { let message_suffix = error.msg_suffix(); if !message_suffix.is_empty() { - message = message.footer(Level::Note.title(&message_suffix)); + message = message.footer(Level::Note.title(message_suffix)); } let origin = format!("{}:{}", file, error.line); diff --git a/src/formatting.rs b/src/formatting.rs index 1e1e329f624..b9554cbb62f 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -48,9 +48,8 @@ impl<'b, T: Write + 'b> Session<'b, T> { let config = &self.config.clone(); let format_result = format_project(input, config, self, is_macro_def); - format_result.map(|report| { + format_result.inspect(|report| { self.errors.add(&report.internal.borrow().1); - report }) }) } diff --git a/src/imports.rs b/src/imports.rs index cfc2f3bda19..e01814d8b72 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -33,7 +33,7 @@ pub(crate) fn path_to_imported_ident(path: &ast::Path) -> symbol::Ident { path.segments.last().unwrap().ident } -impl<'a> FmtVisitor<'a> { +impl FmtVisitor<'_> { pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) { let span = item.span(); let shape = self.shape(); @@ -637,7 +637,7 @@ impl UseTree { } fn has_comment(&self) -> bool { - self.list_item.as_ref().map_or(false, ListItem::has_comment) + self.list_item.as_ref().is_some_and(ListItem::has_comment) } fn contains_comment(&self) -> bool { @@ -1034,9 +1034,10 @@ fn rewrite_nested_use_tree( } } let has_nested_list = use_tree_list.iter().any(|use_segment| { - use_segment.path.last().map_or(false, |last_segment| { - matches!(last_segment.kind, UseSegmentKind::List(..)) - }) + use_segment + .path + .last() + .is_some_and(|last_segment| matches!(last_segment.kind, UseSegmentKind::List(..))) }); let remaining_width = if has_nested_list { @@ -1164,7 +1165,7 @@ mod test { style_edition: StyleEdition, } - impl<'a> Parser<'a> { + impl Parser<'_> { fn bump(&mut self) { self.input.next().unwrap(); } diff --git a/src/items.rs b/src/items.rs index 901ad44edab..0f430a198b1 100644 --- a/src/items.rs +++ b/src/items.rs @@ -236,7 +236,7 @@ fn same_line_else_kw_and_brace( .last() .expect("initializer expression is multi-lined") .strip_prefix(indent.as_ref()) - .map_or(false, |l| !l.starts_with(char::is_whitespace)) + .is_some_and(|l| !l.starts_with(char::is_whitespace)) } fn allow_single_line_let_else_block(result: &str, block: &ast::Block) -> bool { @@ -315,7 +315,7 @@ impl<'a> FnSig<'a> { constness: method_sig.header.constness, defaultness: ast::Defaultness::Final, ext: method_sig.header.ext, - decl: &*method_sig.decl, + decl: &method_sig.decl, generics, visibility, } @@ -349,7 +349,7 @@ impl<'a> FnSig<'a> { fn to_str(&self, context: &RewriteContext<'_>) -> String { let mut result = String::with_capacity(128); // Vis defaultness constness unsafety abi. - result.push_str(&*format_visibility(context, self.visibility)); + result.push_str(&format_visibility(context, self.visibility)); result.push_str(format_defaultness(self.defaultness)); result.push_str(format_constness(self.constness)); self.coroutine_kind @@ -363,7 +363,7 @@ impl<'a> FnSig<'a> { } } -impl<'a> FmtVisitor<'a> { +impl FmtVisitor<'_> { fn format_item(&mut self, item: &Item<'_>) { self.buffer.push_str(format_safety(item.safety)); self.buffer.push_str(&item.abi); @@ -480,7 +480,7 @@ impl<'a> FmtVisitor<'a> { block: &ast::Block, inner_attrs: Option<&[ast::Attribute]>, ) -> Option { - if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) { + if fn_str.contains('\n') || inner_attrs.is_some_and(|a| !a.is_empty()) { return None; } @@ -769,7 +769,7 @@ impl<'a> FmtVisitor<'a> { // different impl items. if prev_kind .as_ref() - .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind)) + .is_some_and(|prev_kind| need_empty_line(prev_kind, &item.kind)) { self.push_str("\n"); } @@ -1040,7 +1040,7 @@ fn format_impl_ref_and_type( IndentStyle::Visual => new_line_offset + trait_ref_overhead, IndentStyle::Block => new_line_offset, }; - result.push_str(&*self_ty.rewrite_result(context, Shape::legacy(budget, type_offset))?); + result.push_str(&self_ty.rewrite_result(context, Shape::legacy(budget, type_offset))?); Ok(result) } @@ -1239,7 +1239,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) @@ -1326,7 +1326,7 @@ pub(crate) struct TraitAliasBounds<'a> { generics: &'a ast::Generics, } -impl<'a> Rewrite for TraitAliasBounds<'a> { +impl Rewrite for TraitAliasBounds<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -1688,11 +1688,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, ) -> RewriteResult { use ItemVisitorKind::*; @@ -1864,7 +1864,7 @@ fn rewrite_ty( } else { shape }; - rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape)? + rewrite_assign_rhs(context, lhs, ty, &RhsAssignKind::Ty, shape)? } else { result }; @@ -2158,7 +2158,7 @@ struct OpaqueType<'a> { bounds: &'a ast::GenericBounds, } -impl<'a> Rewrite for OpaqueType<'a> { +impl Rewrite for OpaqueType<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { let shape = shape.offset_left_opt(5)?; // `impl ` self.bounds @@ -2290,7 +2290,7 @@ impl Rewrite for ast::Param { !has_multiple_attr_lines && !has_doc_comments, )?; - if !is_empty_infer(&*self.ty, self.pat.span) { + if !is_empty_infer(&self.ty, self.pat.span) { let (before_comment, after_comment) = get_missing_param_comments(context, self.pat.span, self.ty.span, shape); result.push_str(&before_comment); @@ -2478,7 +2478,7 @@ fn rewrite_fn_base( let generics_str = rewrite_generics( context, rewrite_ident(context, ident), - &fn_sig.generics, + fn_sig.generics, shape, )?; result.push_str(&generics_str); @@ -2486,7 +2486,7 @@ fn rewrite_fn_base( let snuggle_angle_bracket = generics_str .lines() .last() - .map_or(false, |l| l.trim_start().len() == 1); + .is_some_and(|l| l.trim_start().len() == 1); // Note that the width and indent don't really matter, we'll re-layout the // return type later anyway. @@ -2572,7 +2572,7 @@ fn rewrite_fn_base( params_last_line_contains_comment = param_str .lines() .last() - .map_or(false, |last_line| last_line.contains("//")); + .is_some_and(|last_line| last_line.contains("//")); if context.config.style_edition() >= StyleEdition::Edition2027 { if closing_paren_overflow_max_width { @@ -2681,10 +2681,10 @@ fn rewrite_fn_base( // Try to preserve the layout of the original snippet. let original_starts_with_newline = snippet .find(|c| c != ' ') - .map_or(false, |i| starts_with_newline(&snippet[i..])); + .is_some_and(|i| starts_with_newline(&snippet[i..])); let original_ends_with_newline = snippet .rfind(|c| c != ' ') - .map_or(false, |i| snippet[i..].ends_with('\n')); + .is_some_and(|i| snippet[i..].ends_with('\n')); let snippet = snippet.trim(); if !snippet.is_empty() { result.push(if original_starts_with_newline { @@ -3388,7 +3388,7 @@ fn format_generics( // add missing comments let missed_line_comments = missed_comments .filter(|missed_comments| !missed_comments.is_empty()) - .map_or(false, |missed_comments| { + .is_some_and(|missed_comments| { let is_block = is_last_comment_block(&missed_comments); let sep = if is_block { " " } else { "\n" }; result.push_str(sep); @@ -3557,7 +3557,7 @@ pub(crate) fn rewrite_mod( attrs_shape: Shape, ) -> RewriteResult { let mut result = String::with_capacity(32); - result.push_str(&*format_visibility(context, &item.vis)); + result.push_str(&format_visibility(context, &item.vis)); result.push_str("mod "); result.push_str(rewrite_ident(context, item.ident)); result.push(';'); diff --git a/src/lib.rs b/src/lib.rs index 898689933e6..a6d3294232b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -387,7 +387,7 @@ fn format_code_block( let block_len = formatted .snippet .rfind('}') - .unwrap_or_else(|| formatted.snippet.len()); + .unwrap_or(formatted.snippet.len()); // It's possible that `block_len < FN_MAIN_PREFIX.len()`. This can happen if the code block was // formatted into the empty string, leading to the enclosing `fn main() {\n}` being formatted @@ -517,9 +517,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()) - } + EmitMode::Files if config.make_backup() => Box::new(emitter::FilesWithBackupEmitter), EmitMode::Files => Box::new(emitter::FilesEmitter::new( config.print_misformatted_file_names(), )), @@ -527,8 +525,8 @@ pub(crate) fn create_emitter<'a>(config: &Config) -> Box { 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::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter), + EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter), EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())), } } diff --git a/src/lists.rs b/src/lists.rs index 9d811e5d9b5..a293efa6beb 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -136,7 +136,7 @@ impl ListItem { ListItem { pre_comment: None, pre_comment_style: ListItemCommentStyle::None, - item: item, + item, post_comment: None, new_lines: false, } @@ -149,32 +149,23 @@ impl ListItem { pub(crate) fn is_different_group(&self) -> bool { self.inner_as_ref().contains('\n') || self.pre_comment.is_some() - || self - .post_comment - .as_ref() - .map_or(false, |s| s.contains('\n')) + || self.post_comment.as_ref().is_some_and(|s| s.contains('\n')) } pub(crate) fn is_multiline(&self) -> bool { self.inner_as_ref().contains('\n') - || self - .pre_comment - .as_ref() - .map_or(false, |s| s.contains('\n')) - || self - .post_comment - .as_ref() - .map_or(false, |s| s.contains('\n')) + || self.pre_comment.as_ref().is_some_and(|s| s.contains('\n')) + || self.post_comment.as_ref().is_some_and(|s| s.contains('\n')) } pub(crate) fn has_single_line_comment(&self) -> bool { self.pre_comment .as_ref() - .map_or(false, |comment| comment.trim_start().starts_with("//")) + .is_some_and(|comment| comment.trim_start().starts_with("//")) || self .post_comment .as_ref() - .map_or(false, |comment| comment.trim_start().starts_with("//")) + .is_some_and(|comment| comment.trim_start().starts_with("//")) } pub(crate) fn has_comment(&self) -> bool { @@ -285,7 +276,7 @@ where let indent_str = &formatting.shape.indent.to_string(formatting.config); while let Some((i, item)) = iter.next() { let item = item.as_ref(); - let inner_item = item.item.as_ref().or_else(|err| Err(err.clone()))?; + let inner_item = item.item.as_ref().map_err(|err| err.clone())?; let first = i == 0; let last = iter.peek().is_none(); let mut separate = match sep_place { @@ -589,7 +580,7 @@ pub(crate) fn extract_pre_comment(pre_snippet: &str) -> (Option, ListIte let ends_with_block_comment = trimmed_pre_snippet.ends_with("*/"); let starts_with_single_line_comment = trimmed_pre_snippet.starts_with("//"); if ends_with_block_comment { - let comment_end = pre_snippet.rfind(|c| c == '/').unwrap(); + let comment_end = pre_snippet.rfind('/').unwrap(); if pre_snippet[comment_end..].contains('\n') { ( Some(trimmed_pre_snippet.to_owned()), @@ -632,7 +623,7 @@ pub(crate) fn extract_post_comment( false }; - let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') { + let post_snippet_trimmed = if post_snippet.starts_with([',', ':']) { post_snippet[1..].trim_matches(white_space) } else if let Some(stripped) = post_snippet.strip_prefix(separator) { stripped.trim_matches(white_space) @@ -669,7 +660,7 @@ pub(crate) fn get_comment_end( if is_last { return post_snippet .find_uncommented(terminator) - .unwrap_or_else(|| post_snippet.len()); + .unwrap_or(post_snippet.len()); } let mut block_open_index = post_snippet.find("/*"); @@ -725,14 +716,12 @@ pub(crate) fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool .len_utf8(); // Everything from the separator to the next item. let test_snippet = &post_snippet[comment_end - len_last..]; - let first_newline = test_snippet - .find('\n') - .unwrap_or_else(|| test_snippet.len()); + let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len()); // From the end of the first line of comments. let test_snippet = &test_snippet[first_newline..]; let first = test_snippet .find(|c: char| !c.is_whitespace()) - .unwrap_or_else(|| test_snippet.len()); + .unwrap_or(test_snippet.len()); // From the end of the first line of comments to the next non-whitespace char. let test_snippet = &test_snippet[..first]; @@ -740,7 +729,7 @@ pub(crate) fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool count_newlines(test_snippet) > 1 } -impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3> +impl Iterator for ListItems<'_, I, F1, F2, F3> where I: Iterator, F1: Fn(&T) -> BytePos, diff --git a/src/macros.rs b/src/macros.rs index 1049fab1ebd..aab86f55724 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -466,7 +466,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)?; @@ -831,7 +831,7 @@ impl MacroArgParser { // Parse '*', '+' or '?. for tok in iter { - self.set_last_tok(&tok); + self.set_last_tok(tok); if first { first = false; } @@ -979,7 +979,7 @@ impl MacroArgParser { } } - self.set_last_tok(&tok); + self.set_last_tok(tok); } // We are left with some stuff in the buffer. Since there is nothing @@ -1015,7 +1015,7 @@ fn wrap_macro_args_inner( result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?); if use_multiple_lines - && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var())) + && (arg.kind.ends_with_space() || iter.peek().is_some_and(|a| a.kind.has_meta_var())) { if arg.kind.ends_with_space() { result.pop(); @@ -1284,10 +1284,8 @@ impl MacroBranch { let old_body = context.snippet(self.body).trim(); let has_block_body = old_body.starts_with('{'); let mut prefix_width = 5; // 5 = " => {" - if context.config.style_edition() >= StyleEdition::Edition2024 { - if has_block_body { - prefix_width = 6; // 6 = " => {{" - } + if context.config.style_edition() >= StyleEdition::Edition2024 && has_block_body { + prefix_width = 6; // 6 = " => {{" } let mut result = format_macro_args( context, @@ -1439,7 +1437,7 @@ fn format_lazy_static( result.push_str(&rewrite_assign_rhs( context, stmt, - &*expr, + expr, &RhsAssignKind::Expr(&expr.kind, expr.span), nested_shape.sub_width(1, expr.span)?, )?); diff --git a/src/matches.rs b/src/matches.rs index 2955f5d119a..f9aa16c2fcb 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -43,7 +43,7 @@ impl<'a> ArmWrapper<'a> { } } -impl<'a> Spanned for ArmWrapper<'a> { +impl Spanned for ArmWrapper<'_> { fn span(&self) -> Span { if let Some(lo) = self.beginning_vert { let lo = std::cmp::min(lo, self.arm.span().lo()); @@ -54,7 +54,7 @@ impl<'a> Spanned for ArmWrapper<'a> { } } -impl<'a> Rewrite for ArmWrapper<'a> { +impl Rewrite for ArmWrapper<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -217,7 +217,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)), "}", "|", @@ -343,7 +343,7 @@ fn block_can_be_flattened<'a>( && is_simple_block(context, block, Some(&expr.attrs)) && !stmt_is_expr_mac(&block.stmts[0]) => { - Some(&*block) + Some(block) } _ => None, } @@ -371,18 +371,18 @@ fn flatten_arm_body<'a>( } else { let cond_becomes_multi_line = opt_shape .and_then(|shape| rewrite_cond(context, expr, shape)) - .map_or(false, |cond| cond.contains('\n')); + .is_some_and(|cond| cond.contains('\n')); if cond_becomes_multi_line { - (false, &*body) + (false, body) } else { - (can_extend(expr), &*expr) + (can_extend(expr), expr) } } } else { - (false, &*body) + (false, body) } } else { - (can_extend(body), &*body) + (can_extend(body), body) } } @@ -472,12 +472,10 @@ fn rewrite_match_body( }; let semicolon = if context.config.style_edition() <= StyleEdition::Edition2021 { "" + } else if semicolon_for_expr(context, body) { + ";" } else { - if semicolon_for_expr(context, body) { - ";" - } else { - "" - } + "" }; ("{", format!("{}{}}}{}", semicolon, indent_str, comma)) } else { diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 384de1ce9ae..3b4722b467d 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -30,7 +30,7 @@ impl SnippetStatus { } } -impl<'a> FmtVisitor<'a> { +impl FmtVisitor<'_> { fn output_at_start(&self) -> bool { self.buffer.is_empty() } @@ -237,7 +237,7 @@ impl<'a> FmtVisitor<'a> { .rev() .find(|rev_c| ![' ', '\t'].contains(rev_c)); - let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c)); + let fix_indent = last_char.is_none_or(|rev_c| ['{', '\n'].contains(&rev_c)); let mut on_same_line = false; let comment_indent = if fix_indent { diff --git a/src/overflow.rs b/src/overflow.rs index 19f7b06f8a3..41b6158e1fb 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -87,7 +87,7 @@ pub(crate) enum OverflowableItem<'a> { PreciseCapturingArg(&'a ast::PreciseCapturingArg), } -impl<'a> Rewrite for OverflowableItem<'a> { +impl Rewrite for OverflowableItem<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.map(|item| item.rewrite(context, shape)) } @@ -97,7 +97,7 @@ impl<'a> Rewrite for OverflowableItem<'a> { } } -impl<'a> Spanned for OverflowableItem<'a> { +impl Spanned for OverflowableItem<'_> { fn span(&self) -> Span { self.map(|item| item.span()) } @@ -446,7 +446,7 @@ impl<'a> Context<'a> { | ast::ExprKind::While(..) | ast::ExprKind::Match(..) => { let multi_line = rewrite_cond(self.context, expr, shape) - .map_or(false, |cond| cond.contains('\n')); + .is_some_and(|cond| cond.contains('\n')); if multi_line { None @@ -463,7 +463,7 @@ impl<'a> Context<'a> { if let Some(rewrite) = rewrite { // splitn(2, *).next().unwrap() is always safe. - let rewrite_first_line = Ok(rewrite.splitn(2, '\n').next().unwrap().to_owned()); + let rewrite_first_line = Ok(rewrite.split('\n').next().unwrap().to_owned()); last_list_item.item = rewrite_first_line; Some(rewrite) } else { @@ -549,7 +549,7 @@ impl<'a> Context<'a> { .items .last() .and_then(|last_item| last_item.rewrite(self.context, self.nested_shape)); - let no_newline = rw.as_ref().map_or(false, |s| !s.contains('\n')); + let no_newline = rw.as_ref().is_some_and(|s| !s.contains('\n')); if no_newline { list_items[self.items.len() - 1].item = rw.unknown_error(); } else { @@ -584,7 +584,7 @@ impl<'a> Context<'a> { if tactic == DefinitiveListTactic::Vertical { if let Some((all_simple, num_args_before)) = - maybe_get_args_offset(self.ident, &self.items, &self.context.config) + maybe_get_args_offset(self.ident, &self.items, self.context.config) { let one_line = all_simple && definitive_tactic( @@ -740,14 +740,14 @@ impl<'a> Context<'a> { fn need_block_indent(s: &str, shape: Shape) -> bool { s.lines().skip(1).any(|s| { s.find(|c| !char::is_whitespace(c)) - .map_or(false, |w| w + 1 < shape.indent.width()) + .is_some_and(|w| w + 1 < shape.indent.width()) }) } fn can_be_overflowed(context: &RewriteContext<'_>, items: &[OverflowableItem<'_>]) -> bool { items .last() - .map_or(false, |x| x.can_be_overflowed(context, items.len())) + .is_some_and(|x| x.can_be_overflowed(context, items.len())) } /// Returns a shape for the last argument which is going to be overflowed. @@ -757,7 +757,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 @@ -808,7 +808,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/pairs.rs b/src/pairs.rs index 48948b88b3b..c2f9e6e5349 100644 --- a/src/pairs.rs +++ b/src/pairs.rs @@ -281,7 +281,7 @@ fn is_ident_or_bool_lit(expr: &ast::Expr) -> bool { } } -impl<'a, 'b> PairList<'a, 'b, ast::Expr> { +impl PairList<'_, '_, ast::Expr> { fn let_chain_count(&self) -> usize { self.list .iter() diff --git a/src/parse/macros/mod.rs b/src/parse/macros/mod.rs index 680a35f7e03..bd47ca1f17c 100644 --- a/src/parse/macros/mod.rs +++ b/src/parse/macros/mod.rs @@ -13,7 +13,7 @@ pub(crate) mod asm; pub(crate) mod cfg_if; pub(crate) mod lazy_static; -fn build_stream_parser<'a>(psess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> { +fn build_stream_parser(psess: &ParseSess, tokens: TokenStream) -> Parser<'_> { Parser::new(psess, tokens, MACRO_ARGUMENTS).recovery(Recovery::Forbidden) } @@ -141,7 +141,7 @@ pub(crate) fn parse_macro_args( } return None; } - _ if args.last().map_or(false, MacroArg::is_item) => continue, + _ if args.last().is_some_and(MacroArg::is_item) => continue, _ => return None, } diff --git a/src/parse/session.rs b/src/parse/session.rs index 63cc8794cea..cc8e0ff7045 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -102,7 +102,7 @@ fn default_dcx( show_parse_errors: bool, color: Color, ) -> DiagCtxt { - let supports_color = term::stderr().map_or(false, |term| term.supports_color()); + let supports_color = term::stderr().is_some_and(|term| term.supports_color()); let emit_color = if supports_color { ColorConfig::from(color) } else { @@ -424,7 +424,7 @@ mod tests { let fatal_diagnostic = build_diagnostic(DiagnosticLevel::Fatal, Some(span)); emitter.emit_diagnostic(fatal_diagnostic, ®istry); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1); - assert_eq!(can_reset_errors.load(Ordering::Acquire), false); + assert!(!can_reset_errors.load(Ordering::Acquire)); } #[nightly_only_test] @@ -450,7 +450,7 @@ mod tests { let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span)); emitter.emit_diagnostic(non_fatal_diagnostic, ®istry); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 0); - assert_eq!(can_reset_errors.load(Ordering::Acquire), true); + assert!(can_reset_errors.load(Ordering::Acquire)); } #[nightly_only_test] @@ -475,7 +475,7 @@ mod tests { let non_fatal_diagnostic = build_diagnostic(DiagnosticLevel::Warning, Some(span)); emitter.emit_diagnostic(non_fatal_diagnostic, ®istry); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 1); - assert_eq!(can_reset_errors.load(Ordering::Acquire), false); + assert!(!can_reset_errors.load(Ordering::Acquire)); } #[nightly_only_test] @@ -517,7 +517,7 @@ mod tests { emitter.emit_diagnostic(foo_diagnostic, ®istry); emitter.emit_diagnostic(fatal_diagnostic, ®istry); assert_eq!(num_emitted_errors.load(Ordering::Acquire), 2); - assert_eq!(can_reset_errors.load(Ordering::Acquire), false); + assert!(!can_reset_errors.load(Ordering::Acquire)); } } } diff --git a/src/patterns.rs b/src/patterns.rs index 875c6441190..3edc19adff1 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -57,7 +57,7 @@ fn is_short_pattern_inner(pat: &ast::Pat) -> bool { ast::PatKind::Box(ref p) | PatKind::Deref(ref p) | ast::PatKind::Ref(ref p, _) - | ast::PatKind::Paren(ref p) => is_short_pattern_inner(&*p), + | ast::PatKind::Paren(ref p) => is_short_pattern_inner(p), PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)), } } @@ -67,7 +67,7 @@ pub(crate) struct RangeOperand<'a> { pub(crate) span: Span, } -impl<'a> Rewrite for RangeOperand<'a> { +impl Rewrite for RangeOperand<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -408,14 +408,12 @@ fn rewrite_struct_pat( } fields_str.push('\n'); fields_str.push_str(&nested_shape.indent.to_string(context.config)); - } else { - if !fields_str.is_empty() { - // there are preceding struct fields being matched on - if has_trailing_comma { - fields_str.push(' '); - } else { - fields_str.push_str(", "); - } + } else if !fields_str.is_empty() { + // there are preceding struct fields being matched on + if has_trailing_comma { + fields_str.push(' '); + } else { + fields_str.push_str(", "); } } fields_str.push_str(".."); @@ -486,7 +484,7 @@ pub(crate) enum TuplePatField<'a> { Dotdot(Span), } -impl<'a> Rewrite for TuplePatField<'a> { +impl Rewrite for TuplePatField<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -499,7 +497,7 @@ impl<'a> Rewrite for TuplePatField<'a> { } } -impl<'a> Spanned for TuplePatField<'a> { +impl Spanned for TuplePatField<'_> { fn span(&self) -> Span { match *self { TuplePatField::Pat(p) => p.span(), @@ -508,7 +506,7 @@ impl<'a> Spanned for TuplePatField<'a> { } } -impl<'a> TuplePatField<'a> { +impl TuplePatField<'_> { fn is_dotdot(&self) -> bool { match self { TuplePatField::Pat(pat) => matches!(pat.kind, ast::PatKind::Rest), @@ -566,7 +564,7 @@ fn rewrite_tuple_pat( (&pat_vec[..], span) }; - let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot()); + let is_last_pat_dotdot = pat_vec.last().is_some_and(|p| p.is_dotdot()); let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot; let path_str = path_str.unwrap_or_default(); diff --git a/src/reorder.rs b/src/reorder.rs index 3a94a82f85d..2d2abedb968 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -35,7 +35,7 @@ fn compare_items(a: &ast::Item, b: &ast::Item, context: &RewriteContext<'_>) -> version_sort(a.ident.as_str(), b.ident.as_str()) } } - (&ast::ItemKind::ExternCrate(ref a_name), &ast::ItemKind::ExternCrate(ref b_name)) => { + (ast::ItemKind::ExternCrate(a_name), ast::ItemKind::ExternCrate(b_name)) => { // `extern crate foo as bar;` // ^^^ Comparing this. let a_orig_name = a_name.unwrap_or(a.ident.name); @@ -148,10 +148,7 @@ fn rewrite_reorderable_or_regroupable_items( .map(|use_tree| { let item = use_tree.rewrite_top_level(context, nested_shape); if let Some(list_item) = use_tree.list_item { - ListItem { - item: item, - ..list_item - } + ListItem { item, ..list_item } } else { ListItem::from_item(item) } @@ -288,7 +285,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let item_length = items .iter() .take_while(|ppi| { - item_kind.is_same_item_kind(&***ppi) + item_kind.is_same_item_kind(ppi) && (!in_group || { let current = self.psess.lookup_line_range(ppi.span()); let in_same_group = current.lo < last.hi + 2; diff --git a/src/rewrite.rs b/src/rewrite.rs index 7ca1ca522ff..0aab0c6b7d3 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -86,21 +86,18 @@ pub(crate) trait RewriteErrorExt { impl RewriteErrorExt for Option { fn max_width_error(self, width: usize, span: Span) -> Result { - self.ok_or_else(|| RewriteError::ExceedsMaxWidth { + self.ok_or(RewriteError::ExceedsMaxWidth { configured_width: width, - span: span, + span, }) } fn macro_error(self, kind: MacroErrorKind, span: Span) -> Result { - self.ok_or_else(|| RewriteError::MacroFailure { - kind: kind, - span: span, - }) + self.ok_or(RewriteError::MacroFailure { kind, span }) } fn unknown_error(self) -> Result { - self.ok_or_else(|| RewriteError::Unknown) + self.ok_or(RewriteError::Unknown) } } @@ -142,7 +139,7 @@ impl Drop for InsideMacroGuard { } } -impl<'a> RewriteContext<'a> { +impl RewriteContext<'_> { pub(crate) fn snippet(&self, span: Span) -> &str { self.snippet_provider.span_to_snippet(span).unwrap() } diff --git a/src/sort.rs b/src/sort.rs index 0cdd937b4f5..04facd97815 100644 --- a/src/sort.rs +++ b/src/sort.rs @@ -14,12 +14,12 @@ impl<'a> VersionChunkIter<'a> { fn parse_numeric_chunk( &mut self, - mut chars: std::str::CharIndices<'a>, + chars: std::str::CharIndices<'a>, ) -> Option> { let mut end = self.start; let mut is_end_of_chunk = false; - while let Some((idx, c)) = chars.next() { + for (idx, c) in chars { end = self.start + idx; if c.is_ascii_digit() { @@ -50,14 +50,11 @@ impl<'a> VersionChunkIter<'a> { }) } - fn parse_str_chunk( - &mut self, - mut chars: std::str::CharIndices<'a>, - ) -> Option> { + fn parse_str_chunk(&mut self, chars: std::str::CharIndices<'a>) -> Option> { let mut end = self.start; let mut is_end_of_chunk = false; - while let Some((idx, c)) = chars.next() { + for (idx, c) in chars { end = self.start + idx; if c == '_' { @@ -95,7 +92,7 @@ impl<'a> Iterator for VersionChunkIter<'a> { let (_, next) = chars.next()?; if next == '_' { - self.start = self.start + next.len_utf8(); + self.start += next.len_utf8(); return Some(VersionChunk::Underscore); } @@ -151,11 +148,11 @@ pub(crate) fn version_sort(a: &str, b: &str) -> std::cmp::Ordering { (VersionChunk::Str(ca), VersionChunk::Str(cb)) | (VersionChunk::Str(ca), VersionChunk::Number { source: cb, .. }) | (VersionChunk::Number { source: ca, .. }, VersionChunk::Str(cb)) => { - match ca.cmp(&cb) { + match ca.cmp(cb) { std::cmp::Ordering::Equal => { continue; } - order @ _ => return order, + order => return order, } } ( @@ -182,7 +179,7 @@ pub(crate) fn version_sort(a: &str, b: &str) -> std::cmp::Ordering { } continue; } - order @ _ => return order, + order => return order, }, }, } diff --git a/src/spanned.rs b/src/spanned.rs index 6b3e40b9115..4d6483ec215 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -211,7 +211,7 @@ impl Spanned for ast::PreciseCapturingArg { } } -impl<'a> Spanned for RangeOperand<'a> { +impl Spanned for RangeOperand<'_> { fn span(&self) -> Span { self.span } diff --git a/src/stmt.rs b/src/stmt.rs index 76194421c84..80d9abfff62 100644 --- a/src/stmt.rs +++ b/src/stmt.rs @@ -15,7 +15,7 @@ pub(crate) struct Stmt<'a> { is_last: bool, } -impl<'a> Spanned for Stmt<'a> { +impl Spanned for Stmt<'_> { fn span(&self) -> Span { self.inner.span() } @@ -88,7 +88,7 @@ impl<'a> Stmt<'a> { } } -impl<'a> Rewrite for Stmt<'a> { +impl Rewrite for Stmt<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } diff --git a/src/string.rs b/src/string.rs index 3b971188cd5..43dd1f2bb74 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()?; @@ -390,7 +390,7 @@ mod test { #[test] fn line_break_at_valid_points_test() { let string = "[TheName](Dont::break::my::type::That::would::be::very::nice) break here"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::LineEnd( @@ -403,7 +403,7 @@ mod test { #[test] fn should_break_on_whitespace() { let string = "Placerat felis. Mauris porta ante sagittis purus."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::LineEnd("Placerat felis. ".to_string(), 16) @@ -417,7 +417,7 @@ mod test { #[test] fn should_break_on_punctuation() { let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::LineEnd("Placerat_felis.".to_string(), 15) @@ -427,7 +427,7 @@ mod test { #[test] fn should_break_forward() { let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29) @@ -441,7 +441,7 @@ mod test { #[test] fn nothing_to_break() { let string = "Venenatis_tellus_vel_tellus"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string()) @@ -451,7 +451,7 @@ mod test { #[test] fn significant_whitespaces() { let string = "Neque in sem. \n Pellentesque tellus augue."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(15, false, "", &graphemes[..]), SnippetState::EndWithLineFeed("Neque in sem. \n".to_string(), 20) @@ -474,7 +474,7 @@ mod test { #[test] fn big_whitespace() { let string = "Neque in sem. Pellentesque tellus augue."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(20, false, "", &graphemes[..]), SnippetState::LineEnd("Neque in sem. ".to_string(), 25) @@ -489,7 +489,7 @@ mod test { fn newline_in_candidate_line() { let string = "Nulla\nconsequat erat at massa. Vivamus id mi."; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!( break_string(25, false, "", &graphemes[..]), SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6) @@ -699,27 +699,27 @@ mod test { #[test] fn detect_urls() { let string = "aaa http://example.org something"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 8), Some(21)); let string = "https://example.org something"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 0), Some(18)); let string = "aaa ftp://example.org something"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 8), Some(20)); let string = "aaa file://example.org something"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 8), Some(21)); let string = "aaa http not an url"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 6), None); let string = "aaa file://example.org"; - let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::>(); + let graphemes = UnicodeSegmentation::graphemes(string, false).collect::>(); assert_eq!(detect_url(&graphemes, 8), Some(21)); } } diff --git a/src/test/mod.rs b/src/test/mod.rs index d62da08fff8..76c96308f82 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -105,14 +105,14 @@ fn is_file_skip(path: &Path) -> bool { fn get_test_files(path: &Path, recursive: bool) -> Vec { let mut files = vec![]; if path.is_dir() { - for entry in - fs::read_dir(path).expect(&format!("couldn't read directory {}", path.display())) + for entry in fs::read_dir(path) + .unwrap_or_else(|_| panic!("couldn't read directory {}", path.display())) { let entry = entry.expect("couldn't get `DirEntry`"); let path = entry.path(); if path.is_dir() && recursive { files.append(&mut get_test_files(&path, recursive)); - } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) { + } else if path.extension().is_some_and(|f| f == "rs") && !is_file_skip(&path) { files.push(path); } } @@ -121,10 +121,12 @@ fn get_test_files(path: &Path, recursive: bool) -> Vec { } fn verify_config_used(path: &Path, config_name: &str) { - for entry in fs::read_dir(path).expect(&format!("couldn't read {} directory", path.display())) { + for entry in + fs::read_dir(path).unwrap_or_else(|_| panic!("couldn't read {} directory", path.display())) + { let entry = entry.expect("couldn't get directory entry"); let path = entry.path(); - if path.extension().map_or(false, |f| f == "rs") { + if path.extension().is_some_and(|f| f == "rs") { // check if "// rustfmt-:" appears in the file. let filebuf = BufReader::new( fs::File::open(&path) @@ -292,7 +294,7 @@ fn assert_output(source: &Path, expected_filename: &Path) { let _ = source_file::write_all_files(&source_file, &mut out, &config); let output = String::from_utf8(out).unwrap(); - let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target"); + let mut expected_file = fs::File::open(expected_filename).expect("couldn't open target"); let mut expected_text = String::new(); expected_file .read_to_string(&mut expected_text) @@ -319,7 +321,7 @@ fn assert_stdin_output( config.set().newline_style(NewlineStyle::Unix); config.set().emit_mode(emit_mode); - let mut source_file = fs::File::open(&source).expect("couldn't open source"); + let mut source_file = fs::File::open(source).expect("couldn't open source"); let mut source_text = String::new(); source_file .read_to_string(&mut source_text) @@ -338,7 +340,7 @@ fn assert_stdin_output( assert_eq!(session.errors, errors); } - let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target"); + let mut expected_file = fs::File::open(expected_filename).expect("couldn't open target"); let mut expected_text = String::new(); expected_file .read_to_string(&mut expected_text) @@ -687,7 +689,7 @@ fn print_mismatches_default_message(result: HashMap>) { for (file_name, diff) in result { let mismatch_msg_formatter = |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num); - print_diff(diff, &mismatch_msg_formatter, &Default::default()); + print_diff(diff, mismatch_msg_formatter, &Default::default()); } if let Some(mut t) = term::stdout() { @@ -762,15 +764,16 @@ fn get_editions_from_comments( comments: &HashMap, ) -> (Option, Option, Option) { ( - comments - .get("edition") - .map(|e| Edition::from_str(e).expect(&format!("invalid edition value: '{}'", e))), + comments.get("edition").map(|e| { + Edition::from_str(e).unwrap_or_else(|_| panic!("invalid edition value: '{}'", e)) + }), comments.get("style_edition").map(|se| { - StyleEdition::from_str(se).expect(&format!("invalid style_edition value: '{}'", se)) + StyleEdition::from_str(se) + .unwrap_or_else(|_| panic!("invalid style_edition value: '{}'", se)) + }), + comments.get("version").map(|v| { + Version::from_str(v).unwrap_or_else(|_| panic!("invalid version value: '{}'", v)) }), - comments - .get("version") - .map(|v| Version::from_str(v).expect(&format!("invalid version value: '{}'", v))), ) } @@ -976,7 +979,7 @@ fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool { struct CharsIgnoreNewlineRepr<'a>(Peekable>); -impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> { +impl Iterator for CharsIgnoreNewlineRepr<'_> { type Item = char; fn next(&mut self) -> Option { diff --git a/src/types.rs b/src/types.rs index 6180a4dac13..fb2182483ca 100644 --- a/src/types.rs +++ b/src/types.rs @@ -146,7 +146,7 @@ pub(crate) enum SegmentParam<'a> { Binding(&'a ast::AssocItemConstraint), } -impl<'a> SegmentParam<'a> { +impl SegmentParam<'_> { fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_> { match arg { ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt), @@ -156,7 +156,7 @@ impl<'a> SegmentParam<'a> { } } -impl<'a> Spanned for SegmentParam<'a> { +impl Spanned for SegmentParam<'_> { fn span(&self) -> Span { match *self { SegmentParam::Const(const_) => const_.value.span, @@ -167,7 +167,7 @@ impl<'a> Spanned for SegmentParam<'a> { } } -impl<'a> Rewrite for SegmentParam<'a> { +impl Rewrite for SegmentParam<'_> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { self.rewrite_result(context, shape).ok() } @@ -644,7 +644,7 @@ impl Rewrite for ast::GenericParam { let mut result = self .attrs .rewrite_result(context, shape) - .unwrap_or(String::new()); + .unwrap_or_default(); let has_attrs = !result.is_empty(); let mut param = String::with_capacity(128); @@ -1128,16 +1128,14 @@ fn join_bounds_inner( let segments = &poly_trait_ref.trait_ref.path.segments; if segments.len() > 1 { true + } else if let Some(args_in) = &segments[0].args { + matches!( + args_in.deref(), + ast::GenericArgs::AngleBracketed(bracket_args) + if bracket_args.args.len() > 1 + ) } else { - if let Some(args_in) = &segments[0].args { - matches!( - args_in.deref(), - ast::GenericArgs::AngleBracketed(bracket_args) - if bracket_args.args.len() > 1 - ) - } else { - false - } + false } } ast::GenericBound::Use(args, _) => args.len() > 1, @@ -1244,7 +1242,7 @@ fn join_bounds_inner( // or the single item is of type `Trait`, // and any of the internal arrays contains more than one item; let retry_with_force_newline = match context.config.style_edition() { - style_edition @ _ if style_edition <= StyleEdition::Edition2021 => { + style_edition if style_edition <= StyleEdition::Edition2021 => { !force_newline && items.len() > 1 && (result.0.contains('\n') || result.0.len() > shape.width) @@ -1278,7 +1276,7 @@ pub(crate) fn can_be_overflowed_type( ast::TyKind::Tup(..) => context.use_block_indent() && len == 1, ast::TyKind::Ref(_, ref mutty) | ast::TyKind::PinnedRef(_, ref mutty) - | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len), + | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &mutty.ty, len), _ => false, } } diff --git a/src/utils.rs b/src/utils.rs index ba4a4c045f1..d4cc89425f1 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -183,12 +183,12 @@ pub(crate) fn is_single_line(s: &str) -> bool { #[inline] pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool { - s.lines().next().map_or(false, |l| l.contains("//")) + s.lines().next().is_some_and(|l| l.contains("//")) } #[inline] pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool { - s.lines().last().map_or(false, |l| l.contains("//")) + s.lines().last().is_some_and(|l| l.contains("//")) } #[inline] @@ -199,13 +199,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. @@ -266,9 +266,7 @@ fn is_skip_nested(meta_item: &MetaItemInner) -> bool { #[inline] pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool { - attrs - .iter() - .any(|a| a.meta().map_or(false, |a| is_skip(&a))) + attrs.iter().any(|a| a.meta().is_some_and(|a| is_skip(&a))) } #[inline] @@ -458,7 +456,7 @@ pub(crate) fn starts_with_newline(s: &str) -> bool { #[inline] pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool { - s.lines().next().map_or(false, |l| l.ends_with(c)) + s.lines().next().is_some_and(|l| l.ends_with(c)) } // States whether an expression's last line exclusively consists of closing diff --git a/src/visitor.rs b/src/visitor.rs index 59e52d687d0..2774816c4ba 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -89,7 +89,7 @@ pub(crate) struct FmtVisitor<'a> { pub(crate) is_macro_def: bool, } -impl<'a> Drop for FmtVisitor<'a> { +impl Drop for FmtVisitor<'_> { fn drop(&mut self) { if let Some(ctx) = self.parent_context { if self.macro_rewrite_failure { @@ -121,7 +121,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo())); let original_starts_with_newline = snippet .find(|c| c != ' ') - .map_or(false, |i| starts_with_newline(&snippet[i..])); + .is_some_and(|i| starts_with_newline(&snippet[i..])); let snippet = snippet.trim(); if !snippet.is_empty() { // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy @@ -267,7 +267,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 @@ -871,7 +871,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { // Extract leading `use ...;`. let items: Vec<_> = stmts .iter() - .take_while(|stmt| stmt.to_item().map_or(false, is_use_item)) + .take_while(|stmt| stmt.to_item().is_some_and(is_use_item)) .filter_map(|stmt| stmt.to_item()) .collect(); @@ -920,7 +920,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { attrs: &[ast::Attribute], ) { let vis_str = utils::format_visibility(&self.get_context(), vis); - self.push_str(&*vis_str); + self.push_str(&vis_str); self.push_str(format_safety(safety)); self.push_str("mod "); // Calling `to_owned()` to work around borrow checker.