Skip to content

Commit 1375cb1

Browse files
committed
impl rewrite_result for ControlFlow, Stmt, update rewrite_index
1 parent 4489061 commit 1375cb1

File tree

6 files changed

+99
-60
lines changed

6 files changed

+99
-60
lines changed

src/comment.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1703,12 +1703,11 @@ impl<'a> Iterator for CommentCodeSlices<'a> {
17031703
}
17041704

17051705
/// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1706-
/// (if it fits in the width/offset, else return `None`), else return `new`
17071706
pub(crate) fn recover_comment_removed(
17081707
new: String,
17091708
span: Span,
17101709
context: &RewriteContext<'_>,
1711-
) -> Option<String> {
1710+
) -> String {
17121711
let snippet = context.snippet(span);
17131712
if snippet != new && changed_comment_content(snippet, &new) {
17141713
// We missed some comments. Warn and keep the original text.
@@ -1722,9 +1721,9 @@ pub(crate) fn recover_comment_removed(
17221721
)],
17231722
);
17241723
}
1725-
Some(snippet.to_owned())
1724+
snippet.to_owned()
17261725
} else {
1727-
Some(new)
1726+
new
17281727
}
17291728
}
17301729

src/expr.rs

Lines changed: 49 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ pub(crate) fn format_expr(
275275
)
276276
.ok(),
277277
ast::ExprKind::Index(ref expr, ref index, _) => {
278-
rewrite_index(&**expr, &**index, context, shape)
278+
rewrite_index(&**expr, &**index, context, shape).ok()
279279
}
280280
ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
281281
&**expr,
@@ -432,7 +432,7 @@ pub(crate) fn format_expr(
432432
};
433433

434434
expr_rw
435-
.and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
435+
.and_then(|expr_str| Some(recover_comment_removed(expr_str, expr.span, context)))
436436
.and_then(|expr_str| {
437437
let attrs = outer_attributes(&expr.attrs);
438438
let attrs_str = attrs.rewrite(context, shape)?;
@@ -669,6 +669,7 @@ pub(crate) fn rewrite_cond(
669669
String::from("\n") + &shape.indent.block_only().to_string(context.config);
670670
control_flow
671671
.rewrite_cond(context, shape, &alt_block_sep)
672+
.ok()
672673
.map(|rw| rw.0)
673674
}),
674675
}
@@ -893,20 +894,24 @@ impl<'a> ControlFlow<'a> {
893894
expr: &ast::Expr,
894895
shape: Shape,
895896
offset: usize,
896-
) -> Option<String> {
897+
) -> RewriteResult {
897898
debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
898899

899-
let cond_shape = shape.offset_left(offset)?;
900+
let cond_shape = shape
901+
.offset_left(offset)
902+
.max_width_error(shape.width, expr.span)?;
900903
if let Some(pat) = self.pat {
904+
debug!("matcher {} connector {}", self.matcher, self.connector);
901905
let matcher = if self.matcher.is_empty() {
902906
self.matcher.to_owned()
903907
} else {
904908
format!("{} ", self.matcher)
905909
};
906910
let pat_shape = cond_shape
907-
.offset_left(matcher.len())?
908-
.sub_width(self.connector.len())?;
909-
let pat_string = pat.rewrite(context, pat_shape)?;
911+
.offset_left(matcher.len())
912+
.and_then(|s| s.sub_width(self.connector.len()))
913+
.max_width_error(cond_shape.width, pat.span)?;
914+
let pat_string = pat.rewrite_result(context, pat_shape)?;
910915
let comments_lo = context
911916
.snippet_provider
912917
.span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
@@ -920,14 +925,13 @@ impl<'a> ControlFlow<'a> {
920925
RhsTactics::Default,
921926
comments_span,
922927
true,
923-
)
924-
.ok();
928+
);
925929
}
926930

