Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 46711ea

Browse files
committedAug 27, 2024·
impl rewrite_result for ControlFlow, Stmt, update rewrite_index
1 parent 5ee4d3b commit 46711ea

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
@@ -278,7 +278,7 @@ pub(crate) fn format_expr(
278278
)
279279
.ok(),
280280
ast::ExprKind::Index(ref expr, ref index, _) => {
281-
rewrite_index(&**expr, &**index, context, shape)
281+
rewrite_index(&**expr, &**index, context, shape).ok()
282282
}
283283
ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
284284
&**expr,
@@ -435,7 +435,7 @@ pub(crate) fn format_expr(
435435
};
436436

437437
expr_rw
438-
.and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
438+
.and_then(|expr_str| Some(recover_comment_removed(expr_str, expr.span, context)))
439439
.and_then(|expr_str| {
440440
let attrs = outer_attributes(&expr.attrs);
441441
let attrs_str = attrs.rewrite(context, shape)?;
@@ -672,6 +672,7 @@ pub(crate) fn rewrite_cond(
672672
String::from("\n") + &shape.indent.block_only().to_string(context.config);
673673
control_flow
674674
.rewrite_cond(context, shape, &alt_block_sep)
675+
.ok()
675676
.map(|rw| rw.0)
676677
}),
677678
}
@@ -896,20 +897,24 @@ impl<'a> ControlFlow<'a> {
896897
expr: &ast::Expr,
897898
shape: Shape,
898899
offset: usize,
899-
) -> Option<String> {
900+
) -> RewriteResult {
900901
debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
901902

902-
let cond_shape = shape.offset_left(offset)?;
903+
let cond_shape = shape
904+
.offset_left(offset)
905+
.max_width_error(shape.width, expr.span)?;
903906
if let Some(pat) = self.pat {
907+
debug!("matcher {} connector {}", self.matcher, self.connector);
904908
let matcher = if self.matcher.is_empty() {
905909
self.matcher.to_owned()
906910
} else {
907911
format!("{} ", self.matcher)
908912
};
909913
let pat_shape = cond_shape
910-
.offset_left(matcher.len())?
911-
.sub_width(self.connector.len())?;
912-
let pat_string = pat.rewrite(context, pat_shape)?;
914+
.offset_left(matcher.len())
915+
.and_then(|s| s.sub_width(self.connector.len()))
916+
.max_width_error(cond_shape.width, pat.span)?;
917+
let pat_string = pat.rewrite_result(context, pat_shape)?;
913918
let comments_lo = context
914919
.snippet_provider
915920
.span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
@@ -923,14 +928,13 @@ impl<'a> ControlFlow<'a> {
923928
RhsTactics::Default,
924929
comments_span,
925930
true,
926-
)
927-
.ok();
931+
);
928932
}
929933

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

@@ -939,7 +943,7 @@ impl<'a> ControlFlow<'a> {
939943
.block_indent(context.config.tab_spaces())
940944
.with_max_width(context.config);
941945
let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
942-
expr.rewrite(context, nested_shape)
946+
expr.rewrite_result(context, nested_shape)
943947
.map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
944948
}
945949

