Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

impl rewrite_result for Pat, TuplePatField #6262

Merged
merged 1 commit into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 28 additions & 22 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 113,7 @@ pub(crate) fn format_expr(
})
.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) => {
let ast::StructExpr {
qself,
Expand Down Expand Up @@ -213,14 213,14 @@ pub(crate) fn format_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 {
Some(format!("break{id_str}"))
}
}
ast::ExprKind::Yield(ref 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 {
Some("yield".to_string())
}
Expand Down Expand Up @@ -253,15 253,17 @@ pub(crate) fn format_expr(
}
ast::ExprKind::Ret(None) => Some("return".to_owned()),
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(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) => {
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(
&**expr,
Expand Down Expand Up @@ -344,15 346,15 @@ 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).ok()
}
(Some(lhs), None) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {delim}")
} else {
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()),
}
Expand Down Expand Up @@ -1970,39 1972,43 @@ 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<'_>,
prefix: &str,
rewrite: &R,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
let shape = shape
.offset_left(prefix.len())
.max_width_error(shape.width, rewrite.span())?;
rewrite
.rewrite(context, shape.offset_left(prefix.len())?)
.rewrite_result(context, shape)
.map(|r| format!("{}{}", prefix, r))
}

// FIXME: this is probably not correct for multi-line Rewrites. we should
// 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<'_>,
suffix: &str,
rewrite: &R,
shape: Shape,
) -> Option<String> {
rewrite
.rewrite(context, shape.sub_width(suffix.len())?)
.map(|mut r| {
r.push_str(suffix);
r
})
) -> RewriteResult {
let shape = shape
.sub_width(suffix.len())
.max_width_error(shape.width, rewrite.span())?;
Comment on lines 1997 to 1999
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ytmimi Thank you! I addressed the nit, and rebased it

rewrite.rewrite_result(context, shape).map(|mut r| {
r.push_str(suffix);
r
})
}