927-
let expr_rw = expr.rewrite(context, cond_shape);
931+
let expr_rw = expr.rewrite_result(context, cond_shape);
928932
// The expression may (partially) fit on the current line.
929933
// We do not allow splitting between `if` and condition.
930-
if self.keyword == "if" || expr_rw.is_some() {
934+
if self.keyword == "if" || expr_rw.is_ok() {
931935
return expr_rw;
932936
}
933937

@@ -936,7 +940,7 @@ impl<'a> ControlFlow<'a> {
936940
.block_indent(context.config.tab_spaces())
937941
.with_max_width(context.config);
938942
let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
939-
expr.rewrite(context, nested_shape)
943+
expr.rewrite_result(context, nested_shape)
940944
.map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
941945
}
942946

@@ -945,7 +949,7 @@ impl<'a> ControlFlow<'a> {
945949
context: &RewriteContext<'_>,
946950
shape: Shape,
947951
alt_block_sep: &str,
948-
) -> Option<(String, usize)> {
952+
) -> Result<(String, usize), RewriteError> {
949953
// Do not take the rhs overhead from the upper expressions into account
950954
// when rewriting pattern.
951955
let new_width = context.budget(shape.used_width());
@@ -956,7 +960,9 @@ impl<'a> ControlFlow<'a> {
956960
let constr_shape = if self.nested_if {
957961
// We are part of an if-elseif-else chain. Our constraints are tightened.
958962
// 7 = "} else " .len()
959-
fresh_shape.offset_left(7)?
963+
fresh_shape
964+
.offset_left(7)
965+
.max_width_error(fresh_shape.width, self.span)?
960966
} else {
961967
fresh_shape
962968
};
@@ -992,7 +998,7 @@ impl<'a> ControlFlow<'a> {
992998

993999
if let Some(cond_str) = trial {
9941000
if cond_str.len() <= context.config.single_line_if_else_max_width() {
995-
return Some((cond_str, 0));
1001+
return Ok((cond_str, 0));
9961002
}
9971003
}
9981004
}
@@ -1045,7 +1051,7 @@ impl<'a> ControlFlow<'a> {
10451051
label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
10461052
};
10471053

1048-
Some((
1054+
Ok((
10491055
format!(
10501056
"{}{}{}{}{}",
10511057
label_string,
@@ -1111,13 +1117,17 @@ pub(crate) fn rewrite_else_kw_with_comments(
11111117

11121118
impl<'a> Rewrite for ControlFlow<'a> {
11131119
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1120+
self.rewrite_result(context, shape).ok()
1121+
}
1122+
1123+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
11141124
debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
11151125

11161126
let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
11171127
let (cond_str, used_width) = self.rewrite_cond(context, shape, alt_block_sep)?;
11181128
// If `used_width` is 0, it indicates that whole control flow is written in a single line.
11191129
if used_width == 0 {
1120-
return Some(cond_str);
1130+
return Ok(cond_str);
11211131
}
11221132

11231133
let block_width = shape.width.saturating_sub(used_width);
@@ -1135,8 +1145,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11351145
let block_str = {
11361146
let old_val = context.is_if_else_block.replace(self.else_block.is_some());
11371147
let result =
1138-
rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true)
1139-
.ok();
1148+
rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
11401149
context.is_if_else_block.replace(old_val);
11411150
result?
11421151
};
@@ -1162,7 +1171,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11621171
true,
11631172
mk_sp(else_block.span.lo(), self.span.hi()),
11641173
)
1165-
.rewrite(context, shape)
1174+
.rewrite_result(context, shape)
11661175
}
11671176
_ => {
11681177
last_in_chain = true;
@@ -1173,6 +1182,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11731182
..shape
11741183
};
11751184
format_expr(else_block, ExprType::Statement, context, else_shape)
1185+
.unknown_error()
11761186
}
11771187
};
11781188

@@ -1187,7 +1197,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11871197
result.push_str(&rewrite?);
11881198
}
11891199

1190-
Some(result)
1200+
Ok(result)
11911201
}
11921202
}
11931203

@@ -1564,8 +1574,8 @@ fn rewrite_index(
15641574
index: &ast::Expr,
15651575
context: &RewriteContext<'_>,
15661576
shape: Shape,
1567-
) -> Option<String> {
1568-
let expr_str = expr.rewrite(context, shape)?;
1577+
) -> RewriteResult {
1578+
let expr_str = expr.rewrite_result(context, shape)?;
15691579

15701580
let offset = last_line_width(&expr_str) + 1;
15711581
let rhs_overhead = shape.rhs_overhead(context.config);
@@ -1580,37 +1590,42 @@ fn rewrite_index(
15801590
.and_then(|shape| shape.sub_width(1)),
15811591
IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
15821592
}
1583-
};
1584-
let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1593+
}
1594+
.max_width_error(shape.width, index.span());
1595+
let orig_index_rw = index_shape.and_then(|s| index.rewrite_result(context, s));
15851596