@@ -948,7 +952,7 @@ impl<'a> ControlFlow<'a> {
948952
context: &RewriteContext<'_>,
949953
shape: Shape,
950954
alt_block_sep: &str,
951-
) -> Option<(String, usize)> {
955+
) -> Result<(String, usize), RewriteError> {
952956
// Do not take the rhs overhead from the upper expressions into account
953957
// when rewriting pattern.
954958
let new_width = context.budget(shape.used_width());
@@ -959,7 +963,9 @@ impl<'a> ControlFlow<'a> {
959963
let constr_shape = if self.nested_if {
960964
// We are part of an if-elseif-else chain. Our constraints are tightened.
961965
// 7 = "} else " .len()
962-
fresh_shape.offset_left(7)?
966+
fresh_shape
967+
.offset_left(7)
968+
.max_width_error(fresh_shape.width, self.span)?
963969
} else {
964970
fresh_shape
965971
};
@@ -995,7 +1001,7 @@ impl<'a> ControlFlow<'a> {
9951001

9961002
if let Some(cond_str) = trial {
9971003
if cond_str.len() <= context.config.single_line_if_else_max_width() {
998-
return Some((cond_str, 0));
1004+
return Ok((cond_str, 0));
9991005
}
10001006
}
10011007
}
@@ -1048,7 +1054,7 @@ impl<'a> ControlFlow<'a> {
10481054
label_string.len() + self.keyword.len() + pat_expr_string.len() + 2
10491055
};
10501056

1051-
Some((
1057+
Ok((
10521058
format!(
10531059
"{}{}{}{}{}",
10541060
label_string,
@@ -1114,13 +1120,17 @@ pub(crate) fn rewrite_else_kw_with_comments(
11141120

11151121
impl<'a> Rewrite for ControlFlow<'a> {
11161122
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1123+
self.rewrite_result(context, shape).ok()
1124+
}
1125+
1126+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
11171127
debug!("ControlFlow::rewrite {:?} {:?}", self, shape);
11181128

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

11261136
let block_width = shape.width.saturating_sub(used_width);
@@ -1138,8 +1148,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11381148
let block_str = {
11391149
let old_val = context.is_if_else_block.replace(self.else_block.is_some());
11401150
let result =
1141-
rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true)
1142-
.ok();
1151+
rewrite_block_with_visitor(context, "", self.block, None, None, block_shape, true);
11431152
context.is_if_else_block.replace(old_val);
11441153
result?
11451154
};
@@ -1165,7 +1174,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11651174
true,
11661175
mk_sp(else_block.span.lo(), self.span.hi()),
11671176
)
1168-
.rewrite(context, shape)
1177+
.rewrite_result(context, shape)
11691178
}
11701179
_ => {
11711180
last_in_chain = true;
@@ -1176,6 +1185,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11761185
..shape
11771186
};
11781187
format_expr(else_block, ExprType::Statement, context, else_shape)
1188+
.unknown_error()
11791189
}
11801190
};
11811191

@@ -1190,7 +1200,7 @@ impl<'a> Rewrite for ControlFlow<'a> {
11901200
result.push_str(&rewrite?);
11911201
}
11921202

1193-
Some(result)
1203+
Ok(result)
11941204
}
11951205
}
11961206

@@ -1567,8 +1577,8 @@ fn rewrite_index(
15671577
index: &ast::Expr,
15681578
context: &RewriteContext<'_>,
15691579
shape: Shape,
1570-
) -> Option<String> {
1571-
let expr_str = expr.rewrite(context, shape)?;
1580+
) -> RewriteResult {
1581+
let expr_str = expr.rewrite_result(context, shape)?;
15721582

15731583
let offset = last_line_width(&expr_str) + 1;
15741584
let rhs_overhead = shape.rhs_overhead(context.config);
@@ -1583,37 +1593,42 @@ fn rewrite_index(
15831593
.and_then(|shape| shape.sub_width(1)),
15841594
IndentStyle::Visual => shape.visual_indent(offset).sub_width(offset + 1),
15851595
}
1586-
};
1587-
let orig_index_rw = index_shape.and_then(|s| index.rewrite(context, s));
1596+
}
1597+
.max_width_error(shape.width, index.span());
1598+
let orig_index_rw = index_shape.and_then(|s| index.rewrite_result(context, s));
15881599

