impl rewrite_result for Pat, TuplePatField

- also update rewrite_unary_*** to return RewriteResult
This commit is contained in:
ding-young 2024-08-01 15:22:34 +09:00 committed by Yacin Tmimi
parent 88944668fe
commit 40f5075269
3 changed files with 88 additions and 66 deletions

View File

@ -113,7 +113,7 @@ pub(crate) fn format_expr(
}) })
.ok() .ok()
} }
ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape), ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape).ok(),
ast::ExprKind::Struct(ref struct_expr) => { ast::ExprKind::Struct(ref struct_expr) => {
let ast::StructExpr { let ast::StructExpr {
qself, qself,
@ -213,14 +213,14 @@ pub(crate) fn format_expr(
}; };
if let Some(ref expr) = *opt_expr { if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape) rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape).ok()
} else { } else {
Some(format!("break{id_str}")) Some(format!("break{id_str}"))
} }
} }
ast::ExprKind::Yield(ref opt_expr) => { ast::ExprKind::Yield(ref opt_expr) => {
if let Some(ref expr) = *opt_expr { if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, "yield ", &**expr, shape) rewrite_unary_prefix(context, "yield ", &**expr, shape).ok()
} else { } else {
Some("yield".to_string()) Some("yield".to_string())
} }
@ -253,15 +253,17 @@ pub(crate) fn format_expr(
} }
ast::ExprKind::Ret(None) => Some("return".to_owned()), ast::ExprKind::Ret(None) => Some("return".to_owned()),
ast::ExprKind::Ret(Some(ref expr)) => { ast::ExprKind::Ret(Some(ref expr)) => {
rewrite_unary_prefix(context, "return ", &**expr, shape) rewrite_unary_prefix(context, "return ", &**expr, shape).ok()
}
ast::ExprKind::Become(ref expr) => {
rewrite_unary_prefix(context, "become ", &**expr, shape).ok()
} }
ast::ExprKind::Become(ref expr) => rewrite_unary_prefix(context, "become ", &**expr, shape),
ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()), ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
ast::ExprKind::Yeet(Some(ref expr)) => { ast::ExprKind::Yeet(Some(ref expr)) => {
rewrite_unary_prefix(context, "do yeet ", &**expr, shape) rewrite_unary_prefix(context, "do yeet ", &**expr, shape).ok()
} }
ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => { ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape) rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape).ok()
} }
ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair( ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
&**expr, &**expr,
@ -344,7 +346,7 @@ pub(crate) fn format_expr(
} else { } else {
default_sp_delim(None, Some(rhs)) default_sp_delim(None, Some(rhs))
}; };
rewrite_unary_prefix(context, &sp_delim, &*rhs, shape) rewrite_unary_prefix(context, &sp_delim, &*rhs, shape).ok()
} }
(Some(lhs), None) => { (Some(lhs), None) => {
let sp_delim = if context.config.spaces_around_ranges() { let sp_delim = if context.config.spaces_around_ranges() {
@ -352,7 +354,7 @@ pub(crate) fn format_expr(
} else { } else {
default_sp_delim(Some(lhs), None) default_sp_delim(Some(lhs), None)
}; };
rewrite_unary_suffix(context, &sp_delim, &*lhs, shape) rewrite_unary_suffix(context, &sp_delim, &*lhs, shape).ok()
} }
(None, None) => Some(delim.to_owned()), (None, None) => Some(delim.to_owned()),
} }
@ -1970,31 +1972,35 @@ pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
} }
} }
pub(crate) fn rewrite_unary_prefix<R: Rewrite>( pub(crate) fn rewrite_unary_prefix<R: Rewrite + Spanned>(
context: &RewriteContext<'_>, context: &RewriteContext<'_>,
prefix: &str, prefix: &str,
rewrite: &R, rewrite: &R,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> RewriteResult {
let shape = shape
.offset_left(prefix.len())
.max_width_error(shape.width, rewrite.span())?;
rewrite rewrite
.rewrite(context, shape.offset_left(prefix.len())?) .rewrite_result(context, shape)
.map(|r| format!("{}{}", prefix, r)) .map(|r| format!("{}{}", prefix, r))
} }
// FIXME: this is probably not correct for multi-line Rewrites. we should // FIXME: this is probably not correct for multi-line Rewrites. we should
// subtract suffix.len() from the last line budget, not the first! // subtract suffix.len() from the last line budget, not the first!
pub(crate) fn rewrite_unary_suffix<R: Rewrite>( pub(crate) fn rewrite_unary_suffix<R: Rewrite + Spanned>(
context: &RewriteContext<'_>, context: &RewriteContext<'_>,
suffix: &str, suffix: &str,
rewrite: &R, rewrite: &R,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> RewriteResult {
rewrite let shape = shape
.rewrite(context, shape.sub_width(suffix.len())?) .sub_width(suffix.len())
.map(|mut r| { .max_width_error(shape.width, rewrite.span())?;
r.push_str(suffix); rewrite.rewrite_result(context, shape).map(|mut r| {
r r.push_str(suffix);
}) r
})
} }
fn rewrite_unary_op( fn rewrite_unary_op(
@ -2002,7 +2008,7 @@ fn rewrite_unary_op(
op: ast::UnOp, op: ast::UnOp,
expr: &ast::Expr, expr: &ast::Expr,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> RewriteResult {
// For some reason, an UnOp is not spanned like BinOp! // For some reason, an UnOp is not spanned like BinOp!
rewrite_unary_prefix(context, op.as_str(), expr, shape) rewrite_unary_prefix(context, op.as_str(), expr, shape)
} }
@ -2257,7 +2263,7 @@ fn rewrite_expr_addrof(
mutability: ast::Mutability, mutability: ast::Mutability,
expr: &ast::Expr, expr: &ast::Expr,
shape: Shape, shape: Shape,
) -> Option<String> { ) -> RewriteResult {
let operator_str = match (mutability, borrow_kind) { let operator_str = match (mutability, borrow_kind) {
(ast::Mutability::Not, ast::BorrowKind::Ref) => "&", (ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
(ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ", (ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",

View File

@ -13,7 +13,7 @@ use crate::lists::{
use crate::macros::{rewrite_macro, MacroPosition}; use crate::macros::{rewrite_macro, MacroPosition};
use crate::overflow; use crate::overflow;
use crate::pairs::{rewrite_pair, PairParts}; use crate::pairs::{rewrite_pair, PairParts};
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult}; use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
use crate::shape::Shape; use crate::shape::Shape;
use crate::source_map::SpanUtils; use crate::source_map::SpanUtils;
use crate::spanned::Spanned; use crate::spanned::Spanned;
@ -81,12 +81,16 @@ impl<'a> Rewrite for RangeOperand<'a> {
impl Rewrite for Pat { impl Rewrite for Pat {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
self.rewrite_result(context, shape).ok()
}
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
match self.kind { match self.kind {
PatKind::Or(ref pats) => { PatKind::Or(ref pats) => {
let pat_strs = pats let pat_strs = pats
.iter() .iter()
.map(|p| p.rewrite(context, shape)) .map(|p| p.rewrite_result(context, shape))
.collect::<Option<Vec<_>>>()?; .collect::<Result<Vec<_>, RewriteError>>()?;
let use_mixed_layout = pats let use_mixed_layout = pats
.iter() .iter()
@ -108,7 +112,7 @@ impl Rewrite for Pat {
.separator(" |") .separator(" |")
.separator_place(context.config.binop_separator()) .separator_place(context.config.binop_separator())
.ends_with_newline(false); .ends_with_newline(false);
write_list(&items, &fmt).ok() write_list(&items, &fmt)
} }
PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => {
@ -122,19 +126,25 @@ impl Rewrite for Pat {
let sub_pat = match *sub_pat { let sub_pat = match *sub_pat {
Some(ref p) => { Some(ref p) => {
// 2 - `@ `. // 2 - `@ `.
let width = shape.width.checked_sub( let width = shape
mut_prefix.len() + ref_kw.len() + mut_infix.len() + id_str.len() + 2, .width
)?; .checked_sub(
mut_prefix.len()
+ ref_kw.len()
+ mut_infix.len()
+ id_str.len()
+ 2,
)
.max_width_error(shape.width, p.span())?;
let lo = context.snippet_provider.span_after(self.span, "@"); let lo = context.snippet_provider.span_after(self.span, "@");
combine_strs_with_missing_comments( combine_strs_with_missing_comments(
context, context,
"@", "@",
&p.rewrite(context, Shape::legacy(width, shape.indent))?, &p.rewrite_result(context, Shape::legacy(width, shape.indent))?,
mk_sp(lo, p.span.lo()), mk_sp(lo, p.span.lo()),
shape, shape,
true, true,
) )?
.ok()?
} }
None => "".to_owned(), None => "".to_owned(),
}; };
@ -153,8 +163,7 @@ impl Rewrite for Pat {
mk_sp(lo, hi), mk_sp(lo, hi),
shape, shape,
true, true,
) )?,
.ok()?,
) )
} }
(false, true) => ( (false, true) => (
@ -183,8 +192,7 @@ impl Rewrite for Pat {
mk_sp(lo, hi), mk_sp(lo, hi),
shape, shape,
true, true,
) )?,
.ok()?,
) )
} }
(false, true) => (first_lo, first), (false, true) => (first_lo, first),
@ -201,8 +209,7 @@ impl Rewrite for Pat {
mk_sp(ident.span.hi(), hi), mk_sp(ident.span.hi(), hi),
shape, shape,
true, true,
) )?
.ok()?
} else { } else {
id_str.to_owned() id_str.to_owned()
}; };
@ -215,23 +222,28 @@ impl Rewrite for Pat {
shape, shape,
true, true,
) )
.ok()
} }
PatKind::Wild => { PatKind::Wild => {
if 1 <= shape.width { if 1 <= shape.width {
Some("_".to_owned()) Ok("_".to_owned())
} else { } else {
None Err(RewriteError::ExceedsMaxWidth {
configured_width: 1,
span: self.span,
})
} }
} }
PatKind::Rest => { PatKind::Rest => {
if 1 <= shape.width { if 1 <= shape.width {
Some("..".to_owned()) Ok("..".to_owned())
} else { } else {
None Err(RewriteError::ExceedsMaxWidth {
configured_width: 1,
span: self.span,
})
} }
} }
PatKind::Never => None, PatKind::Never => Err(RewriteError::Unknown),
PatKind::Range(ref lhs, ref rhs, ref end_kind) => { PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
let infix = match end_kind.node { let infix = match end_kind.node {
RangeEnd::Included(RangeSyntax::DotDotDot) => "...", RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
@ -267,38 +279,34 @@ impl Rewrite for Pat {
shape, shape,
SeparatorPlace::Front, SeparatorPlace::Front,
) )
.ok()
} }
PatKind::Ref(ref pat, mutability) => { PatKind::Ref(ref pat, mutability) => {
let prefix = format!("&{}", format_mutability(mutability)); let prefix = format!("&{}", format_mutability(mutability));
rewrite_unary_prefix(context, &prefix, &**pat, shape) rewrite_unary_prefix(context, &prefix, &**pat, shape)
} }
PatKind::Tuple(ref items) => { PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
rewrite_tuple_pat(items, None, self.span, context, shape).ok()
}
PatKind::Path(ref q_self, ref path) => { PatKind::Path(ref q_self, ref path) => {
rewrite_path(context, PathContext::Expr, q_self, path, shape).ok() rewrite_path(context, PathContext::Expr, q_self, path, shape)
} }
PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => { PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
let path_str = let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?;
rewrite_path(context, PathContext::Expr, q_self, path, shape).ok()?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape).ok()
} }
PatKind::Lit(ref expr) => expr.rewrite(context, shape), PatKind::Lit(ref expr) => expr.rewrite_result(context, shape),
PatKind::Slice(ref slice_pat) PatKind::Slice(ref slice_pat)
if context.config.style_edition() <= StyleEdition::Edition2021 => if context.config.style_edition() <= StyleEdition::Edition2021 =>
{ {
let rw: Vec<String> = slice_pat let rw: Vec<String> = slice_pat
.iter() .iter()
.map(|p| { .map(|p| {
if let Some(rw) = p.rewrite(context, shape) { if let Ok(rw) = p.rewrite_result(context, shape) {
rw rw
} else { } else {
context.snippet(p.span).to_string() context.snippet(p.span).to_string()
} }
}) })
.collect(); .collect();
Some(format!("[{}]", rw.join(", "))) Ok(format!("[{}]", rw.join(", ")))
} }
PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets( PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
context, context,
@ -308,8 +316,7 @@ impl Rewrite for Pat {
self.span, self.span,
None, None,
None, None,
) ),
.ok(),
PatKind::Struct(ref qself, ref path, ref fields, rest) => rewrite_struct_pat( PatKind::Struct(ref qself, ref path, ref fields, rest) => rewrite_struct_pat(
qself, qself,
path, path,
@ -318,16 +325,21 @@ impl Rewrite for Pat {
self.span, self.span,
context, context,
shape, shape,
) ),
.ok(),
PatKind::MacCall(ref mac) => { PatKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Pat) rewrite_macro(mac, None, context, shape, MacroPosition::Pat).unknown_error()
} }
PatKind::Paren(ref pat) => pat PatKind::Paren(ref pat) => pat
.rewrite(context, shape.offset_left(1)?.sub_width(1)?) .rewrite_result(
context,
shape
.offset_left(1)
.and_then(|s| s.sub_width(1))
.max_width_error(shape.width, self.span)?,
)
.map(|inner_pat| format!("({})", inner_pat)), .map(|inner_pat| format!("({})", inner_pat)),
PatKind::Err(_) => None, PatKind::Err(_) => Err(RewriteError::Unknown),
PatKind::Deref(_) => None, PatKind::Deref(_) => Err(RewriteError::Unknown),
} }
} }
} }
@ -473,9 +485,13 @@ pub(crate) enum TuplePatField<'a> {
impl<'a> Rewrite for TuplePatField<'a> { impl<'a> Rewrite for TuplePatField<'a> {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
self.rewrite_result(context, shape).ok()
}
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
match *self { match *self {
TuplePatField::Pat(p) => p.rewrite(context, shape), TuplePatField::Pat(p) => p.rewrite_result(context, shape),
TuplePatField::Dotdot(_) => Some("..".to_string()), TuplePatField::Dotdot(_) => Ok("..".to_string()),
} }
} }
} }

View File

@ -802,7 +802,7 @@ impl Rewrite for ast::Ty {
Mutability::Not => "*const ", Mutability::Not => "*const ",
}; };
rewrite_unary_prefix(context, prefix, &*mt.ty, shape).unknown_error() rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
} }
ast::TyKind::Ref(ref lifetime, ref mt) => { ast::TyKind::Ref(ref lifetime, ref mt) => {
let mut_str = format_mutability(mt.mutbl); let mut_str = format_mutability(mt.mutbl);