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 68ee602

Browse files
committedJun 29, 2024·
impl rewrite_result for AssocItemConstraintKind, GenericArg, GenericBound, Ty
1 parent adf8c0a commit 68ee602

File tree

1 file changed

+127
-67
lines changed

1 file changed

+127
-67
lines changed
 

‎src/types.rs

Lines changed: 127 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::lists::{
1717
use crate::macros::{rewrite_macro, MacroPosition};
1818
use crate::overflow;
1919
use crate::pairs::{rewrite_pair, PairParts};
20-
use crate::rewrite::{Rewrite, RewriteContext};
20+
use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
2121
use crate::shape::Shape;
2222
use crate::source_map::SpanUtils;
2323
use crate::spanned::Spanned;
@@ -209,12 +209,16 @@ impl Rewrite for ast::AssocItemConstraint {
209209

210210
impl Rewrite for ast::AssocItemConstraintKind {
211211
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
212+
self.rewrite_result(context, shape).ok()
213+
}
214+
215+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
212216
match self {
213217
ast::AssocItemConstraintKind::Equality { term } => match term {
214-
Term::Ty(ty) => ty.rewrite(context, shape),
215-
Term::Const(c) => c.rewrite(context, shape),
218+
Term::Ty(ty) => ty.rewrite_result(context, shape),
219+
Term::Const(c) => c.rewrite_result(context, shape),
216220
},
217-
ast::AssocItemConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
221+
ast::AssocItemConstraintKind::Bound { bounds } => bounds.rewrite_result(context, shape),
218222
}
219223
}
220224
}
@@ -286,7 +290,7 @@ fn format_function_type<'a, I>(
286290
span: Span,
287291
context: &RewriteContext<'_>,
288292
shape: Shape,
289-
) -> Option<String>
293+
) -> RewriteResult
290294
where
291295
I: ExactSizeIterator,
292296
<I as Iterator>::Item: Deref,
@@ -296,12 +300,12 @@ where
296300