15891600
// Return if index fits in a single line.
15901601
match orig_index_rw {
1591-
Some(ref index_str) if !index_str.contains('\n') => {
1592-
return Some(format!("{expr_str}[{index_str}]"));
1602+
Ok(ref index_str) if !index_str.contains('\n') => {
1603+
return Ok(format!("{expr_str}[{index_str}]"));
15931604
}
15941605
_ => (),
15951606
}
15961607

15971608
// Try putting index on the next line and see if it fits in a single line.
15981609
let indent = shape.indent.block_indent(context.config);
1599-
let index_shape = Shape::indented(indent, context.config).offset_left(1)?;
1600-
let index_shape = index_shape.sub_width(1 + rhs_overhead)?;
1601-
let new_index_rw = index.rewrite(context, index_shape);
1610+
let index_shape = Shape::indented(indent, context.config)
1611+
.offset_left(1)
1612+
.max_width_error(shape.width, index.span())?;
1613+
let index_shape = index_shape
1614+
.sub_width(1 + rhs_overhead)
1615+
.max_width_error(index_shape.width, index.span())?;
1616+
let new_index_rw = index.rewrite_result(context, index_shape);
16021617
match (orig_index_rw, new_index_rw) {
1603-
(_, Some(ref new_index_str)) if !new_index_str.contains('\n') => Some(format!(
1618+
(_, Ok(ref new_index_str)) if !new_index_str.contains('\n') => Ok(format!(
16041619
"{}{}[{}]",
16051620
expr_str,
16061621
indent.to_string_with_newline(context.config),
16071622
new_index_str,
16081623
)),
1609-
(None, Some(ref new_index_str)) => Some(format!(
1624+
(Err(_), Ok(ref new_index_str)) => Ok(format!(
16101625
"{}{}[{}]",
16111626
expr_str,
16121627
indent.to_string_with_newline(context.config),
16131628
new_index_str,
16141629
)),
1615-
(Some(ref index_str), _) => Some(format!("{expr_str}[{index_str}]")),
1616-
_ => None,
1630+
(Ok(ref index_str), _) => Ok(format!("{expr_str}[{index_str}]")),
1631+
(Err(_), Err(new_index_rw_err)) => Err(new_index_rw_err),
16171632
}
16181633
}
16191634

‎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
}

‎src/types.rs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -480,8 +480,8 @@ impl Rewrite for ast::WherePredicate {
480480
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
481481
ref lifetime,
482482
ref bounds,
483-
..
484-
}) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
483+
span,
484+
}) => rewrite_bounded_lifetime(lifetime, bounds, span, context, shape).ok()?,
485485
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
486486
ref lhs_ty,
487487
ref rhs_ty,
@@ -552,23 +552,27 @@ fn rewrite_generic_args(
552552
fn rewrite_bounded_lifetime(
553553
lt: &ast::Lifetime,
554554
bounds: &[ast::GenericBound],
555+
span: Span,
555556
context: &RewriteContext<'_>,
556557
shape: Shape,
557-
) -> Option<String> {
558-
let result = lt.rewrite(context, shape)?;
558+
) -> RewriteResult {
559+
let result = lt.rewrite_result(context, shape)?;
559560

560561
if bounds.is_empty() {
561-
Some(result)
562+
Ok(result)
562563
} else {
563564
let colon = type_bound_colon(context);
564565
let overhead = last_line_width(&result) + colon.len();
566+
let shape = shape
567+
.sub_width(overhead)
568+
.max_width_error(shape.width, span)?;
565569
let result = format!(
566570
"{}{}{}",
567571
result,
568572
colon,
569-
join_bounds(context, shape.sub_width(overhead)?, bounds, true).ok()?
573+
join_bounds(context, shape, bounds, true)?
570574
);
571-
Some(result)
575+
Ok(result)
572576
}
573577
}
574578

@@ -579,8 +583,12 @@ impl Rewrite for ast::AnonConst {
579583
}
580584

581585
impl Rewrite for ast::Lifetime {
582-
fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
583-
Some(rewrite_ident(context, self.ident).to_owned())
586+
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
587+
self.rewrite_result(context, shape).ok()
588+
}
589+
590+
fn rewrite_result(&self, context: &RewriteContext<'_>, _: Shape) -> RewriteResult {
591+
Ok(rewrite_ident(context, self.ident).to_owned())
584592
}
585593
}
586594

0 commit comments

Comments
 (0)
Please sign in to comment.