Skip to content

return RewriteResult for rewrite_path & rewrite_struct_*** #6236

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

Merged
merged 2 commits into from
Jul 18, 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
8 changes: 5 additions & 3 deletions src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,11 @@ impl Rewrite for ast::MetaItem {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
Some(match self.kind {
ast::MetaItemKind::Word => {
rewrite_path(context, PathContext::Type, &None, &self.path, shape)?
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?
}
ast::MetaItemKind::List(ref list) => {
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
let path =
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span);
overflow::rewrite_with_parens(
context,
Expand All @@ -297,7 +298,8 @@ impl Rewrite for ast::MetaItem {
)?
}
ast::MetaItemKind::NameValue(ref lit) => {
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
let path =
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
// 3 = ` = `
let lit_shape = shape.shrink_left(path.len() + 3)?;
// `rewrite_literal` returns `None` when `lit` exceeds max
Expand Down
62 changes: 34 additions & 28 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pub(crate) fn format_expr(
expr.span,
shape,
)
.ok()
}
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
Expand Down Expand Up @@ -185,7 +186,7 @@ pub(crate) fn format_expr(
rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs, kind)
}
ast::ExprKind::Path(ref qself, ref path) => {
rewrite_path(context, PathContext::Expr, qself, path, shape)
rewrite_path(context, PathContext::Expr, qself, path, shape).ok()
}
ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
rewrite_assignment(context, lhs, rhs, None, shape)
Expand Down Expand Up @@ -1603,7 +1604,7 @@ fn rewrite_struct_lit<'a>(
attrs: &[ast::Attribute],
span: Span,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
debug!("rewrite_struct_lit: shape {:?}", shape);

enum StructLitField<'a> {
Expand All @@ -1613,20 +1614,21 @@ fn rewrite_struct_lit<'a>(
}

// 2 = " {".len()
let path_shape = shape.sub_width(2)?;
let path_shape = shape.sub_width(2).max_width_error(shape.width, span)?;
let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;

let has_base_or_rest = match struct_rest {
ast::StructRest::None if fields.is_empty() => return Some(format!("{path_str} {{}}")),
ast::StructRest::None if fields.is_empty() => return Ok(format!("{path_str} {{}}")),
ast::StructRest::Rest(_) if fields.is_empty() => {
return Some(format!("{path_str} {{ .. }}"));
return Ok(format!("{path_str} {{ .. }}"));
}
ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true,
_ => false,
};

// Foo { a: Foo } - indent is +3, width is -5.
let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)?;
let (h_shape, v_shape) = struct_lit_shape(shape, context, path_str.len() + 3, 2)
.max_width_error(shape.width, span)?;

let one_line_width = h_shape.map_or(0, |shape| shape.width);
let body_lo = context.snippet_provider.span_after(span, "{");
Expand All @@ -1639,7 +1641,8 @@ fn rewrite_struct_lit<'a>(
v_shape,
mk_sp(body_lo, span.hi()),
one_line_width,
)?
)
.unknown_error()?
} else {
let field_iter = fields.iter().map(StructLitField::Regular).chain(
match struct_rest {
Expand Down Expand Up @@ -1668,12 +1671,13 @@ fn rewrite_struct_lit<'a>(
let rewrite = |item: &StructLitField<'_>| match *item {
StructLitField::Regular(field) => {
// The 1 taken from the v_budget is for the comma.
rewrite_field(context, field, v_shape.sub_width(1)?, 0)
let v_shape = v_shape.sub_width(1)?;
rewrite_field(context, field, v_shape, 0).ok()
}
StructLitField::Base(expr) => {
// 2 = ..
expr.rewrite(context, v_shape.offset_left(2)?)
.map(|s| format!("..{}", s))
let v_shape = v_shape.sub_width(2)?;
expr.rewrite(context, v_shape).map(|s| format!("..{}", s))
}
StructLitField::Rest(_) => Some("..".to_owned()),
};
Expand Down Expand Up @@ -1705,12 +1709,12 @@ fn rewrite_struct_lit<'a>(
force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
);

write_list(&item_vec, &fmt)?
write_list(&item_vec, &fmt).unknown_error()?
};

let fields_str =
wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
Some(format!("{path_str} {{{fields_str}}}"))
Ok(format!("{path_str} {{{fields_str}}}"))