15861597
// Return if index fits in a single line.
15871598
match orig_index_rw {
1588-
Some(ref index_str) if !index_str.contains('\n') => {
1589-
return Some(format!("{expr_str}[{index_str}]"));
1599+
Ok(ref index_str) if !index_str.contains('\n') => {
1600+
return Ok(format!("{expr_str}[{index_str}]"));
15901601
}
15911602
_ => (),
15921603
}
15931604

15941605
// Try putting index on the next line and see if it fits in a single line.
15951606
let indent = shape.indent.block_indent(context.config);
1596-
let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1597-
let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1598-
let new_index_rw = index.rewrite(context, index_shape);
1607+
let index_shape = Shape::indented(indent, context.config)
1608+
.offset_left(1)
1609+
.max_width_error(shape.width, index.span())?;
1610+
let index_shape = index_shape
1611+
.sub_width(1 + rhs_overhead)
1612+
.max_width_error(index_shape.width, index.span())?;
1613+
let new_index_rw = index.rewrite_result(context, index_shape);
15991614
match (orig_index_rw, new_index_rw) {
1600-
(_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1615+
(_, Ok(ref new_index_str)) if !new_index_str.contains('\n') => Ok(format!(
16011616
"{}{}[{}]",
16021617
expr_str,
16031618
indent.to_string_with_newline(context.config),
16041619
new_index_str,
16051620
)),
1606-
(None, Some(ref new_index_str)) => Some(format!(
1621+
(Err(_), Ok(ref new_index_str)) => Ok(format!(
16071622
"{}{}[{}]",
16081623
expr_str,
16091624
indent.to_string_with_newline(context.config),
16101625
new_index_str,
16111626
)),
1612-
(Some(ref index_str), _) => Some(format!("{expr_str}[{index_str}]")),
1613-
_ => None,
1627+
(Ok(ref index_str), _) => Ok(format!("{expr_str}[{index_str}]")),
1628+
(Err(_), Err(new_index_rw_err)) => Err(new_index_rw_err),
16141629
}
16151630
}
16161631

src/items.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2074,7 +2074,7 @@ fn rewrite_static(
20742074
true,
20752075
)
20762076
.ok()
2077-
.and_then(|res| recover_comment_removed(res, static_parts.span, context))
2077+
.and_then(|res| Some(recover_comment_removed(res, static_parts.span, context)))
20782078
.map(|s| if s.ends_with(';') { s } else { s + ";" })
20792079
} else {
20802080
Some(format!("{prefix}{ty_str};"))

src/overflow.rs

Lines changed: 7 additions & 4 deletions
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, RewriteResult};
22+
use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
2323
use crate::shape::Shape;
2424
use crate::source_map::SpanUtils;
2525
use crate::spanned::Spanned;
@@ -90,6 +90,10 @@ impl<'a> Rewrite for OverflowableItem<'a> {
9090
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
9191
self.map(|item| item.rewrite(context, shape))
9292
}
93+
94+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
95+
self.map(|item| item.rewrite_result(context, shape))
96+
}
9397
}
9498

