Skip to content

Commit 4caeb34

Browse files
committed
refactor rewrite_array, pair, tuple, call
1 parent 1313d61 commit 4caeb34

File tree

10 files changed

+171
-103
lines changed

10 files changed

+171
-103
lines changed

src/attr.rs

+17-9
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::config::IndentStyle;
1111
use crate::expr::rewrite_literal;
1212
use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
1313
use crate::overflow;
14-
use crate::rewrite::{Rewrite, RewriteContext};
14+
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt};
1515
use crate::shape::Shape;
1616
use crate::source_map::SpanUtils;
1717
use crate::types::{rewrite_path, PathContext};
@@ -274,20 +274,27 @@ fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
274274

275275
impl Rewrite for ast::MetaItem {
276276
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
277-
Some(match self.kind {
277+
self.rewrite_result(context, shape).ok()
278+
}
279+
280+
fn rewrite_result(
281+
&self,
282+
context: &RewriteContext<'_>,
283+
shape: Shape,
284+
) -> crate::rewrite::RewriteResult {
285+
Ok(match self.kind {
278286
ast::MetaItemKind::Word => {
279-
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?
287+
rewrite_path(context, PathContext::Type, &None, &self.path, shape)?
280288
}
281289
ast::MetaItemKind::List(ref list) => {
282-
let path =
283-
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
290+
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
284291
let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span);
285292
overflow::rewrite_with_parens(
286293
context,
287294
&path,
288295
list.iter(),
289296
// 1 = "]"
290-
shape.sub_width(1)?,
297+
shape.sub_width(1).max_width_error(shape.width, self.span)?,
291298
self.span,
292299
context.config.attr_fn_like_width(),
293300
Some(if has_trailing_comma {
@@ -298,10 +305,11 @@ impl Rewrite for ast::MetaItem {
298305
)?
299306
}
300307
ast::MetaItemKind::NameValue(ref lit) => {
301-
let path =
302-
rewrite_path(context, PathContext::Type, &None, &self.path, shape).ok()?;
308+
let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
303309
// 3 = ` = `
304-
let lit_shape = shape.shrink_left(path.len() + 3)?;
310+
let lit_shape = shape
311+
.shrink_left(path.len() + 3)
312+
.max_width_error(shape.width, self.span)?;
305313
// `rewrite_literal` returns `None` when `lit` exceeds max
306314
// width. Since a literal is basically unformattable unless it
307315
// is a string literal (and only if `format_strings` is set),

src/chains.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ use crate::config::{IndentStyle, Version};
6666
use crate::expr::rewrite_call;
6767
use crate::lists::extract_pre_comment;
6868
use crate::macros::convert_try_mac;
69-
use crate::rewrite::{Rewrite, RewriteContext};
69+
use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteResult};
7070
use crate::shape::Shape;
7171
use crate::source_map::SpanUtils;
7272
use crate::utils::{
@@ -279,7 +279,8 @@ impl Rewrite for ChainItem {
279279
parens: false,
280280
} => expr.rewrite(context, shape)?,
281281
ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
282-
Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
282+
Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)
283+
.ok()?
283284
}
284285
ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)),
285286
ChainItemKind::TupleField(ident, nested) => format!(
@@ -326,14 +327,14 @@ impl ChainItem {
326327
span: Span,
327328
context: &RewriteContext<'_>,
328329
shape: Shape,
329-
) -> Option<String> {
330+
) -> RewriteResult {
330331
let type_str = if types.is_empty() {
331332
String::new()
332333
} else {
333334
let type_list = types
334335
.iter()
335-
.map(|ty| ty.rewrite(context, shape))
336-
.collect::<Option<Vec<_>>>()?;
336+
.map(|ty| ty.rewrite_result(context, shape))
337+
.collect::<Result<Vec<_>, RewriteError>>()?;
337338

338339
format!("::<{}>", type_list.join(", "))
339340
};

src/expr.rs

+36-24
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ pub(crate) fn format_expr(
7979
shape,
8080
choose_separator_tactic(context, expr.span),
8181
None,
82-
),
82+
)
83+
.ok(),
8384
ast::ExprKind::Lit(token_lit) => {
8485
if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
8586
Some(expr_rw)
@@ -94,21 +95,23 @@ pub(crate) fn format_expr(
9495
ast::ExprKind::Call(ref callee, ref args) => {
9596
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
9697
let callee_str = callee.rewrite(context, shape)?;
97-
rewrite_call(context, &callee_str, args, inner_span, shape)
98+
rewrite_call(context, &callee_str, args, inner_span, shape).ok()
9899
}
99100
ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
100101
ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
101102
// FIXME: format comments between operands and operator
102-
rewrite_all_pairs(expr, shape, context).or_else(|| {
103-
rewrite_pair(
104-
&**lhs,
105-
&**rhs,
106-
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
107-
context,
108-
shape,
109-
context.config.binop_separator(),
110-
)
111-
})
103+
rewrite_all_pairs(expr, shape, context)
104+
.or_else(|_| {
105+
rewrite_pair(
106+
&**lhs,
107+
&**rhs,
108+
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
109+
context,
110+
shape,
111+
context.config.binop_separator(),
112+
)
113+
})
114+
.ok()
112115
}
113116
ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
114117
ast::ExprKind::Struct(ref struct_expr) => {
@@ -131,7 +134,7 @@ pub(crate) fn format_expr(
131134
.ok()
132135
}
133136
ast::ExprKind::Tup(ref items) => {
134-
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
137+
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1).ok()
135138
}
136139
ast::ExprKind::Let(ref pat, ref expr, _span, _) => rewrite_let(context, shape, pat, expr),
137140
ast::ExprKind::If(..)
@@ -265,7 +268,8 @@ pub(crate) fn format_expr(
265268
context,
266269
shape,
267270
SeparatorPlace::Front,
268-
),
271+
)
272+
.ok(),
269273
ast::ExprKind::Index(ref expr, ref index, _) => {
270274
rewrite_index(&**expr, &**index, context, shape)
271275
}
@@ -276,7 +280,8 @@ pub(crate) fn format_expr(
276280
context,
277281
shape,
278282
SeparatorPlace::Back,
279-
),
283+
)
284+
.ok(),
280285
ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
281286
let delim = match limits {
282287
ast::RangeLimits::HalfOpen => "..",
@@ -329,6 +334,7 @@ pub(crate) fn format_expr(
329334
shape,
330335
context.config.binop_separator(),
331336
)
337+
.ok()
332338
}
333339
(None, Some(rhs)) => {
334340
let sp_delim = if context.config.spaces_around_ranges() {
@@ -442,7 +448,7 @@ pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
442448
shape: Shape,
443449
force_separator_tactic: Option<SeparatorTactic>,
444450
delim_token: Option<Delimiter>,
445-
) -> Option<String> {
451+
) -> RewriteResult {
446452
overflow::rewrite_with_square_brackets(
447453
context,
448454
name,
@@ -1346,7 +1352,7 @@ pub(crate) fn rewrite_call(
13461352
args: &[ptr::P<ast::Expr>],
13471353
span: Span,
13481354
shape: Shape,
1349-
) -> Option<String> {
1355+
) -> RewriteResult {
13501356
overflow::rewrite_with_parens(
13511357
context,
13521358
callee,
@@ -1830,21 +1836,27 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
18301836
span: Span,
18311837
shape: Shape,
18321838
is_singleton_tuple: bool,
1833-
) -> Option<String> {
1839+
) -> RewriteResult {
18341840
// In case of length 1, need a trailing comma
18351841
debug!("rewrite_tuple_in_visual_indent_style {:?}", shape);
18361842
if is_singleton_tuple {
18371843
// 3 = "(" + ",)"
1838-
let nested_shape = shape.sub_width(3)?.visual_indent(1);
1844+
let nested_shape = shape
1845+
.sub_width(3)
1846+
.max_width_error(shape.width, span)?
1847+
.visual_indent(1);
18391848
return items
18401849
.next()
18411850
.unwrap()
1842-
.rewrite(context, nested_shape)
1851+
.rewrite_result(context, nested_shape)
18431852
.map(|s| format!("({},)", s));
18441853
}
18451854

18461855
let list_lo = context.snippet_provider.span_after(span, "(");
1847-
let nested_shape = shape.sub_width(2)?.visual_indent(1);
1856+
let nested_shape = shape
1857+
.sub_width(2)
1858+
.max_width_error(shape.width, span)?
1859+
.visual_indent(1);
18481860
let items = itemize_list(
18491861
context.snippet_provider,
18501862
items,
@@ -1867,9 +1879,9 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
18671879
let fmt = ListFormatting::new(nested_shape, context.config)
18681880
.tactic(tactic)
18691881
.ends_with_newline(false);
1870-
let list_str = write_list(&item_vec, &fmt).ok()?;
1882+
let list_str = write_list(&item_vec, &fmt)?;
18711883

1872-
Some(format!("({list_str})"))
1884+
Ok(format!("({list_str})"))
18731885
}
18741886

18751887
fn rewrite_let(
@@ -1912,7 +1924,7 @@ pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>(
19121924
span: Span,
19131925
shape: Shape,
19141926
is_singleton_tuple: bool,
1915-
) -> Option<String> {
1927+
) -> RewriteResult {
19161928
debug!("rewrite_tuple {:?}", shape);
19171929
if context.use_block_indent() {
19181930
// We use the same rule as function calls for rewriting tuples.

src/items.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1646,7 +1646,8 @@ fn format_tuple_struct(
16461646
mk_sp(lo, span.hi()),
16471647
context.config.fn_call_width(),
16481648
None,
1649-
)?;
1649+
)
1650+
.ok()?;
16501651
}
16511652

16521653
if !where_clause_str.is_empty()
@@ -2912,7 +2913,7 @@ fn rewrite_generics(
29122913
}
29132914

29142915
let params = generics.params.iter();
2915-
overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2916+
overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span).ok()
29162917
}
29172918

29182919
fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {

src/macros.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@ fn rewrite_macro_inner(
283283
Some(SeparatorTactic::Never)
284284
},
285285
)
286+
.ok()
286287
.map(|rw| match position {
287288
MacroPosition::Item => format!("{};", rw),
288289
_ => rw,
@@ -316,7 +317,8 @@ fn rewrite_macro_inner(
316317
shape,
317318
force_trailing_comma,
318319
Some(original_style),
319-
)?;
320+
)
321+
.ok()?;
320322
let comma = match position {
321323
MacroPosition::Item => ";",
322324
_ => "",

src/overflow.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use crate::lists::{
1919
};
2020
use crate::macros::MacroArg;
2121
use crate::patterns::{can_be_overflowed_pat, TuplePatField};
22-
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt};
22+
use crate::rewrite::{Rewrite, RewriteContext, RewriteErrorExt, RewriteResult};
2323
use crate::shape::Shape;
2424
use crate::source_map::SpanUtils;
2525
use crate::spanned::Spanned;
@@ -277,7 +277,7 @@ pub(crate) fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>(
277277
span: Span,
278278
item_max_width: usize,
279279
force_separator_tactic: Option<SeparatorTactic>,
280-
) -> Option<String> {
280+
) -> RewriteResult {
281281
Context::new(
282282
context,
283283
items,
@@ -299,7 +299,7 @@ pub(crate) fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>(
299299
items: impl Iterator<Item = &'a T>,
300300
shape: Shape,
301301
span: Span,
302-
) -> Option<String> {
302+
) -> RewriteResult {
303303
Context::new(
304304
context,
305305
items,
@@ -323,7 +323,7 @@ pub(crate) fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>
323323
span: Span,
324324
force_separator_tactic: Option<SeparatorTactic>,
325325
delim_token: Option<Delimiter>,
326-
) -> Option<String> {
326+
) -> RewriteResult {
327327
let (lhs, rhs) = match delim_token {
328328
Some(Delimiter::Parenthesis) => ("(", ")"),
329329
Some(Delimiter::Brace) => ("{", "}"),
@@ -712,8 +712,8 @@ impl<'a> Context<'a> {
712712
result
713713
}
714714

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

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

729-
Some(self.wrap_items(&items_str, shape, extendable))
729+
Ok(self.wrap_items(&items_str, shape, extendable))
730730
}
731731
}
732732

0 commit comments

Comments
 (0)