// FIXME if context.config.indent_style() == Visual, but we run out
// of space, we should fall back to BlockIndent.
Expand All @@ -1723,7 +1727,7 @@ pub(crate) fn wrap_struct_field(
shape: Shape,
nested_shape: Shape,
one_line_width: usize,
) -> Option<String> {
) -> RewriteResult {
let should_vertical = context.config.indent_style() == IndentStyle::Block
&& (fields_str.contains('\n')
|| !context.config.struct_lit_single_line()
Expand All @@ -1732,21 +1736,21 @@ pub(crate) fn wrap_struct_field(
let inner_attrs = &inner_attributes(attrs);
if inner_attrs.is_empty() {
if should_vertical {
Some(format!(
Ok(format!(
"{}{}{}",
nested_shape.indent.to_string_with_newline(context.config),
fields_str,
shape.indent.to_string_with_newline(context.config)
))
} else {
// One liner or visual indent.
Some(format!(" {fields_str} "))
Ok(format!(" {fields_str} "))
}
} else {
Some(format!(
Ok(format!(
"{}{}{}{}{}",
nested_shape.indent.to_string_with_newline(context.config),
inner_attrs.rewrite(context, shape)?,
inner_attrs.rewrite_result(context, shape)?,
nested_shape.indent.to_string_with_newline(context.config),
fields_str,
shape.indent.to_string_with_newline(context.config)
Expand All @@ -1763,38 +1767,40 @@ pub(crate) fn rewrite_field(
field: &ast::ExprField,
shape: Shape,
prefix_max_width: usize,
) -> Option<String> {
) -> RewriteResult {
if contains_skip(&field.attrs) {
return Some(context.snippet(field.span()).to_owned());
return Ok(context.snippet(field.span()).to_owned());
}
let mut attrs_str = field.attrs.rewrite(context, shape)?;
let mut attrs_str = field.attrs.rewrite_result(context, shape)?;
if !attrs_str.is_empty() {
attrs_str.push_str(&shape.indent.to_string_with_newline(context.config));
};
let name = context.snippet(field.ident.span);
if field.is_shorthand {
Some(attrs_str + name)
Ok(attrs_str + name)
} else {
let mut separator = String::from(struct_lit_field_separator(context.config));
for _ in 0..prefix_max_width.saturating_sub(name.len()) {
separator.push(' ');
}
let overhead = name.len() + separator.len();
let expr_shape = shape.offset_left(overhead)?;
let expr = field.expr.rewrite(context, expr_shape);
let expr_shape = shape
.offset_left(overhead)
.max_width_error(shape.width, field.span)?;
let expr = field.expr.rewrite_result(context, expr_shape);
let is_lit = matches!(field.expr.kind, ast::ExprKind::Lit(_));
match expr {
Some(ref e)
Ok(ref e)
if !is_lit && e.as_str() == name && context.config.use_field_init_shorthand() =>
{
Some(attrs_str + name)
Ok(attrs_str + name)
}
Some(e) => Some(format!("{attrs_str}{name}{separator}{e}")),
None => {
Ok(e) => Ok(format!("{attrs_str}{name}{separator}{e}")),
Err(_) => {
let expr_offset = shape.indent.block_indent(context.config);
let expr = field
.expr
.rewrite(context, Shape::indented(expr_offset, context.config));
.rewrite_result(context, Shape::indented(expr_offset, context.config));
expr.map(|s| {
format!(
"{}{}:\n{}{}",
Expand Down
23 changes: 13 additions & 10 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};
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::spanned::Spanned;
Expand Down Expand Up @@ -254,10 +254,11 @@ impl Rewrite for Pat {
}
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)
rewrite_path(context, PathContext::Expr, q_self, path, shape).ok()
}
PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => {
let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?;
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)
}
PatKind::Lit(ref expr) => expr.rewrite(context, shape),
Expand Down Expand Up @@ -291,7 +292,8 @@ impl Rewrite for Pat {
self.span,
context,
shape,
),
)
.ok(),
PatKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Pat)
}
Expand All @@ -312,20 +314,21 @@ fn rewrite_struct_pat(
span: Span,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
// 2 = ` {`
let path_shape = shape.sub_width(2)?;
let path_shape = shape.sub_width(2).max_width_error(shape.width, span)?;
let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?;

if fields.is_empty() && !ellipsis {
return Some(format!("{path_str} {{}}"));
return Ok(format!("{path_str} {{}}"));
}

let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };

// 3 = ` { `, 2 = ` }`.
let (h_shape, v_shape) =
struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)
.max_width_error(shape.width, span)?;

let items = itemize_list(
context.snippet_provider,
Expand All @@ -351,7 +354,7 @@ fn rewrite_struct_pat(
let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
let fmt = struct_lit_formatting(nested_shape, tactic, context, false);

let mut fields_str = write_list(&item_vec, &fmt)?;
let mut fields_str = write_list(&item_vec, &fmt).unknown_error()?;
let one_line_width = h_shape.map_or(0, |shape| shape.width);

let has_trailing_comma = fmt.needs_trailing_separator();
Expand Down Expand Up @@ -379,7 +382,7 @@ fn rewrite_struct_pat(

// ast::Pat doesn't have attrs so use &[]
let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
Some(format!("{path_str} {{{fields_str}}}"))
Ok(format!("{path_str} {{{fields_str}}}"))
}

impl Rewrite for PatField {
Expand Down
Loading
Loading