9599
impl<'a> Spanned for OverflowableItem<'a> {
@@ -617,7 +621,7 @@ impl<'a> Context<'a> {
617621
tactic
618622
}
619623

620-
fn rewrite_items(&self) -> Option<(bool, String)> {
624+
fn rewrite_items(&self) -> Result<(bool, String), RewriteError> {
621625
let span = self.items_span();
622626
debug!("items: {:?}", self.items);
623627

@@ -661,7 +665,6 @@ impl<'a> Context<'a> {
661665
.ends_with_newline(ends_with_newline);
662666

663667
write_list(&list_items, &fmt)
664-
.ok()
665668
.map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str))
666669
}
667670

@@ -718,7 +721,7 @@ impl<'a> Context<'a> {
718721
}
719722

720723
fn rewrite(&self, shape: Shape) -> RewriteResult {
721-
let (extendable, items_str) = self.rewrite_items().unknown_error()?;
724+
let (extendable, items_str) = self.rewrite_items()?;
722725

723726
// If we are using visual indent style and failed to format, retry with block indent.
724727
if !self.context.use_block_indent()

src/stmt.rs

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_span::Span;
44
use crate::comment::recover_comment_removed;
55
use crate::config::StyleEdition;
66
use crate::expr::{format_expr, is_simple_block, ExprType};
7-
use crate::rewrite::{Rewrite, RewriteContext};
7+
use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
88
use crate::shape::Shape;
99
use crate::source_map::LineRangeUtils;
1010
use crate::spanned::Spanned;
@@ -90,6 +90,14 @@ impl<'a> Stmt<'a> {
9090

9191
impl<'a> Rewrite for Stmt<'a> {
9292
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
93+
self.rewrite_result(context, shape).ok()
94+
}
95+
96+
fn rewrite_result(
97+
&self,
98+
context: &RewriteContext<'_>,
99+
shape: Shape,
100+
) -> crate::rewrite::RewriteResult {
93101
let expr_type =
94102
if context.config.style_edition() >= StyleEdition::Edition2024 && self.is_last_expr() {
95103
ExprType::SubExpression
@@ -112,22 +120,28 @@ fn format_stmt(
112120
stmt: &ast::Stmt,
113121
expr_type: ExprType,
114122
is_last_expr: bool,
115-
) -> Option<String> {
116-
skip_out_of_file_lines_range!(context, stmt.span());
123+
) -> RewriteResult {
124+
skip_out_of_file_lines_range_err!(context, stmt.span());
117125

118126
let result = match stmt.kind {
119-
ast::StmtKind::Let(ref local) => local.rewrite(context, shape),
127+
ast::StmtKind::Let(ref local) => local.rewrite_result(context, shape),
120128
ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
121129
let suffix = if semicolon_for_stmt(context, stmt, is_last_expr) {
122130
";"
123131
} else {
124132
""
125133
};
126134

127-
let shape = shape.sub_width(suffix.len())?;
128-
format_expr(ex, expr_type, context, shape).map(|s| s + suffix)
135+
let shape = shape
136+
.sub_width(suffix.len())
137+
.max_width_error(shape.width, ex.span())?;
138+
format_expr(ex, expr_type, context, shape)
139+
.map(|s| s + suffix)
140+
.unknown_error()
141+
}
142+
ast::StmtKind::MacCall(..) | ast::StmtKind::Item(..) | ast::StmtKind::Empty => {
143+
Err(RewriteError::Unknown)
129144
}
130-
ast::StmtKind::MacCall(..) | ast::StmtKind::Item(..) | ast::StmtKind::Empty => None,
131145
};
132-
result.and_then(|res| recover_comment_removed(res, stmt.span(), context))
146+
result.map(|res| recover_comment_removed(res, stmt.span(), context))
133147
}

0 commit comments

Comments
 (0)