1 use std
::iter
::ExactSizeIterator
;
4 use rustc_ast
::ast
::{self, FnRetTy, Mutability}
;
5 use rustc_span
::{symbol::kw, BytePos, Pos, Span}
;
7 use crate::comment
::{combine_strs_with_missing_comments, contains_comment}
;
8 use crate::config
::lists
::*;
9 use crate::config
::{IndentStyle, TypeDensity, Version}
;
11 format_expr
, rewrite_assign_rhs
, rewrite_call
, rewrite_tuple
, rewrite_unary_prefix
, ExprType
,
14 definitive_tactic
, itemize_list
, write_list
, ListFormatting
, ListItem
, Separator
,
16 use crate::macros
::{rewrite_macro, MacroPosition}
;
18 use crate::pairs
::{rewrite_pair, PairParts}
;
19 use crate::rewrite
::{Rewrite, RewriteContext}
;
20 use crate::shape
::Shape
;
21 use crate::source_map
::SpanUtils
;
22 use crate::spanned
::Spanned
;
24 colon_spaces
, extra_offset
, first_line_width
, format_extern
, format_mutability
,
25 last_line_extendable
, last_line_width
, mk_sp
, rewrite_ident
,
28 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
29 pub(crate) enum PathContext
{
35 // Does not wrap on simple segments.
36 pub(crate) fn rewrite_path(
37 context
: &RewriteContext
<'_
>,
38 path_context
: PathContext
,
39 qself
: Option
<&ast
::QSelf
>,
43 let skip_count
= qself
.map_or(0, |x
| x
.position
);
45 let mut result
= if path
.is_global() && qself
.is_none() && path_context
!= PathContext
::Import
{
51 let mut span_lo
= path
.span
.lo();
53 if let Some(qself
) = qself
{
56 let fmt_ty
= qself
.ty
.rewrite(context
, shape
)?
;
57 result
.push_str(&fmt_ty
);
60 result
.push_str(" as ");
61 if path
.is_global() && path_context
!= PathContext
::Import
{
62 result
.push_str("::");
66 let shape
= shape
.sub_width(3)?
;
68 result
= rewrite_path_segments(
71 path
.segments
.iter().take(skip_count
),
79 result
.push_str(">::");
80 span_lo
= qself
.ty
.span
.hi() + BytePos(1);
83 rewrite_path_segments(
86 path
.segments
.iter().skip(skip_count
),
94 fn rewrite_path_segments
<'a
, I
>(
95 path_context
: PathContext
,
100 context
: &RewriteContext
<'_
>,
104 I
: Iterator
<Item
= &'a ast
::PathSegment
>,
106 let mut first
= true;
107 let shape
= shape
.visual_indent(0);
109 for segment
in iter
{
110 // Indicates a global path, shouldn't be rendered.
111 if segment
.ident
.name
== kw
::PathRoot
{
117 buffer
.push_str("::");
120 let extra_offset
= extra_offset(&buffer
, shape
);
121 let new_shape
= shape
.shrink_left(extra_offset
)?
;
122 let segment_string
= rewrite_segment(
131 buffer
.push_str(&segment_string
);
138 pub(crate) enum SegmentParam
<'a
> {
139 Const(&'a ast
::AnonConst
),
140 LifeTime(&'a ast
::Lifetime
),
142 Binding(&'a ast
::AssocTyConstraint
),
145 impl<'a
> SegmentParam
<'a
> {
146 fn from_generic_arg(arg
: &ast
::GenericArg
) -> SegmentParam
<'_
> {
148 ast
::GenericArg
::Lifetime(ref lt
) => SegmentParam
::LifeTime(lt
),
149 ast
::GenericArg
::Type(ref ty
) => SegmentParam
::Type(ty
),
150 ast
::GenericArg
::Const(const_
) => SegmentParam
::Const(const_
),
155 impl<'a
> Spanned
for SegmentParam
<'a
> {
156 fn span(&self) -> Span
{
158 SegmentParam
::Const(const_
) => const_
.value
.span
,
159 SegmentParam
::LifeTime(lt
) => lt
.ident
.span
,
160 SegmentParam
::Type(ty
) => ty
.span
,
161 SegmentParam
::Binding(binding
) => binding
.span
,
166 impl<'a
> Rewrite
for SegmentParam
<'a
> {
167 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
169 SegmentParam
::Const(const_
) => const_
.rewrite(context
, shape
),
170 SegmentParam
::LifeTime(lt
) => lt
.rewrite(context
, shape
),
171 SegmentParam
::Type(ty
) => ty
.rewrite(context
, shape
),
172 SegmentParam
::Binding(assoc_ty_constraint
) => {
173 let mut result
= match assoc_ty_constraint
.kind
{
174 ast
::AssocTyConstraintKind
::Bound { .. }
=> {
175 format
!("{}: ", rewrite_ident(context
, assoc_ty_constraint
.ident
))
177 ast
::AssocTyConstraintKind
::Equality { .. }
=> {
178 match context
.config
.type_punctuation_density() {
179 TypeDensity
::Wide
=> {
180 format
!("{} = ", rewrite_ident(context
, assoc_ty_constraint
.ident
))
182 TypeDensity
::Compressed
=> {
183 format
!("{}=", rewrite_ident(context
, assoc_ty_constraint
.ident
))
189 let budget
= shape
.width
.checked_sub(result
.len())?
;
190 let rewrite
= assoc_ty_constraint
192 .rewrite(context
, Shape
::legacy(budget
, shape
.indent
+ result
.len()))?
;
193 result
.push_str(&rewrite
);
200 impl Rewrite
for ast
::AssocTyConstraintKind
{
201 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
203 ast
::AssocTyConstraintKind
::Equality { ty }
=> ty
.rewrite(context
, shape
),
204 ast
::AssocTyConstraintKind
::Bound { bounds }
=> bounds
.rewrite(context
, shape
),
209 // Formats a path segment. There are some hacks involved to correctly determine
210 // the segment's associated span since it's not part of the AST.
212 // The span_lo is assumed to be greater than the end of any previous segment's
213 // parameters and lesser or equal than the start of current segment.
215 // span_hi is assumed equal to the end of the entire path.
217 // When the segment contains a positive number of parameters, we update span_lo
218 // so that invariants described above will hold for the next segment.
220 path_context
: PathContext
,
221 segment
: &ast
::PathSegment
,
222 span_lo
: &mut BytePos
,
224 context
: &RewriteContext
<'_
>,
226 ) -> Option
<String
> {
227 let mut result
= String
::with_capacity(128);
228 result
.push_str(rewrite_ident(context
, segment
.ident
));
230 let ident_len
= result
.len();
231 let shape
= if context
.use_block_indent() {
232 shape
.offset_left(ident_len
)?
234 shape
.shrink_left(ident_len
)?
237 if let Some(ref args
) = segment
.args
{
239 ast
::GenericArgs
::AngleBracketed(ref data
) if !data
.args
.is_empty() => {
240 let param_list
= data
244 ast
::AngleBracketedArg
::Arg(generic_arg
) => {
245 SegmentParam
::from_generic_arg(generic_arg
)
247 ast
::AngleBracketedArg
::Constraint(constraint
) => {
248 SegmentParam
::Binding(constraint
)
251 .collect
::<Vec
<_
>>();
253 // HACK: squeeze out the span between the identifier and the parameters.
254 // The hack is requried so that we don't remove the separator inside macro calls.
255 // This does not work in the presence of comment, hoping that people are
256 // sane about where to put their comment.
257 let separator_snippet
= context
258 .snippet(mk_sp(segment
.ident
.span
.hi(), data
.span
.lo()))
260 let force_separator
= context
.inside_macro() && separator_snippet
.starts_with("::");
261 let separator
= if path_context
== PathContext
::Expr
|| force_separator
{
266 result
.push_str(separator
);
268 let generics_str
= overflow
::rewrite_with_angle_brackets(
273 mk_sp(*span_lo
, span_hi
),
276 // Update position of last bracket.
279 .span_after(mk_sp(*span_lo
, span_hi
), "<");
281 result
.push_str(&generics_str
)
283 ast
::GenericArgs
::Parenthesized(ref data
) => {
284 result
.push_str(&format_function_type(
285 data
.inputs
.iter().map(|x
| &**x
),
300 fn format_function_type
<'a
, I
>(
305 context
: &RewriteContext
<'_
>,
309 I
: ExactSizeIterator
,
310 <I
as Iterator
>::Item
: Deref
,
311 <I
::Item
as Deref
>::Target
: Rewrite
+ Spanned
+ 'a
,
313 debug
!("format_function_type {:#?}", shape
);
315 let ty_shape
= match context
.config
.indent_style() {
317 IndentStyle
::Block
=> shape
.offset_left(4)?
,
318 IndentStyle
::Visual
=> shape
.block_left(4)?
,
320 let output
= match *output
{
321 FnRetTy
::Ty(ref ty
) => {
322 let type_str
= ty
.rewrite(context
, ty_shape
)?
;
323 format
!(" -> {}", type_str
)
325 FnRetTy
::Default(..) => String
::new(),
328 let list_shape
= if context
.use_block_indent() {
330 shape
.block().indent
.block_indent(context
.config
),
335 let budget
= shape
.width
.checked_sub(2)?
;
337 let offset
= shape
.indent
+ 1;
338 Shape
::legacy(budget
, offset
)
341 let is_inputs_empty
= inputs
.len() == 0;
342 let list_lo
= context
.snippet_provider
.span_after(span
, "(");
343 let (list_str
, tactic
) = if is_inputs_empty
{
344 let tactic
= get_tactics(&[], &output
, shape
);
345 let list_hi
= context
.snippet_provider
.span_before(span
, ")");
346 let comment
= context
348 .span_to_snippet(mk_sp(list_lo
, list_hi
))?
350 let comment
= if comment
.starts_with("//") {
353 &list_shape
.indent
.to_string_with_newline(context
.config
),
355 &shape
.block().indent
.to_string_with_newline(context
.config
)
362 let items
= itemize_list(
363 context
.snippet_provider
,
367 |arg
| arg
.span().lo(),
368 |arg
| arg
.span().hi(),
369 |arg
| arg
.rewrite(context
, list_shape
),
375 let item_vec
: Vec
<_
> = items
.collect();
376 let tactic
= get_tactics(&item_vec
, &output
, shape
);
377 let trailing_separator
= if !context
.use_block_indent() || variadic
{
378 SeparatorTactic
::Never
380 context
.config
.trailing_comma()
383 let fmt
= ListFormatting
::new(list_shape
, context
.config
)
385 .trailing_separator(trailing_separator
)
386 .ends_with_newline(tactic
.ends_with_newline(context
.config
.indent_style()))
387 .preserve_newline(true);
388 (write_list(&item_vec
, &fmt
)?
, tactic
)
391 let args
= if tactic
== DefinitiveListTactic
::Horizontal
392 || !context
.use_block_indent()
395 format
!("({})", list_str
)
399 list_shape
.indent
.to_string_with_newline(context
.config
),
401 shape
.block().indent
.to_string_with_newline(context
.config
),
404 if output
.is_empty() || last_line_width(&args
) + first_line_width(&output
) <= shape
.width
{
405 Some(format
!("{}{}", args
, output
))
410 list_shape
.indent
.to_string(context
.config
),
416 fn type_bound_colon(context
: &RewriteContext
<'_
>) -> &'
static str {
417 colon_spaces(context
.config
)
420 // If the return type is multi-lined, then force to use multiple lines for
421 // arguments as well.
422 fn get_tactics(item_vec
: &[ListItem
], output
: &str, shape
: Shape
) -> DefinitiveListTactic
{
423 if output
.contains('
\n'
) {
424 DefinitiveListTactic
::Vertical
428 ListTactic
::HorizontalVertical
,
430 // 2 is for the case of ',\n'
431 shape
.width
.saturating_sub(2 + output
.len()),
436 impl Rewrite
for ast
::WherePredicate
{
437 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
438 // FIXME: dead spans?
439 let result
= match *self {
440 ast
::WherePredicate
::BoundPredicate(ast
::WhereBoundPredicate
{
441 ref bound_generic_params
,
446 let type_str
= bounded_ty
.rewrite(context
, shape
)?
;
447 let colon
= type_bound_colon(context
).trim_end();
448 let lhs
= if let Some(lifetime_str
) =
449 rewrite_lifetime_param(context
, shape
, bound_generic_params
)
451 format
!("for<{}> {}{}", lifetime_str
, type_str
, colon
)
453 format
!("{}{}", type_str
, colon
)
456 rewrite_assign_rhs(context
, lhs
, bounds
, shape
)?
458 ast
::WherePredicate
::RegionPredicate(ast
::WhereRegionPredicate
{
462 }) => rewrite_bounded_lifetime(lifetime
, bounds
, context
, shape
)?
,
463 ast
::WherePredicate
::EqPredicate(ast
::WhereEqPredicate
{
468 let lhs_ty_str
= lhs_ty
.rewrite(context
, shape
).map(|lhs
| lhs
+ " =")?
;
469 rewrite_assign_rhs(context
, lhs_ty_str
, &**rhs_ty
, shape
)?
477 impl Rewrite
for ast
::GenericArg
{
478 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
480 ast
::GenericArg
::Lifetime(ref lt
) => lt
.rewrite(context
, shape
),
481 ast
::GenericArg
::Type(ref ty
) => ty
.rewrite(context
, shape
),
482 ast
::GenericArg
::Const(ref const_
) => const_
.rewrite(context
, shape
),
487 fn rewrite_bounded_lifetime(
489 bounds
: &[ast
::GenericBound
],
490 context
: &RewriteContext
<'_
>,
492 ) -> Option
<String
> {
493 let result
= lt
.rewrite(context
, shape
)?
;
495 if bounds
.is_empty() {
498 let colon
= type_bound_colon(context
);
499 let overhead
= last_line_width(&result
) + colon
.len();
500 let result
= format
!(
504 join_bounds(context
, shape
.sub_width(overhead
)?
, bounds
, true)?
510 impl Rewrite
for ast
::AnonConst
{
511 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
512 format_expr(&self.value
, ExprType
::SubExpression
, context
, shape
)
516 impl Rewrite
for ast
::Lifetime
{
517 fn rewrite(&self, context
: &RewriteContext
<'_
>, _
: Shape
) -> Option
<String
> {
518 Some(rewrite_ident(context
, self.ident
).to_owned())
522 impl Rewrite
for ast
::GenericBound
{
523 fn rewrite(&self, context
: &RewriteContext
<'_
>, shape
: Shape
) -> Option
<String
> {
525 ast
::GenericBound
::Trait(ref poly_trait_ref
, trait_bound_modifier
) => {
526 let snippet
= context
.snippet(self.span());
527 let has_paren
= snippet
.starts_with('
('
) && snippet
.ends_with('
)'
);
528 let rewrite
= match trait_bound_modifier
{
529 ast
::TraitBoundModifier
::None
=> poly_trait_ref
.rewrite(context
, shape
),
530 ast
::TraitBoundModifier
::Maybe
=> poly_trait_ref
531 .rewrite(context
, shape
.offset_left(1)?
)
532 .map(|s
| format
!("?{}", s
)),
533 ast
::TraitBoundModifier
::MaybeConst
=> poly_trait_ref
534 .rewrite(context
, shape
.offset_left(7)?
)
535 .map(|s
| format
!("~const {}", s
)),
536 ast
::TraitBoundModifier
::MaybeConstMaybe
=> poly_trait_ref
537 .rewrite(context
, shape
.offset_left(8)?
)
538 .map(|s
| format
!("~const ?{}", s
)),
540 rewrite
.map(|s
| if has_paren { format!("({}
)", s) } else { s })
542 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
547 impl Rewrite for ast::GenericBounds {
548 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
550 return Some(String::new());
553 join_bounds(context, shape, self, true)
557 impl Rewrite for ast::GenericParam {
558 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
559 let mut result = String::with_capacity(128);
560 // FIXME: If there are more than one attributes, this will force multiline.
561 match self.attrs.rewrite(context, shape) {
562 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{}
", rw)),
566 if let ast::GenericParamKind::Const {
572 result.push_str("const ");
573 result.push_str(rewrite_ident(context, self.ident));
574 result.push_str(": ");
575 result.push_str(&ty.rewrite(context, shape)?);
577 result.push_str(rewrite_ident(context, self.ident));
580 if !self.bounds.is_empty() {
581 result.push_str(type_bound_colon(context));
582 result.push_str(&self.bounds.rewrite(context, shape)?)
584 if let ast::GenericParamKind::Type {
585 default: Some(ref def),
588 let eq_str = match context.config.type_punctuation_density() {
589 TypeDensity::Compressed => "=",
590 TypeDensity::Wide => " = ",
592 result.push_str(eq_str);
593 let budget = shape.width.checked_sub(result.len())?;
595 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
596 result.push_str(&rewrite);
603 impl Rewrite for ast::PolyTraitRef {
604 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
605 if let Some(lifetime_str) =
606 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
608 // 6 is "for<> ".len()
609 let extra_offset = lifetime_str.len() + 6;
612 .rewrite(context, shape.offset_left(extra_offset)?)?;
614 Some(format!("for<{}
> {}
", lifetime_str, path_str))
616 self.trait_ref.rewrite(context, shape)
621 impl Rewrite for ast::TraitRef {
622 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
623 rewrite_path(context, PathContext::Type, None, &self.path, shape)
627 impl Rewrite for ast::Ty {
628 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
630 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
631 // we have to consider 'dyn' keyword is used or not!!!
632 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
633 // 4 is length of 'dyn '
634 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
635 let mut res = bounds.rewrite(context, shape)?;
636 // We may have falsely removed a trailing `+` inside macro call.
637 if context.inside_macro() && bounds.len() == 1 {
638 if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
643 Some(format!("dyn {}
", res))
648 ast::TyKind::Ptr(ref mt) => {
649 let prefix = match mt.mutbl {
650 Mutability::Mut => "*mut ",
651 Mutability::Not => "*const ",
654 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
656 ast::TyKind::Rptr(ref lifetime, ref mt) => {
657 let mut_str = format_mutability(mt.mutbl);
658 let mut_len = mut_str.len();
659 let mut result = String::with_capacity(128);
661 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
662 let mut cmnt_lo = ref_hi;
664 if let Some(ref lifetime) = *lifetime {
665 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
666 let lt_str = lifetime.rewrite(
668 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
670 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
671 if contains_comment(context.snippet(before_lt_span)) {
672 result = combine_strs_with_missing_comments(
681 result.push_str(<_str);
684 cmnt_lo = lifetime.ident.span.hi();
687 if ast::Mutability::Mut == mt.mutbl {
688 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
689 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
690 if contains_comment(context.snippet(before_mut_span)) {
691 result = combine_strs_with_missing_comments(
700 result.push_str(mut_str);
705 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
706 if contains_comment(context.snippet(before_ty_span)) {
707 result = combine_strs_with_missing_comments(
710 &mt.ty.rewrite(&context, shape)?,
716 let used_width = last_line_width(&result);
717 let budget = shape.width.checked_sub(used_width)?;
720 .rewrite(&context, Shape::legacy(budget, shape.indent + used_width))?;
721 result.push_str(&ty_str);
726 // FIXME: we drop any comments here, even though it's a silly place to put
728 ast::TyKind::Paren(ref ty) => {
729 if context.config.version() == Version::One
730 || context.config.indent_style() == IndentStyle::Visual
732 let budget = shape.width.checked_sub(2)?;
734 .rewrite(context, Shape::legacy(budget, shape.indent + 1))
735 .map(|ty_str| format!("({}
)", ty_str));
739 if let Some(sh) = shape.sub_width(2) {
740 if let Some(ref s) = ty.rewrite(context, sh) {
741 if !s.contains('\n') {
742 return Some(format!("({}
)", s));
747 let indent_str = shape.indent.to_string_with_newline(context.config);
749 .block_indent(context.config.tab_spaces())
750 .with_max_width(context.config);
751 let rw = ty.rewrite(context, shape)?;
754 shape.to_string_with_newline(context.config),
759 ast::TyKind::Slice(ref ty) => {
760 let budget = shape.width.checked_sub(4)?;
761 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
762 .map(|ty_str| format!("[{}
]", ty_str))
764 ast::TyKind::Tup(ref items) => {
765 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
767 ast::TyKind::Path(ref q_self, ref path) => {
768 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
770 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
773 PairParts::new("[", "; ", "]"),
776 SeparatorPlace::Back,
778 ast::TyKind::Infer => {
779 if shape.width >= 1 {
785 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
786 ast::TyKind::Never => Some(String::from("!")),
787 ast::TyKind::MacCall(ref mac) => {
788 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
790 ast::TyKind::ImplicitSelf => Some(String::from("")),
791 ast::TyKind::ImplTrait(_, ref it) => {
792 // Empty trait is not a parser error.
794 return Some("impl".to_owned());
796 let rw = if context.config.version() == Version::One {
797 it.rewrite(context, shape)
799 join_bounds(context, shape, it, false)
802 let space = if it_str.is_empty() { "" } else { " " };
803 format!("impl{}{}
", space, it_str)
806 ast::TyKind::CVarArgs => Some("...".to_owned()),
807 ast::TyKind::Err => Some(context.snippet(self.span).to_owned()),
808 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
811 &[anon_const.value.clone()],
820 bare_fn: &ast::BareFnTy,
822 context: &RewriteContext<'_>,
824 ) -> Option<String> {
825 debug!("rewrite_bare_fn {:#?}
", shape);
827 let mut result = String::with_capacity(128);
829 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
831 result.push_str("for<");
832 // 6 = "for<> ".len(), 4 = "for<".
833 // This doesn't work out so nicely for multiline situation with lots of
834 // rightward drift. If that is a problem, we could use the list stuff.
835 result.push_str(lifetime_str);
836 result.push_str("> ");
839 result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
841 result.push_str(&format_extern(
843 context.config.force_explicit_abi(),
847 result.push_str("fn");
849 let func_ty_shape = if context.use_block_indent() {
850 shape.offset_left(result.len())?
852 shape.visual_indent(result.len()).sub_width(result.len())?
855 let rewrite = format_function_type(
856 bare_fn.decl.inputs.iter(),
857 &bare_fn.decl.output,
858 bare_fn.decl.c_variadic(),
864 result.push_str(&rewrite);
869 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
870 let is_trait = |b: &ast::GenericBound| match b {
871 ast::GenericBound::Outlives(..) => false,
872 ast::GenericBound::Trait(..) => true,
874 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
875 let last_trait_index = generic_bounds.iter().rposition(is_trait);
876 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
877 match (last_trait_index, first_lifetime_index) {
878 (Some(last_trait_index), Some(first_lifetime_index)) => {
879 last_trait_index < first_lifetime_index
886 context: &RewriteContext<'_>,
888 items: &[ast::GenericBound],
890 ) -> Option<String> {
891 join_bounds_inner(context, shape, items, need_indent, false)
894 fn join_bounds_inner(
895 context: &RewriteContext<'_>,
897 items: &[ast::GenericBound],
900 ) -> Option<String> {
901 debug_assert!(!items.is_empty());
903 let generic_bounds_in_order = is_generic_bounds_in_order(items);
904 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
905 ast::GenericBound::Outlives(..) => true,
906 ast::GenericBound::Trait(..) => last_line_extendable(s),
909 let result = items.iter().enumerate().try_fold(
910 (String::new(), None, false),
911 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
912 let trailing_span = if i < items.len() - 1 {
915 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
917 Some(mk_sp(item.span().hi(), hi))
921 let (leading_span, has_leading_comment) = if i > 0 {
924 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
926 let span = mk_sp(lo, item.span().lo());
928 let has_comments = contains_comment(context.snippet(span));
930 (Some(mk_sp(lo, item.span().lo())), has_comments)
934 let prev_has_trailing_comment = match prev_trailing_span {
935 Some(ts) => contains_comment(context.snippet(ts)),
939 let shape = if need_indent && force_newline {
941 .block_indent(context.config.tab_spaces())
942 .with_max_width(context.config)
946 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
949 .to_string_with_newline(context.config)
955 let joiner = match context.config.type_punctuation_density() {
956 TypeDensity::Compressed => String::from("+"),
957 TypeDensity::Wide => whitespace + "+ ",
959 let joiner = if has_leading_comment {
964 let joiner = if prev_has_trailing_comment {
970 let (extendable, trailing_str) = if i == 0 {
971 let bound_str = item.rewrite(context, shape)?;
972 (is_bound_extendable(&bound_str, item), bound_str)
974 let bound_str = &item.rewrite(context, shape)?;
976 Some(ls) if has_leading_comment => (
977 is_bound_extendable(bound_str, item),
978 combine_strs_with_missing_comments(
979 context, joiner, bound_str, ls, shape, true,
983 is_bound_extendable(bound_str, item),
984 String::from(joiner) + bound_str,
988 match prev_trailing_span {
989 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
997 .map(|v| (v, trailing_span, extendable)),
998 _ => Some((strs + &trailing_str, trailing_span, extendable)),
1005 && (result.0.contains('\n') || result.0.len() > shape.width)
1007 join_bounds_inner(context, shape, items, need_indent, true)
1013 pub(crate) fn can_be_overflowed_type(
1014 context: &RewriteContext<'_>,
1019 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1020 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
1021 can_be_overflowed_type(context, &*mutty.ty, len)
1027 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
1028 fn rewrite_lifetime_param(
1029 context: &RewriteContext<'_>,
1031 generic_params: &[ast::GenericParam],
1032 ) -> Option<String> {
1033 let result = generic_params
1035 .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime))
1036 .map(|lt| lt.rewrite(context, shape))
1037 .collect::<Option<Vec<_>>>()?
1039 if result.is_empty() {