Skip to content

Commit

Permalink
refactor rewrite_array, pair, tuple, call
Browse files Browse the repository at this point in the history
  • Loading branch information
ding-young authored and ytmimi committed Jul 26, 2024
1 parent 1313d61 commit e21c1e2
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 103 deletions.
26 changes: 17 additions & 9 deletions src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::types::{rewrite_path, PathContext};
Expand Down Expand Up @@ -274,20 +274,27 @@ fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {

impl Rewrite for ast::MetaItem {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
Some(match self.kind {
self.rewrite_result(context, shape).ok()
}

fn rewrite_result(
&self,
context: &RewriteContext<'_>,
shape: Shape,
) -> crate::rewrite::RewriteResult {
Ok(match self.kind {
ast::MetaItemKind::Word => {
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?
rewrite_path(context, PathContext::Type, &None, &self.path, shape)?
}
ast::MetaItemKind::List(ref list) => {
let path =
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span);
overflow::rewrite_with_parens(
context,
&path,
list.iter(),
// 1 = "]"
shape.sub_width(1)?,
shape.sub_width(1).max_width_error(shape.width, self.span)?,
self.span,
context.config.attr_fn_like_width(),
Some(if has_trailing_comma {
Expand All @@ -298,10 +305,11 @@ impl Rewrite for ast::MetaItem {
)?
}
ast::MetaItemKind::NameValue(ref lit) => {
let path =
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
// 3 = ` = `
let lit_shape = shape.shrink_left(path.len() + 3)?;
let lit_shape = shape
.shrink_left(path.len() + 3)
.max_width_error(shape.width, self.span)?;
// `rewrite_literal` returns `None` when `lit` exceeds max
// width. Since a literal is basically unformattable unless it
// is a string literal (and only if `format_strings` is set),
Expand Down
11 changes: 6 additions & 5 deletions src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ use crate::config::{IndentStyle, Version};
use crate::expr::rewrite_call;
use crate::lists::extract_pre_comment;
use crate::macros::convert_try_mac;
use crate::rewrite::{Rewrite, RewriteContext};
use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteResult};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::utils::{
Expand Down Expand Up @@ -279,7 +279,8 @@ impl Rewrite for ChainItem {
parens: false,
} => expr.rewrite(context, shape)?,
ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)
.ok()?
}
ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)),
ChainItemKind::TupleField(ident, nested) => format!(
Expand Down Expand Up @@ -326,14 +327,14 @@ impl ChainItem {
span: Span,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
let type_str = if types.is_empty() {
String::new()
} else {
let type_list = types
.iter()
.map(|ty| ty.rewrite(context, shape))
.collect::<Option<Vec<_>>>()?;
.map(|ty| ty.rewrite_result(context, shape))
.collect::<Result<Vec<_>, RewriteError>>()?;

format!("::<{}>", type_list.join(", "))
};
Expand Down
60 changes: 36 additions & 24 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ pub(crate) fn format_expr(
shape,
choose_separator_tactic(context, expr.span),
None,
),
)
.ok(),
ast::ExprKind::Lit(token_lit) => {
if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
Some(expr_rw)
Expand All @@ -94,21 +95,23 @@ pub(crate) fn format_expr(
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
let callee_str = callee.rewrite(context, shape)?;
rewrite_call(context, &callee_str, args, inner_span, 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::Binary(op, ref lhs, ref rhs) => {
// FIXME: format comments between operands and operator
rewrite_all_pairs(expr, shape, context).or_else(|| {
rewrite_pair(
&**lhs,
&**rhs,
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
context,
shape,
context.config.binop_separator(),
)
})
rewrite_all_pairs(expr, shape, context)
.or_else(|_| {
rewrite_pair(
&**lhs,
&**rhs,
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
context,
shape,
context.config.binop_separator(),
)
})
.ok()
}
ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
ast::ExprKind::Struct(ref struct_expr) => {
Expand All @@ -131,7 +134,7 @@ pub(crate) fn format_expr(
.ok()
}
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
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::If(..)
Expand Down Expand Up @@ -265,7 +268,8 @@ pub(crate) fn format_expr(
context,
shape,
SeparatorPlace::Front,
),
)
.ok(),
ast::ExprKind::Index(ref expr, ref index, _) => {
rewrite_index(&**expr, &**index, context, shape)
}
Expand All @@ -276,7 +280,8 @@ pub(crate) fn format_expr(
context,
shape,
SeparatorPlace::Back,
),
)
.ok(),
ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
let delim = match limits {
ast::RangeLimits::HalfOpen => "..",
Expand Down Expand Up @@ -329,6 +334,7 @@ pub(crate) fn format_expr(
shape,
context.config.binop_separator(),
)
.ok()
}
(None, Some(rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
Expand Down Expand Up @@ -442,7 +448,7 @@ pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
shape: Shape,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<Delimiter>,
) -> Option<String> {
) -> RewriteResult {
overflow::rewrite_with_square_brackets(
context,
name,
Expand Down Expand Up @@ -1346,7 +1352,7 @@ pub(crate) fn rewrite_call(
args: &[ptr::P<ast::Expr>],
span: Span,
shape: Shape,
) -> Option<String> {
) -> RewriteResult {
overflow::rewrite_with_parens(
context,
callee,
Expand Down Expand Up @@ -1830,21 +1836,27 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
span: Span,
shape: Shape,
is_singleton_tuple: bool,
) -> Option<String> {
) -> RewriteResult {
// In case of length 1, need a trailing comma
debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
if is_singleton_tuple {
// 3 = "(" + ",)"
let nested_shape = shape.sub_width(3)?.visual_indent(1);
let nested_shape = shape
.sub_width(3)
.max_width_error(shape.width, span)?
.visual_indent(1);
return items
.next()
.unwrap()
.rewrite(context, nested_shape)
.rewrite_result(context, nested_shape)
.map(|s| format!("({},)", s));
}

let list_lo = context.snippet_provider.span_after(span, "(");
let nested_shape = shape.sub_width(2)?.visual_indent(1);
let nested_shape = shape
.sub_width(2)
.max_width_error(shape.width, span)?
.visual_indent(1);
let items = itemize_list(
context.snippet_provider,
items,
Expand All @@ -1867,9 +1879,9 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
let fmt = ListFormatting::new(nested_shape, context.config)
.tactic(tactic)
.ends_with_newline(false);
let list_str = write_list(&item_vec, &fmt).ok()?;
let list_str = write_list(&item_vec, &fmt)?;

Some(format!("({list_str})"))
Ok(format!("({list_str})"))
}

fn rewrite_let(
Expand Down Expand Up @@ -1912,7 +1924,7 @@ pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
span: Span,
shape: Shape,
is_singleton_tuple: bool,
) -> Option<String> {
) -> RewriteResult {
debug!("rewrite_tuple {:?}", shape);
if context.use_block_indent() {
// We use the same rule as function calls for rewriting tuples.
Expand Down
5 changes: 3 additions & 2 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1646,7 +1646,8 @@ fn format_tuple_struct(
mk_sp(lo, span.hi()),
context.config.fn_call_width(),
None,
)?;
)
.ok()?;
}

if !where_clause_str.is_empty()
Expand Down Expand Up @@ -2912,7 +2913,7 @@ fn rewrite_generics(
}

let params = generics.params.iter();
overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span).ok()
}

fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
Expand Down
4 changes: 3 additions & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ fn rewrite_macro_inner(
Some(SeparatorTactic::Never)
},
)
.ok()
.map(|rw| match position {
MacroPosition::Item => format!("{};", rw),
_ => rw,
Expand Down Expand Up @@ -316,7 +317,8 @@ fn rewrite_macro_inner(
shape,
force_trailing_comma,
Some(original_style),
)?;
)
.ok()?;
let comma = match position {
MacroPosition::Item => ";",
_ => "",
Expand Down
14 changes: 7 additions & 7 deletions src/overflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::lists::{
};
use crate::macros::MacroArg;
use crate::patterns::{can_be_overflowed_pat, TuplePatField};
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt};
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::spanned::Spanned;
Expand Down Expand Up @@ -277,7 +277,7 @@ pub(crate) fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
span: Span,
item_max_width: usize,
force_separator_tactic: Option<SeparatorTactic>,
) -> Option<String> {
) -> RewriteResult {
Context::new(
context,
items,
Expand All @@ -299,7 +299,7 @@ pub(crate) fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
items: impl Iterator<Item = &'a T>,
shape: Shape,
span: Span,
) -> Option<String> {
) -> RewriteResult {
Context::new(
context,
items,
Expand All @@ -323,7 +323,7 @@ pub(crate) fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>
span: Span,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<Delimiter>,
) -> Option<String> {
) -> RewriteResult {
let (lhs, rhs) = match delim_token {
Some(Delimiter::Parenthesis) => ("(", ")"),
Some(Delimiter::Brace) => ("{", "}"),
Expand Down Expand Up @@ -712,8 +712,8 @@ impl<'a> Context<'a> {
result
}

fn rewrite(&self, shape: Shape) -> Option<String> {
let (extendable, items_str) = self.rewrite_items()?;
fn rewrite(&self, shape: Shape) -> RewriteResult {
let (extendable, items_str) = self.rewrite_items().unknown_error()?;

// If we are using visual indent style and failed to format, retry with block indent.
if !self.context.use_block_indent()
Expand All @@ -726,7 +726,7 @@ impl<'a> Context<'a> {
return result;
}

Some(self.wrap_items(&items_str, shape, extendable))
Ok(self.wrap_items(&items_str, shape, extendable))
}
}

Expand Down
Loading

0 comments on commit e21c1e2

Please sign in to comment.