fn rewrite_unary_op(
context: &RewriteContext<'_>,
op: ast::UnOp,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
// For some reason, an UnOp is not spanned like BinOp!
rewrite_unary_prefix(context, op.as_str(), expr, shape)
}
Expand Down Expand Up @@ -2257,7 2263,7 @@ fn rewrite_expr_addrof(
mutability: ast::Mutability,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
let operator_str = match (mutability, borrow_kind) {
(ast::Mutability::Not, ast::BorrowKind::Ref) => "&",
(ast::Mutability::Not, ast::BorrowKind::Raw) => "&raw const ",
Expand Down
102 changes: 59 additions & 43 deletions src/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 13,7 @@ use crate::lists::{
use crate::macros::{rewrite_macro, MacroPosition};
use crate::overflow;
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::source_map::SpanUtils;
use crate::spanned::Spanned;
Expand Down Expand Up @@ -81,12 81,16 @@ impl<'a> Rewrite for RangeOperand<'a> {

impl Rewrite for Pat {
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 {
PatKind::Or(ref pats) => {
let pat_strs = pats
.iter()
.map(|p| p.rewrite(context, shape))
.collect::<Option<Vec<_>>>()?;
.map(|p| p.rewrite_result(context, shape))
.collect::<Result<Vec<_>, RewriteError>>()?;

let use_mixed_layout = pats
.iter()
Expand All @@ -108,7 112,7 @@ impl Rewrite for Pat {
.separator(" |")
.separator_place(context.config.binop_separator())
.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::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => {
Expand All @@ -122,19 126,25 @@ impl Rewrite for Pat {
let sub_pat = match *sub_pat {
Some(ref p) => {
// 2 - `@ `.
let width = shape.width.checked_sub(
mut_prefix.len() ref_kw.len() mut_infix.len() id_str.len() 2,
)?;
let width = shape
.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, "@");
combine_strs_with_missing_comments(
context,
"@",
&p.rewrite(context, Shape::legacy(width, shape.indent))?,
&p.rewrite_result(context, Shape::legacy(width, shape.indent))?,
mk_sp(lo, p.span.lo()),
shape,
true,
)
.ok()?
)?
}
None => "".to_owned(),
};
Expand All @@ -153,8 163,7 @@ impl Rewrite for Pat {
mk_sp(lo, hi),
shape,
true,
)
.ok()?,
)?,
)
}
(false, true) => (
Expand Down Expand Up @@ -183,8 192,7 @@ impl Rewrite for Pat {
mk_sp(lo, hi),
shape,
true,
)
.ok()?,
)?,
)
}
(false, true) => (first_lo, first),
Expand All @@ -201,8 209,7 @@ impl Rewrite for Pat {
mk_sp(ident.span.hi(), hi),
shape,
true,
)
.ok()?
)?
} else {
id_str.to_owned()
};
Expand All @@ -215,23 222,28 @@ impl Rewrite for Pat {
shape,
true,
)
.ok()
}
PatKind::Wild => {
if 1 <= shape.width {
Some("_".to_owned())
Ok("_".to_owned())
} else {
None
Err(RewriteError::ExceedsMaxWidth {
configured_width: 1,
span: self.span,
})
}
}
PatKind::Rest => {
if 1 <= shape.width {
Some("..".to_owned())
Ok("..".to_owned())
} 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) => {
let infix = match end_kind.node {
RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
Expand Down Expand Up @@ -267,38 279,34 @@ impl Rewrite for Pat {
shape,
SeparatorPlace::Front,
)
.ok()
}
PatKind::Ref(ref pat, mutability) => {
let prefix = format!("&{}", format_mutability(mutability));
rewrite_unary_prefix(context, &prefix, &**pat, shape)
}
PatKind::Tuple(ref items) => {
rewrite_tuple_pat(items, None, self.span, context, shape).ok()
}
PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
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) => {
let path_str =
rewrite_path(context, PathContext::Expr, q_self, path, shape).ok()?;
rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape).ok()
let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?;
rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
}
PatKind::Lit(ref expr) => expr.rewrite(context, shape),
PatKind::Lit(ref expr) => expr.rewrite_result(context, shape),
PatKind::Slice(ref slice_pat)
if context.config.style_edition() <= StyleEdition::Edition2021 =>
{
let rw: Vec<String> = slice_pat
.iter()
.map(|p| {
if let Some(rw) = p.rewrite(context, shape) {
if let Ok(rw) = p.rewrite_result(context, shape) {
rw
} else {
context.snippet(p.span).to_string()
}
})
.collect();
Some(format!("[{}]", rw.join(", ")))
Ok(format!("[{}]", rw.join(", ")))
}
PatKind::Slice(ref slice_pat) => overflow::rewrite_with_square_brackets(
context,
Expand All @@ -308,8 316,7 @@ impl Rewrite for Pat {
self.span,
None,
None,
)
.ok(),
),
PatKind::Struct(ref qself, ref path, ref fields, rest) => rewrite_struct_pat(
qself,
path,
Expand All @@ -318,16 325,21 @@ impl Rewrite for Pat {
self.span,
context,
shape,
)
.ok(),
),
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
.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)),
PatKind::Err(_) => None,
PatKind::Deref(_) => None,
PatKind::Err(_) => Err(RewriteError::Unknown),
PatKind::Deref(_) => Err(RewriteError::Unknown),
}
}
}
Expand Down Expand Up @@ -473,9 485,13 @@ pub(crate) enum TuplePatField<'a> {

impl<'a> Rewrite for TuplePatField<'a> {
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 {
TuplePatField::Pat(p) => p.rewrite(context, shape),
TuplePatField::Dotdot(_) => Some("..".to_string()),
TuplePatField::Pat(p) => p.rewrite_result(context, shape),
TuplePatField::Dotdot(_) => Ok("..".to_string()),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 802,7 @@ impl Rewrite for ast::Ty {
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) => {
let mut_str = format_mutability(mt.mutbl);
Expand Down
Loading