diff --git a/src/attr.rs b/src/attr.rs index 2679b1b6e7a..802dfc0485c 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -11,7 +11,7 @@ use crate::config::IndentStyle; use crate::expr::rewrite_literal; use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator}; use crate::overflow; -use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt}; +use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult}; use crate::shape::Shape; use crate::source_map::SpanUtils; use crate::types::{rewrite_path, PathContext}; @@ -217,9 +217,9 @@ fn rewrite_initial_doc_comments( context: &RewriteContext<'_>, attrs: &[ast::Attribute], shape: Shape, -) -> Option<(usize, Option)> { +) -> Result<(usize, Option), RewriteError> { if attrs.is_empty() { - return Some((0, None)); + return Ok((0, None)); } // Rewrite doc comments let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_doc_comment()); @@ -229,7 +229,7 @@ fn rewrite_initial_doc_comments( .map(|a| context.snippet(a.span)) .collect::>() .join("\n"); - return Some(( + return Ok(( sugared_docs.len(), Some(rewrite_doc_comment( &snippet, @@ -239,13 +239,19 @@ fn rewrite_initial_doc_comments( )); } - Some((0, None)) + Ok((0, None)) } impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { match self { - ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), + ast::NestedMetaItem::MetaItem(ref meta_item) => { + meta_item.rewrite_result(context, shape) + } ast::NestedMetaItem::Lit(ref l) => { rewrite_literal(context, l.as_token_lit(), l.span, shape) } @@ -277,11 +283,7 @@ impl Rewrite for ast::MetaItem { self.rewrite_result(context, shape).ok() } - fn rewrite_result( - &self, - context: &RewriteContext<'_>, - shape: Shape, - ) -> crate::rewrite::RewriteResult { + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { Ok(match self.kind { ast::MetaItemKind::Word => { rewrite_path(context, PathContext::Type, &None, &self.path, shape)? @@ -317,7 +319,7 @@ impl Rewrite for ast::MetaItem { // is longer than the max width and continue on formatting. // See #2479 for example. let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape) - .unwrap_or_else(|| context.snippet(lit.span).to_owned()); + .unwrap_or_else(|_| context.snippet(lit.span).to_owned()); format!("{path} = {value}") } }) @@ -326,6 +328,10 @@ impl Rewrite for ast::MetaItem { impl Rewrite for ast::Attribute { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { let snippet = context.snippet(self.span); if self.is_doc_comment() { rewrite_doc_comment(snippet, shape.comment(context.config), context.config) @@ -337,7 +343,7 @@ impl Rewrite for ast::Attribute { let prefix = attr_prefix(self); if should_skip || contains_comment(snippet) { - return Some(snippet.to_owned()); + return Ok(snippet.to_owned()); } if let Some(ref meta) = self.meta() { @@ -362,9 +368,11 @@ impl Rewrite for ast::Attribute { } // 1 = `[` - let shape = shape.offset_left(prefix.len() + 1)?; - Some(meta.rewrite(context, shape).map_or_else( - || snippet.to_owned(), + let shape = shape + .offset_left(prefix.len() + 1) + .max_width_error(shape.width, self.span)?; + Ok(meta.rewrite_result(context, shape).map_or_else( + |_| snippet.to_owned(), |rw| match &self.kind { ast::AttrKind::Normal(normal_attr) => match normal_attr.item.unsafety { // For #![feature(unsafe_attributes)] @@ -376,7 +384,7 @@ impl Rewrite for ast::Attribute { }, )) } else { - Some(snippet.to_owned()) + Ok(snippet.to_owned()) } } } @@ -384,8 +392,12 @@ impl Rewrite for ast::Attribute { impl Rewrite for [ast::Attribute] { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { if self.is_empty() { - return Some(String::new()); + return Ok(String::new()); } // The current remaining attributes. @@ -401,7 +413,7 @@ impl Rewrite for [ast::Attribute] { // merging derives into a single attribute. loop { if attrs.is_empty() { - return Some(result); + return Ok(result); } // Handle doc comments. @@ -440,7 +452,7 @@ impl Rewrite for [ast::Attribute] { // Handle derives if we will merge them. if !skip_derives && context.config.merge_derives() && is_derive(&attrs[0]) { let derives = take_while_with_pred(context, attrs, is_derive); - let derive_str = format_derive(derives, shape, context)?; + let derive_str = format_derive(derives, shape, context).unknown_error()?; result.push_str(&derive_str); let missing_span = attrs @@ -473,7 +485,7 @@ impl Rewrite for [ast::Attribute] { // If we get here, then we have a regular attribute, just handle one // at a time. - let formatted_attr = attrs[0].rewrite(context, shape)?; + let formatted_attr = attrs[0].rewrite_result(context, shape)?; result.push_str(&formatted_attr); let missing_span = attrs diff --git a/src/chains.rs b/src/chains.rs index 923ffeae7b7..65326527000 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -66,7 +66,7 @@ use crate::config::{IndentStyle, StyleEdition}; use crate::expr::rewrite_call; use crate::lists::extract_pre_comment; use crate::macros::convert_try_mac; -use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteResult}; +use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult}; use crate::shape::Shape; use crate::source_map::SpanUtils; use crate::utils::{ @@ -268,7 +268,13 @@ impl ChainItemKind { impl Rewrite for ChainItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - let shape = shape.sub_width(self.tries)?; + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { + let shape = shape + .sub_width(self.tries) + .max_width_error(shape.width, self.span)?; let rewrite = match self.kind { ChainItemKind::Parent { ref expr, @@ -277,10 +283,9 @@ impl Rewrite for ChainItem { ChainItemKind::Parent { ref expr, parens: false, - } => expr.rewrite(context, shape)?, + } => expr.rewrite_result(context, shape)?, ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => { - Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape) - .ok()? + Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)? } ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)), ChainItemKind::TupleField(ident, nested) => format!( @@ -297,7 +302,7 @@ impl Rewrite for ChainItem { rewrite_comment(comment, false, shape, context.config)? } }; - Some(format!("{rewrite}{}", "?".repeat(self.tries))) + Ok(format!("{rewrite}{}", "?".repeat(self.tries))) } } diff --git a/src/comment.rs b/src/comment.rs index 24a5a1be2c3..5bf3c1a725c 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -6,7 +6,7 @@ use itertools::{multipeek, MultiPeek}; use rustc_span::Span; use crate::config::Config; -use crate::rewrite::RewriteContext; +use crate::rewrite::{RewriteContext, RewriteErrorExt, RewriteResult}; use crate::shape::{Indent, Shape}; use crate::string::{rewrite_string, StringFormat}; use crate::utils::{ @@ -157,7 +157,7 @@ pub(crate) fn combine_strs_with_missing_comments( span: Span, shape: Shape, allow_extend: bool, -) -> Option { +) -> RewriteResult { trace!( "combine_strs_with_missing_comments `{}` `{}` {:?} {:?}", prev_str, next_str, span, shape @@ -187,7 +187,7 @@ pub(crate) fn combine_strs_with_missing_comments( result.push_str(&indent.to_string_with_newline(config)) } result.push_str(next_str); - return Some(result); + return Ok(result); } // We have a missing comment between the first expression and the second expression. @@ -232,10 +232,10 @@ pub(crate) fn combine_strs_with_missing_comments( result.push_str(&second_sep); result.push_str(next_str); - Some(result) + Ok(result) } -pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option { +pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> RewriteResult { identify_comment(orig, false, shape, config, true) } @@ -244,7 +244,7 @@ pub(crate) fn rewrite_comment( block_style: bool, shape: Shape, config: &Config, -) -> Option { +) -> RewriteResult { identify_comment(orig, block_style, shape, config, false) } @@ -254,7 +254,7 @@ fn identify_comment( shape: Shape, config: &Config, is_doc_comment: bool, -) -> Option { +) -> RewriteResult { let style = comment_style(orig, false); // Computes the byte length of line taking into account a newline if the line is part of a @@ -346,7 +346,7 @@ fn identify_comment( let (first_group, rest) = orig.split_at(first_group_ending); let rewritten_first_group = if !config.normalize_comments() && has_bare_lines && style.is_block_comment() { - trim_left_preserve_layout(first_group, shape.indent, config)? + trim_left_preserve_layout(first_group, shape.indent, config).unknown_error()? } else if !config.normalize_comments() && !config.wrap_comments() && !( @@ -367,7 +367,7 @@ fn identify_comment( )? }; if rest.is_empty() { - Some(rewritten_first_group) + Ok(rewritten_first_group) } else { identify_comment( rest.trim_start(), @@ -899,7 +899,7 @@ fn rewrite_comment_inner( shape: Shape, config: &Config, is_doc_comment: bool, -) -> Option { +) -> RewriteResult { let mut rewriter = CommentRewrite::new(orig, block_style, shape, config); let line_breaks = count_newlines(orig.trim_end()); @@ -933,7 +933,7 @@ fn rewrite_comment_inner( } } - Some(rewriter.finish()) + Ok(rewriter.finish()) } const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### "; @@ -998,7 +998,7 @@ pub(crate) fn rewrite_missing_comment( span: Span, shape: Shape, context: &RewriteContext<'_>, -) -> Option { +) -> RewriteResult { let missing_snippet = context.snippet(span); let trimmed_snippet = missing_snippet.trim(); // check the span starts with a comment @@ -1006,7 +1006,7 @@ pub(crate) fn rewrite_missing_comment( if !trimmed_snippet.is_empty() && pos.is_some() { rewrite_comment(trimmed_snippet, false, shape, context.config) } else { - Some(String::new()) + Ok(String::new()) } } @@ -1018,13 +1018,13 @@ pub(crate) fn recover_missing_comment_in_span( shape: Shape, context: &RewriteContext<'_>, used_width: usize, -) -> Option { +) -> RewriteResult { let missing_comment = rewrite_missing_comment(span, shape, context)?; if missing_comment.is_empty() { - Some(String::new()) + Ok(String::new()) } else { let missing_snippet = context.snippet(span); - let pos = missing_snippet.find('/')?; + let pos = missing_snippet.find('/').unknown_error()?; // 1 = ` ` let total_width = missing_comment.len() + used_width + 1; let force_new_line_before_comment = @@ -1034,7 +1034,7 @@ pub(crate) fn recover_missing_comment_in_span( } else { Cow::from(" ") }; - Some(format!("{sep}{missing_comment}")) + Ok(format!("{sep}{missing_comment}")) } } diff --git a/src/expr.rs b/src/expr.rs index 6f6f9fec6c0..0edc35c7c7d 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -82,7 +82,7 @@ pub(crate) fn format_expr( ) .ok(), ast::ExprKind::Lit(token_lit) => { - if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) { + if let Ok(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) { Some(expr_rw) } else { if let LitKind::StrRaw(_) = token_lit.kind { @@ -97,7 +97,7 @@ pub(crate) fn format_expr( let callee_str = callee.rewrite(context, shape)?; rewrite_call(context, &callee_str, args, inner_span, shape).ok() } - ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span), + ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span).ok(), ast::ExprKind::Binary(op, ref lhs, ref rhs) => { // FIXME: format comments between operands and operator rewrite_all_pairs(expr, shape, context) @@ -136,7 +136,9 @@ pub(crate) fn format_expr( ast::ExprKind::Tup(ref items) => { rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1).ok() } - ast::ExprKind::Let(ref pat, ref expr, _span, _) => rewrite_let(context, shape, pat, expr), + ast::ExprKind::Let(ref pat, ref expr, _span, _) => { + rewrite_let(context, shape, pat, expr).ok() + } ast::ExprKind::If(..) | ast::ExprKind::ForLoop { .. } | ast::ExprKind::Loop(..) @@ -166,7 +168,7 @@ pub(crate) fn format_expr( // Rewrite block without trying to put it in a single line. rw } else { - let prefix = block_prefix(context, block, shape)?; + let prefix = block_prefix(context, block, shape).ok()?; rewrite_block_with_visitor( context, @@ -437,6 +439,7 @@ pub(crate) fn format_expr( expr.span.lo(), ); combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false) + .ok() }) } @@ -498,17 +501,20 @@ fn rewrite_empty_block( None } -fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> Option { - Some(match block.rules { +fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape) -> RewriteResult { + Ok(match block.rules { ast::BlockCheckMode::Unsafe(..) => { let snippet = context.snippet(block.span); - let open_pos = snippet.find_uncommented("{")?; + let open_pos = snippet.find_uncommented("{").unknown_error()?; // Extract comment between unsafe and block start. let trimmed = &snippet[6..open_pos].trim(); if !trimmed.is_empty() { // 9 = "unsafe {".len(), 7 = "unsafe ".len() - let budget = shape.width.checked_sub(9)?; + let budget = shape + .width + .checked_sub(9) + .max_width_error(shape.width, block.span)?; format!( "unsafe {} ", rewrite_comment( @@ -612,7 +618,7 @@ fn rewrite_block_inner( context: &RewriteContext<'_>, shape: Shape, ) -> RewriteResult { - let prefix = block_prefix(context, block, shape).unknown_error()?; + let prefix = block_prefix(context, block, shape)?; // shape.width is used only for the single line case: either the empty block `{}`, // or an unsafe expression `unsafe { e }`. @@ -912,7 +918,8 @@ impl<'a> ControlFlow<'a> { RhsTactics::Default, comments_span, true, - ); + ) + .ok(); } let expr_rw = expr.rewrite(context, cond_shape); @@ -1191,7 +1198,7 @@ fn rewrite_label(opt_label: Option) -> Cow<'static, str> { fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option { match rewrite_missing_comment(span, shape, context) { - Some(ref comment) if !comment.is_empty() => Some(format!( + Ok(ref comment) if !comment.is_empty() => Some(format!( "{indent}{comment}{indent}", indent = shape.indent.to_string_with_newline(context.config) )), @@ -1262,7 +1269,7 @@ pub(crate) fn rewrite_literal( token_lit: token::Lit, span: Span, shape: Shape, -) -> Option { +) -> RewriteResult { match token_lit.kind { token::LitKind::Str => rewrite_string_lit(context, span, shape), token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape), @@ -1270,11 +1277,12 @@ pub(crate) fn rewrite_literal( context.snippet(span).to_owned(), context.config.max_width(), shape, - ), + ) + .max_width_error(shape.width, span), } } -fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> Option { +fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> RewriteResult { let string_lit = context.snippet(span); if !context.config.format_strings() { @@ -1284,9 +1292,10 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> .all(|line| line.ends_with('\\')) && context.config.style_edition() >= StyleEdition::Edition2024 { - return Some(string_lit.to_owned()); + return Ok(string_lit.to_owned()); } else { - return wrap_str(string_lit.to_owned(), context.config.max_width(), shape); + return wrap_str(string_lit.to_owned(), context.config.max_width(), shape) + .max_width_error(shape.width, span); } } @@ -1298,6 +1307,7 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> &StringFormat::new(shape.visual_indent(0), context.config), shape.width.saturating_sub(2), ) + .max_width_error(shape.width, span) } fn rewrite_int_lit( @@ -1305,7 +1315,7 @@ fn rewrite_int_lit( token_lit: token::Lit, span: Span, shape: Shape, -) -> Option { +) -> RewriteResult { let symbol = token_lit.symbol.as_str(); if let Some(symbol_stripped) = symbol.strip_prefix("0x") { @@ -1323,7 +1333,8 @@ fn rewrite_int_lit( ), context.config.max_width(), shape, - ); + ) + .max_width_error(shape.width, span); } } @@ -1332,6 +1343,7 @@ fn rewrite_int_lit( context.config.max_width(), shape, ) + .max_width_error(shape.width, span) } fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option { @@ -1472,7 +1484,7 @@ pub(crate) fn rewrite_paren( mut subexpr: &ast::Expr, shape: Shape, mut span: Span, -) -> Option { +) -> RewriteResult { debug!("rewrite_paren, shape: {:?}", shape); // Extract comments within parens. @@ -1501,11 +1513,14 @@ pub(crate) fn rewrite_paren( } // 1 = `(` and `)` - let sub_shape = shape.offset_left(1)?.sub_width(1)?; - let subexpr_str = subexpr.rewrite(context, sub_shape)?; + let sub_shape = shape + .offset_left(1) + .and_then(|s| s.sub_width(1)) + .max_width_error(shape.width, span)?; + let subexpr_str = subexpr.rewrite_result(context, sub_shape)?; let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//"); if fits_single_line { - Some(format!("({pre_comment}{subexpr_str}{post_comment})")) + Ok(format!("({pre_comment}{subexpr_str}{post_comment})")) } else { rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span) } @@ -1517,12 +1532,12 @@ fn rewrite_paren_in_multi_line( shape: Shape, pre_span: Span, post_span: Span, -) -> Option { +) -> RewriteResult { let nested_indent = shape.indent.block_indent(context.config); let nested_shape = Shape::indented(nested_indent, context.config); let pre_comment = rewrite_missing_comment(pre_span, nested_shape, context)?; let post_comment = rewrite_missing_comment(post_span, nested_shape, context)?; - let subexpr_str = subexpr.rewrite(context, nested_shape)?; + let subexpr_str = subexpr.rewrite_result(context, nested_shape)?; let mut result = String::with_capacity(subexpr_str.len() * 2); result.push('('); @@ -1539,7 +1554,7 @@ fn rewrite_paren_in_multi_line( result.push_str(&shape.indent.to_string_with_newline(context.config)); result.push(')'); - Some(result) + Ok(result) } fn rewrite_index( @@ -1889,14 +1904,16 @@ fn rewrite_let( shape: Shape, pat: &ast::Pat, expr: &ast::Expr, -) -> Option { +) -> RewriteResult { let mut result = "let ".to_owned(); // TODO(ytmimi) comments could appear between `let` and the `pat` // 4 = "let ".len() - let pat_shape = shape.offset_left(4)?; - let pat_str = pat.rewrite(context, pat_shape)?; + let pat_shape = shape + .offset_left(4) + .max_width_error(shape.width, pat.span)?; + let pat_str = pat.rewrite_result(context, pat_shape)?; result.push_str(&pat_str); // TODO(ytmimi) comments could appear between `pat` and `=` @@ -2116,7 +2133,7 @@ pub(crate) fn rewrite_assign_rhs_with, R: Rewrite>( Some(lhs + &rhs) } -pub(crate) fn rewrite_assign_rhs_with_comments, R: Rewrite>( +pub(crate) fn rewrite_assign_rhs_with_comments, R: Rewrite + Spanned>( context: &RewriteContext<'_>, lhs: S, ex: &R, @@ -2125,21 +2142,23 @@ pub(crate) fn rewrite_assign_rhs_with_comments, R: Rewrite>( rhs_tactics: RhsTactics, between_span: Span, allow_extend: bool, -) -> Option { +) -> RewriteResult { let lhs = lhs.into(); let contains_comment = contains_comment(context.snippet(between_span)); let shape = if contains_comment { - shape.block_left(context.config.tab_spaces())? + shape + .block_left(context.config.tab_spaces()) + .max_width_error(shape.width, between_span.with_hi(ex.span().hi()))? } else { shape }; - let rhs = rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics)?; - + let rhs = + rewrite_assign_rhs_expr(context, &lhs, ex, shape, rhs_kind, rhs_tactics).unknown_error()?; if contains_comment { let rhs = rhs.trim_start(); combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend) } else { - Some(lhs + &rhs) + Ok(lhs + &rhs) } } diff --git a/src/imports.rs b/src/imports.rs index edea5230890..6041f678cea 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -367,6 +367,7 @@ impl UseTree { shape, allow_extend, ) + .ok() } _ => Some(use_str), } diff --git a/src/items.rs b/src/items.rs index 6fb6d081946..35591df0fd8 100644 --- a/src/items.rs +++ b/src/items.rs @@ -77,8 +77,7 @@ impl Rewrite for ast::Local { ), shape, false, - ) - .unknown_error()? + )? }; let let_kw_offset = result.len() - "let ".len(); @@ -718,6 +717,7 @@ impl<'a> FmtVisitor<'a> { }; combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false) + .ok() } fn visit_impl_items(&mut self, items: &[ptr::P]) { @@ -853,7 +853,7 @@ pub(crate) fn format_impl( context, last_line_width(&result), ) { - Some(ref missing_comment) if !missing_comment.is_empty() => { + Ok(ref missing_comment) if !missing_comment.is_empty() => { result.push_str(missing_comment); } _ => (), @@ -1260,7 +1260,7 @@ pub(crate) fn format_trait( context, last_line_width(&result), ) { - Some(ref missing_comment) if !missing_comment.is_empty() => { + Ok(ref missing_comment) if !missing_comment.is_empty() => { result.push_str(missing_comment); } _ => (), @@ -1550,8 +1550,8 @@ fn format_empty_struct_or_tuple( // indented shape for proper indenting of multi-line comments let shape = Shape::indented(offset.block_indent(context.config), context.config); match rewrite_missing_comment(span, shape, context) { - Some(ref s) if s.is_empty() => (), - Some(ref s) => { + Ok(ref s) if s.is_empty() => (), + Ok(ref s) => { let is_multi_line = !is_single_line(s); if is_multi_line || first_line_contains_single_line_comment(s) { let nested_indent_str = offset @@ -1564,7 +1564,7 @@ fn format_empty_struct_or_tuple( result.push_str(&offset.to_string_with_newline(context.config)); } } - None => result.push_str(context.snippet(span)), + Err(_) => result.push_str(context.snippet(span)), } result.push_str(closer); } @@ -1827,7 +1827,8 @@ fn rewrite_ty( comment_span, comment_shape, true, - )? + ) + .ok()? } _ => format!("{result}="), }; @@ -1907,8 +1908,7 @@ pub(crate) fn rewrite_struct_field( missing_span, shape, attrs_extendable, - ) - .unknown_error()?; + )?; let overhead = trimmed_last_line_width(&attr_prefix); let lhs_offset = lhs_max_width.saturating_sub(overhead); for _ in 0..lhs_offset { @@ -1940,7 +1940,6 @@ pub(crate) fn rewrite_struct_field( &field_str }; combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false) - .unknown_error() } pub(crate) struct StaticParts<'a> { @@ -2074,6 +2073,7 @@ fn rewrite_static( comments_span, true, ) + .ok() .and_then(|res| recover_comment_removed(res, static_parts.span, context)) .map(|s| if s.ends_with(';') { s } else { s + ";" }) } else { @@ -2170,9 +2170,11 @@ fn get_missing_param_comments( }; let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context) + .ok() .filter(|comment| !comment.is_empty()) .map_or(String::new(), |comment| format!(" {}", comment)); let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context) + .ok() .filter(|comment| !comment.is_empty()) .map_or(String::new(), |comment| format!("{} ", comment)); (comment_before_colon, comment_after_colon) @@ -2220,8 +2222,7 @@ impl Rewrite for ast::Param { span, shape, !has_multiple_attr_lines && !has_doc_comments, - ) - .unknown_error()?; + )?; if !is_empty_infer(&*self.ty, self.pat.span) { let (before_comment, after_comment) = @@ -2253,8 +2254,7 @@ impl Rewrite for ast::Param { span, shape, !has_multiple_attr_lines, - ) - .unknown_error()?; + )?; result.push_str(&before_comment); result.push_str(colon_spaces(context.config)); result.push_str(&after_comment); @@ -2301,8 +2301,7 @@ fn rewrite_explicit_self( span, shape, !has_multiple_attr_lines, - ) - .unknown_error()?) + )?) } None => Ok(combine_strs_with_missing_comments( context, @@ -2311,8 +2310,7 @@ fn rewrite_explicit_self( span, shape, !has_multiple_attr_lines, - ) - .unknown_error()?), + )?), } } ast::SelfKind::Explicit(ref ty, mutability) => { @@ -2328,8 +2326,7 @@ fn rewrite_explicit_self( span, shape, !has_multiple_attr_lines, - ) - .unknown_error()?) + )?) } ast::SelfKind::Value(mutability) => Ok(combine_strs_with_missing_comments( context, @@ -2338,8 +2335,7 @@ fn rewrite_explicit_self( span, shape, !has_multiple_attr_lines, - ) - .unknown_error()?), + )?), } } @@ -2677,7 +2673,7 @@ fn rewrite_fn_base( context, last_line_width(&result), ) { - Some(ref missing_comment) if !missing_comment.is_empty() => { + Ok(ref missing_comment) if !missing_comment.is_empty() => { result.push_str(missing_comment); force_new_line_for_brace = true; } @@ -3201,12 +3197,13 @@ fn rewrite_comments_before_after_where( span_after_where: Span, shape: Shape, ) -> Option<(String, String)> { - let before_comment = rewrite_missing_comment(span_before_where, shape, context)?; + let before_comment = rewrite_missing_comment(span_before_where, shape, context).ok()?; let after_comment = rewrite_missing_comment( span_after_where, shape.block_indent(context.config.tab_spaces()), context, - )?; + ) + .ok()?; Some((before_comment, after_comment)) } @@ -3229,7 +3226,7 @@ fn format_header( .opt_span_before(mk_sp(vis.span.lo(), ident.span.hi()), item_name.trim()) { let missing_span = mk_sp(after_vis, before_item_name); - if let Some(result_with_comment) = combine_strs_with_missing_comments( + if let Ok(result_with_comment) = combine_strs_with_missing_comments( context, &result, item_name, @@ -3313,7 +3310,8 @@ fn format_generics( ), shape, context, - ), + ) + .ok(), ) }; // add missing comments @@ -3446,6 +3444,7 @@ impl Rewrite for ast::ForeignItem { shape, false, ) + .ok() } } @@ -3481,6 +3480,7 @@ fn rewrite_attrs( shape, allow_extend, ) + .ok() } /// Rewrite an inline mod. diff --git a/src/lists.rs b/src/lists.rs index 46d40fa750e..f9e722130cd 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -8,7 +8,7 @@ use rustc_span::BytePos; use crate::comment::{find_comment_end, rewrite_comment, FindUncommented}; use crate::config::lists::*; use crate::config::{Config, IndentStyle}; -use crate::rewrite::{RewriteContext, RewriteError, RewriteErrorExt, RewriteResult}; +use crate::rewrite::{RewriteContext, RewriteError, RewriteResult}; use crate::shape::{Indent, Shape}; use crate::utils::{ count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline, @@ -366,8 +366,8 @@ where // Block style in non-vertical mode. let block_mode = tactic == DefinitiveListTactic::Horizontal; // Width restriction is only relevant in vertical mode. - let comment = rewrite_comment(comment, block_mode, formatting.shape, formatting.config) - .unknown_error()?; + let comment = + rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?; result.push_str(&comment); if !inner_item.is_empty() { @@ -413,8 +413,7 @@ where true, Shape::legacy(formatting.shape.width, Indent::empty()), formatting.config, - ) - .unknown_error()?; + )?; result.push(' '); result.push_str(&formatted_comment); @@ -465,8 +464,7 @@ where ) }; - let mut formatted_comment = - rewrite_post_comment(&mut item_max_width).unknown_error()?; + let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; if !starts_with_newline(comment) { if formatting.align_comments { @@ -479,8 +477,7 @@ where > formatting.config.max_width() { item_max_width = None; - formatted_comment = - rewrite_post_comment(&mut item_max_width).unknown_error()?; + formatted_comment = rewrite_post_comment(&mut item_max_width)?; comment_alignment = post_comment_alignment(item_max_width, unicode_str_width(inner_item)); } diff --git a/src/matches.rs b/src/matches.rs index 5cb34f54f6e..0a6fada5cb3 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -310,8 +310,7 @@ fn rewrite_match_arm( missing_span, shape, false, - ) - .unknown_error()?; + )?; let arrow_span = mk_sp( arm.pat.span.hi(), @@ -448,7 +447,7 @@ fn rewrite_match_body( if comment_str.is_empty() { String::new() } else { - rewrite_comment(comment_str, false, shape, context.config).unknown_error()? + rewrite_comment(comment_str, false, shape, context.config)? } }; diff --git a/src/missed_spans.rs b/src/missed_spans.rs index fc5daf71d16..4d947328bf7 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -284,13 +284,13 @@ impl<'a> FmtVisitor<'a> { let other_lines = &subslice[offset + 1..]; let comment_str = rewrite_comment(other_lines, false, comment_shape, self.config) - .unwrap_or_else(|| String::from(other_lines)); + .unwrap_or_else(|_| String::from(other_lines)); self.push_str(&comment_str); } } } else { let comment_str = rewrite_comment(subslice, false, comment_shape, self.config) - .unwrap_or_else(|| String::from(subslice)); + .unwrap_or_else(|_| String::from(subslice)); self.push_str(&comment_str); } diff --git a/src/patterns.rs b/src/patterns.rs index 6ec083443bd..f2fbb3c2439 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -133,7 +133,8 @@ impl Rewrite for Pat { mk_sp(lo, p.span.lo()), shape, true, - )? + ) + .ok()? } None => "".to_owned(), }; @@ -152,7 +153,8 @@ impl Rewrite for Pat { mk_sp(lo, hi), shape, true, - )?, + ) + .ok()?, ) } (false, true) => ( @@ -181,7 +183,8 @@ impl Rewrite for Pat { mk_sp(lo, hi), shape, true, - )?, + ) + .ok()?, ) } (false, true) => (first_lo, first), @@ -198,7 +201,8 @@ impl Rewrite for Pat { mk_sp(ident.span.hi(), hi), shape, true, - )? + ) + .ok()? } else { id_str.to_owned() }; @@ -211,6 +215,7 @@ impl Rewrite for Pat { shape, true, ) + .ok() } PatKind::Wild => { if 1 <= shape.width { @@ -408,6 +413,10 @@ fn rewrite_struct_pat( impl Rewrite for PatField { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + self.rewrite_result(context, shape).ok() + } + + fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { let hi_pos = if let Some(last) = self.attrs.last() { last.span.hi() } else { @@ -417,10 +426,10 @@ impl Rewrite for PatField { let attrs_str = if self.attrs.is_empty() { String::from("") } else { - self.attrs.rewrite(context, shape)? + self.attrs.rewrite_result(context, shape)? }; - let pat_str = self.pat.rewrite(context, shape)?; + let pat_str = self.pat.rewrite_result(context, shape)?; if self.is_shorthand { combine_strs_with_missing_comments( context, @@ -441,7 +450,7 @@ impl Rewrite for PatField { "{}:\n{}{}", id_str, nested_shape.indent.to_string(context.config), - self.pat.rewrite(context, nested_shape)? + self.pat.rewrite_result(context, nested_shape)? ) }; combine_strs_with_missing_comments( diff --git a/src/types.rs b/src/types.rs index 1c5a168b42e..676041ffa7a 100644 --- a/src/types.rs +++ b/src/types.rs @@ -713,8 +713,7 @@ impl Rewrite for ast::GenericParam { mk_sp(last_attr.span.hi(), param_start), shape, !last_attr.is_doc_comment(), - ) - .unknown_error()?; + )?; } else { // When rewriting generic params, an extra newline should be put // if the attributes end with a doc comment @@ -831,8 +830,7 @@ impl Rewrite for ast::Ty { before_lt_span, shape, true, - ) - .unknown_error()?; + )?; } else { result.push_str(<_str); } @@ -851,8 +849,7 @@ impl Rewrite for ast::Ty { before_mut_span, shape, true, - ) - .unknown_error()?; + )?; } else { result.push_str(mut_str); } @@ -868,8 +865,7 @@ impl Rewrite for ast::Ty { before_ty_span, shape, true, - ) - .unknown_error()?; + )?; } else { let used_width = last_line_width(&result); let budget = shape @@ -1182,8 +1178,7 @@ fn join_bounds_inner( is_bound_extendable(bound_str, item), combine_strs_with_missing_comments( context, joiner, bound_str, ls, shape, true, - ) - .unknown_error()?, + )?, ), _ => ( is_bound_extendable(bound_str, item), @@ -1200,7 +1195,6 @@ fn join_bounds_inner( shape, true, ) - .unknown_error() .map(|v| (v, trailing_span, extendable)), _ => Ok((strs + &trailing_str, trailing_span, extendable)), } diff --git a/src/vertical.rs b/src/vertical.rs index 670fa5a21e4..80c46da4620 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -24,7 +24,7 @@ use crate::utils::{ pub(crate) trait AlignedItem { fn skip(&self) -> bool; fn get_span(&self) -> Span; - fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option; + fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult; fn rewrite_aligned_item( &self, context: &RewriteContext<'_>, @@ -42,15 +42,15 @@ impl AlignedItem for ast::FieldDef { self.span() } - fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - let attrs_str = self.attrs.rewrite(context, shape)?; + fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { + let attrs_str = self.attrs.rewrite_result(context, shape)?; let missing_span = if self.attrs.is_empty() { mk_sp(self.span.lo(), self.span.lo()) } else { mk_sp(self.attrs.last().unwrap().span.hi(), self.span.lo()) }; let attrs_extendable = self.ident.is_none() && is_attributes_extendable(&attrs_str); - let field_str = rewrite_struct_field_prefix(context, self).ok()?; + let field_str = rewrite_struct_field_prefix(context, self)?; combine_strs_with_missing_comments( context, &attrs_str, @@ -80,8 +80,8 @@ impl AlignedItem for ast::ExprField { self.span() } - fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - let attrs_str = self.attrs.rewrite(context, shape)?; + fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult { + let attrs_str = self.attrs.rewrite_result(context, shape)?; let name = rewrite_ident(context, self.ident); let missing_span = if self.attrs.is_empty() { mk_sp(self.span.lo(), self.span.lo()) @@ -198,7 +198,7 @@ fn struct_field_prefix_max_min_width( .rewrite_prefix(context, shape) .map(|field_str| trimmed_last_line_width(&field_str)) }) - .fold_options((0, ::std::usize::MAX), |(max_len, min_len), len| { + .fold_ok((0, ::std::usize::MAX), |(max_len, min_len), len| { (cmp::max(max_len, len), cmp::min(min_len, len)) }) .unwrap_or((0, 0)) diff --git a/src/visitor.rs b/src/visitor.rs index 0df3d16e0cb..b08aa35f8f8 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -312,8 +312,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let comment_str = rewrite_comment(other_lines, false, comment_shape, config); match comment_str { - Some(ref s) => self.push_str(s), - None => self.push_str(other_lines), + Ok(ref s) => self.push_str(s), + Err(_) => self.push_str(other_lines), } } } @@ -342,8 +342,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config); match comment_str { - Some(ref s) => self.push_str(s), - None => self.push_str(&sub_slice), + Ok(ref s) => self.push_str(s), + Err(_) => self.push_str(&sub_slice), } } }