297301
let ty_shape = match context.config.indent_style() {
298302
// 4 = " -> "
299-
IndentStyle::Block => shape.offset_left(4)?,
300-
IndentStyle::Visual => shape.block_left(4)?,
303+
IndentStyle::Block => shape.offset_left(4).max_width_error(shape.width, span)?,
304+
IndentStyle::Visual => shape.block_left(4).max_width_error(shape.width, span)?,
301305
};
302306
let output = match *output {
303307
FnRetTy::Ty(ref ty) => {
304-
let type_str = ty.rewrite(context, ty_shape)?;
308+
let type_str = ty.rewrite_result(context, ty_shape)?;
305309
format!(" -> {type_str}")
306310
}
307311
FnRetTy::Default(..) => String::new(),
@@ -314,7 +318,10 @@ where
314318
)
315319
} else {
316320
// 2 for ()
317-
let budget = shape.width.checked_sub(2)?;
321+
let budget = shape
322+
.width
323+
.checked_sub(2)
324+
.max_width_error(shape.width, span)?;
318325
// 1 for (
319326
let offset = shape.indent + 1;
320327
Shape::legacy(budget, offset)
@@ -327,7 +334,8 @@ where
327334
let list_hi = context.snippet_provider.span_before(span, ")");
328335
let comment = context
329336
.snippet_provider
330-
.span_to_snippet(mk_sp(list_lo, list_hi))?
337+
.span_to_snippet(mk_sp(list_lo, list_hi))
338+
.unknown_error()?
331339
.trim();
332340
let comment = if comment.starts_with("//") {
333341
format!(
@@ -367,7 +375,7 @@ where
367375
.trailing_separator(trailing_separator)
368376
.ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
369377
.preserve_newline(true);
370-
(write_list(&item_vec, &fmt)?, tactic)
378+
(write_list(&item_vec, &fmt).unknown_error()?, tactic)
371379
};
372380

373381
let args = if tactic == DefinitiveListTactic::Horizontal
@@ -384,9 +392,9 @@ where
384392
)
385393
};
386394
if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
387-
Some(format!("{args}{output}"))
395+
Ok(format!("{args}{output}"))
388396
} else {
389-
Some(format!(
397+
Ok(format!(
390398
"{}\n{}{}",
391399
args,
392400
list_shape.indent.to_string(context.config),
@@ -458,10 +466,14 @@ impl Rewrite for ast::WherePredicate {
458466

459467
impl Rewrite for ast::GenericArg {
460468
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
469+
self.rewrite_result(context, shape).ok()
470+
}
471+
472+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
461473
match *self {
462-
ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
463-
ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
464-
ast::GenericArg::Const(ref const_) => const_.rewrite(context, shape),
474+
ast::GenericArg::Lifetime(ref lt) => lt.rewrite_result(context, shape),
475+
ast::GenericArg::Type(ref ty) => ty.rewrite_result(context, shape),
476+
ast::GenericArg::Const(ref const_) => const_.rewrite_result(context, shape),
465477
}
466478
}
467479
}
@@ -496,7 +508,8 @@ fn rewrite_generic_args(
496508
data.span,
497509
context,
498510
shape,
499-
),
511+
)
512+
.ok(),
500513
_ => Some("".to_owned()),
501514
}
502515
}
@@ -538,6 +551,10 @@ impl Rewrite for ast::Lifetime {
538551

539552
impl Rewrite for ast::GenericBound {
540553
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
554+
self.rewrite_result(context, shape).ok()
555+
}
556+
557+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
541558
match *self {
542559
ast::GenericBound::Trait(
543560
ref poly_trait_ref,
@@ -558,13 +575,15 @@ impl Rewrite for ast::GenericBound {
558575
asyncness.push(' ');
559576
}
560577
let polarity = polarity.as_str();
561-
let shape = shape.offset_left(constness.len() + polarity.len())?;
578+
let shape = shape
579+
.offset_left(constness.len() + polarity.len())
580+
.max_width_error(shape.width, self.span())?;
562581
poly_trait_ref
563-
.rewrite(context, shape)
582+
.rewrite_result(context, shape)
564583
.map(|s| format!("{constness}{asyncness}{polarity}{s}"))
565584
.map(|s| if has_paren { format!("({})", s) } else { s })
566585
}
567-
ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
586+
ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite_result(context, shape),
568587
}
569588
}
570589
}
@@ -683,15 +702,29 @@ impl Rewrite for ast::TraitRef {
683702

684703
impl Rewrite for ast::Ty {
685704
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
705+
self.rewrite_result(context, shape).ok()
706+
}
707+
708+
fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
686709
match self.kind {
687710
ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
688711
// we have to consider 'dyn' keyword is used or not!!!
689712
let (shape, prefix) = match tobj_syntax {
690-
ast::TraitObjectSyntax::Dyn => (shape.offset_left(4)?, "dyn "),
691-
ast::TraitObjectSyntax::DynStar => (shape.offset_left(5)?, "dyn* "),
713+
ast::TraitObjectSyntax::Dyn => (
714+
shape
715+
.offset_left(4)
716+
.max_width_error(shape.width, self.span())?,
717+
"dyn ",
718+
),
719+
ast::TraitObjectSyntax::DynStar => (
720+
shape
721+
.offset_left(5)
722+
.max_width_error(shape.width, self.span())?,
723+
"dyn* ",
724+
),
692725
ast::TraitObjectSyntax::None => (shape, ""),
693726
};
694-
let mut res = bounds.rewrite(context, shape)?;
727+
let mut res = bounds.rewrite_result(context, shape)?;
695728
// We may have falsely removed a trailing `+` inside macro call.
696729
if context.inside_macro()
697730
&& bounds.len() == 1
@@ -700,15 +733,15 @@ impl Rewrite for ast::Ty {
700733
{
701734
res.push('+');
702735
}
703-
Some(format!("{prefix}{res}"))
736+
Ok(format!("{prefix}{res}"))
704737
}
705738
ast::TyKind::Ptr(ref mt) => {
706739
let prefix = match mt.mutbl {
707740
Mutability::Mut => "*mut ",
708741
Mutability::Not => "*const ",
709742
};
710743

711-
rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
744+
rewrite_unary_prefix(context, prefix, &*mt.ty, shape).unknown_error()
712745
}
713746
ast::TyKind::Ref(ref lifetime, ref mt) => {
714747
let mut_str = format_mutability(mt.mutbl);
@@ -719,8 +752,11 @@ impl Rewrite for ast::Ty {
719752
let mut cmnt_lo = ref_hi;
720753

721754
if let Some(ref lifetime) = *lifetime {
722-
let lt_budget = shape.width.checked_sub(2 + mut_len)?;
723-
let lt_str = lifetime.rewrite(
755+
let lt_budget = shape
756+
.width
757+
.checked_sub(2 + mut_len)
758+
.max_width_error(shape.width, self.span())?;
759+
let lt_str = lifetime.rewrite_result(
724760
context,
725761
Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
726762
)?;
@@ -733,7 +769,8 @@ impl Rewrite for ast::Ty {
733769
before_lt_span,
734770
shape,
735771
true,
736-
)?;
772+
)
773+
.unknown_error()?;
737774
} else {
738775
result.push_str(&lt_str);
739776
}
@@ -752,7 +789,8 @@ impl Rewrite for ast::Ty {
752789
before_mut_span,
753790
shape,
754791
true,
755-
)?;
792+
)
793+
.unknown_error()?;
756794
} else {
757795
result.push_str(mut_str);
758796
}
@@ -764,39 +802,47 @@ impl Rewrite for ast::Ty {
764802
result = combine_strs_with_missing_comments(
765803
context,
766804
result.trim_end(),
767-
&mt.ty.rewrite(context, shape)?,
805+
&mt.ty.rewrite_result(context, shape)?,
768806
before_ty_span,
769807
shape,
770808
true,
771-
)?;
809+
)
810+
.unknown_error()?;
772811
} else {
773812
let used_width = last_line_width(&result);
774-
let budget = shape.width.checked_sub(used_width)?;
775-
let ty_str = mt
776-
.ty
777-
.rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
813+
let budget = shape
814+
.width
815+
.checked_sub(used_width)
816+
.max_width_error(shape.width, self.span())?;
817+
let ty_str = mt.ty.rewrite_result(
818+
context,
819+
Shape::legacy(budget, shape.indent + used_width),
820+
)?;
778821
result.push_str(&ty_str);
779822
}
780823

781-
Some(result)
824+
Ok(result)
782825
}
783826
// FIXME: we drop any comments here, even though it's a silly place to put
784827
// comments.
785828
ast::TyKind::Paren(ref ty) => {
786829
if context.config.version() == Version::One
787830
|| context.config.indent_style() == IndentStyle::Visual
788831
{
789-
let budget = shape.width.checked_sub(2)?;
832+
let budget = shape
833+
.width
834+
.checked_sub(2)
835+
.max_width_error(shape.width, self.span())?;
790836
return ty
791-
.rewrite(context, Shape::legacy(budget, shape.indent + 1))
837+
.rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
792838
.map(|ty_str| format!("({})", ty_str));
793839
}
794840

795841
// 2 = ()
796842
if let Some(sh) = shape.sub_width(2) {
797-
if let Some(ref s) = ty.rewrite(context, sh) {
843+
if let Ok(ref s) = ty.rewrite_result(context, sh) {
798844
if !s.contains('\n') {
799-
return Some(format!("({s})"));
845+
return Ok(format!("({s})"));
800846
}
801847
}
802848
}
@@ -805,26 +851,30 @@ impl Rewrite for ast::Ty {
805851
let shape = shape
806852
.block_indent(context.config.tab_spaces())
807853
.with_max_width(context.config);
808-
let rw = ty.rewrite(context, shape)?;
809-
Some(format!(
854+
let rw = ty.rewrite_result(context, shape)?;
855+
Ok(format!(
810856
"({}{}{})",
811857
shape.to_string_with_newline(context.config),
812858
rw,
813859
indent_str
814860
))
815861
}
816862
ast::TyKind::Slice(ref ty) => {
817-
let budget = shape.width.checked_sub(4)?;
818-
ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
863+
let budget = shape
864+
.width
865+
.checked_sub(4)
866+
.max_width_error(shape.width, self.span())?;
867+
ty.rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
819868
.map(|ty_str| format!("[{}]", ty_str))
820869
}
821870
ast::TyKind::Tup(ref items) => {
822871
rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
872+
.unknown_error()
823873
}
824-
ast::TyKind::AnonStruct(..) => Some(context.snippet(self.span).to_owned()),
825-
ast::TyKind::AnonUnion(..) => Some(context.snippet(self.span).to_owned()),
874+
ast::TyKind::AnonStruct(..) => Ok(context.snippet(self.span).to_owned()),
875+
ast::TyKind::AnonUnion(..) => Ok(context.snippet(self.span).to_owned()),
826876
ast::TyKind::Path(ref q_self, ref path) => {
827-
rewrite_path(context, PathContext::Type, q_self, path, shape)
877+
rewrite_path(context, PathContext::Type, q_self, path, shape).unknown_error()
828878
}
829879
ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
830880
&**ty,
@@ -833,52 +883,57 @@ impl Rewrite for ast::Ty {
833883
context,
834884
shape,
835885
SeparatorPlace::Back,
836-
),
886+
)
887+
.unknown_error(),
837888
ast::TyKind::Infer => {
838889
if shape.width >= 1 {
839-
Some("_".to_owned())
890+
Ok("_".to_owned())
840891
} else {
841-
None
892+
Err(RewriteError::ExceedsMaxWidth {
893+
configured_width: shape.width,
894+
span: self.span(),
895+
})
842896
}
843897
}
844898
ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
845-
ast::TyKind::Never => Some(String::from("!")),
899+
ast::TyKind::Never => Ok(String::from("!")),
846900
ast::TyKind::MacCall(ref mac) => {
847-
rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
901+
rewrite_macro(mac, None, context, shape, MacroPosition::Expression).unknown_error()
848902
}
849-
ast::TyKind::ImplicitSelf => Some(String::from("")),
903+
ast::TyKind::ImplicitSelf => Ok(String::from("")),
850904
ast::TyKind::ImplTrait(_, ref it, ref captures) => {
851905
// FIXME(precise_capturing): Implement formatting.
852906
if captures.is_some() {
853-
return None;
907+
return Err(RewriteError::Unknown);
854908
}
855909
// Empty trait is not a parser error.
856910
if it.is_empty() {
857-
return Some("impl".to_owned());
911+
return Ok("impl".to_owned());
858912
}
859913
let rw = if context.config.version() == Version::One {
860-
it.rewrite(context, shape)
914+
it.rewrite_result(context, shape)
861915
} else {
862-
join_bounds(context, shape, it, false)
916+
join_bounds(context, shape, it, false).unknown_error()
863917
};
864918
rw.map(|it_str| {
865919
let space = if it_str.is_empty() { "" } else { " " };
866920
format!("impl{}{}", space, it_str)
867921
})
868922
}
869-
ast::TyKind::CVarArgs => Some("...".to_owned()),
870-
ast::TyKind::Dummy | ast::TyKind::Err(_) => Some(context.snippet(self.span).to_owned()),
923+
ast::TyKind::CVarArgs => Ok("...".to_owned()),
924+
ast::TyKind::Dummy | ast::TyKind::Err(_) => Ok(context.snippet(self.span).to_owned()),
871925
ast::TyKind::Typeof(ref anon_const) => rewrite_call(
872926
context,
873927
"typeof",
874928
&[anon_const.value.clone()],
875929
self.span,
876930
shape,
877-
),
931+
)
932+
.unknown_error(),
878933
ast::TyKind::Pat(ref ty, ref pat) => {
879-
let ty = ty.rewrite(context, shape)?;
880-
let pat = pat.rewrite(context, shape)?;
881-
Some(format!("{ty} is {pat}"))
934+
let ty = ty.rewrite_result(context, shape)?;
935+
let pat = pat.rewrite_result(context, shape)?;
936+
Ok(format!("{ty} is {pat}"))
882937
}
883938
}
884939
}
@@ -889,7 +944,7 @@ fn rewrite_bare_fn(
889944
span: Span,
890945
context: &RewriteContext<'_>,
891946
shape: Shape,
892-
) -> Option<String> {
947+
) -> RewriteResult {
893948
debug!("rewrite_bare_fn {:#?}", shape);
894949

895950
let mut result = String::with_capacity(128);
@@ -913,9 +968,14 @@ fn rewrite_bare_fn(
913968
result.push_str("fn");
914969

915970
let func_ty_shape = if context.use_block_indent() {
916-
shape.offset_left(result.len())?
971+
shape
972+
.offset_left(result.len())
973+
.max_width_error(shape.width, span)?
917974
} else {
918-
shape.visual_indent(result.len()).sub_width(result.len())?
975+
shape
976+
.visual_indent(result.len())
977+
.sub_width(result.len())
978+
.max_width_error(shape.width, span)?
919979
};
920980

921981
let rewrite = format_function_type(
@@ -929,7 +989,7 @@ fn rewrite_bare_fn(
929989

930990
result.push_str(&rewrite);
931991

932-
Some(result)
992+
Ok(result)
933993
}
934994

935995
fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {

0 commit comments

Comments
 (0)
Please sign in to comment.