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(atc) => atc.rewrite(context, shape),
177 impl Rewrite for ast::AssocTyConstraint {
178 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
179 use ast::AssocTyConstraintKind::{Bound, Equality};
181 let mut result = String::with_capacity(128);
182 result.push_str(rewrite_ident(context, self.ident));
184 if let Some(ref gen_args) = self.gen_args {
185 let budget = shape.width.checked_sub(result.len())?;
186 let shape = Shape::legacy(budget, shape.indent + result.len());
187 let gen_str = rewrite_generic_args(gen_args, context, shape, gen_args.span())?;
188 result.push_str(&gen_str);
191 let infix = match (&self.kind, context.config.type_punctuation_density()) {
192 (Bound { .. }, _) => ": ",
193 (Equality { .. }, TypeDensity::Wide) => " = ",
194 (Equality { .. }, TypeDensity::Compressed) => "=",
196 result.push_str(infix);
198 let budget = shape.width.checked_sub(result.len())?;
199 let shape = Shape::legacy(budget, shape.indent + result.len());
200 let rewrite = self.kind.rewrite(context, shape)?;
201 result.push_str(&rewrite);
207 impl Rewrite for ast::AssocTyConstraintKind {
208 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
210 ast::AssocTyConstraintKind::Equality { ty } => ty.rewrite(context, shape),
211 ast::AssocTyConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
216 // Formats a path segment. There are some hacks involved to correctly determine
217 // the segment's associated span since it's not part of the AST.
219 // The span_lo is assumed to be greater than the end of any previous segment's
220 // parameters and lesser or equal than the start of current segment.
222 // span_hi is assumed equal to the end of the entire path.
224 // When the segment contains a positive number of parameters, we update span_lo
225 // so that invariants described above will hold for the next segment.
227 path_context: PathContext,
228 segment: &ast::PathSegment,
229 span_lo: &mut BytePos,
231 context: &RewriteContext<'_>,
233 ) -> Option<String> {
234 let mut result = String::with_capacity(128);
235 result.push_str(rewrite_ident(context, segment.ident));
237 let ident_len = result.len();
238 let shape = if context.use_block_indent() {
239 shape.offset_left(ident_len)?
241 shape.shrink_left(ident_len)?
244 if let Some(ref args) = segment.args {
245 let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?;
247 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
248 // HACK: squeeze out the span between the identifier and the parameters.
249 // The hack is requried so that we don't remove the separator inside macro calls.
250 // This does not work in the presence of comment, hoping that people are
251 // sane about where to put their comment.
252 let separator_snippet = context
253 .snippet(mk_sp(segment.ident.span.hi(), data.span.lo()))
255 let force_separator = context.inside_macro() && separator_snippet.starts_with("::");
256 let separator = if path_context == PathContext::Expr || force_separator {
261 result.push_str(separator);
263 // Update position of last bracket.
266 .span_after(mk_sp(*span_lo, span_hi), "<");
270 result.push_str(&generics_str)
276 fn format_function_type<'a, I>(
281 context: &RewriteContext<'_>,
285 I: ExactSizeIterator,
286 <I as Iterator>::Item: Deref,
287 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
289 debug!("format_function_type {:#?}", shape);
291 let ty_shape = match context.config.indent_style() {
293 IndentStyle::Block => shape.offset_left(4)?,
294 IndentStyle::Visual => shape.block_left(4)?,
296 let output = match *output {
297 FnRetTy::Ty(ref ty) => {
298 let type_str = ty.rewrite(context, ty_shape)?;
299 format!(" -> {}", type_str)
301 FnRetTy::Default(..) => String::new(),
304 let list_shape = if context.use_block_indent() {
306 shape.block().indent.block_indent(context.config),
311 let budget = shape.width.checked_sub(2)?;
313 let offset = shape.indent + 1;
314 Shape::legacy(budget, offset)
317 let is_inputs_empty = inputs.len() == 0;
318 let list_lo = context.snippet_provider.span_after(span, "(");
319 let (list_str, tactic) = if is_inputs_empty {
320 let tactic = get_tactics(&[], &output, shape);
321 let list_hi = context.snippet_provider.span_before(span, ")");
322 let comment = context
324 .span_to_snippet(mk_sp(list_lo, list_hi))?
326 let comment = if comment.starts_with("//") {
329 &list_shape.indent.to_string_with_newline(context.config),
331 &shape.block().indent.to_string_with_newline(context.config)
338 let items = itemize_list(
339 context.snippet_provider,
343 |arg| arg.span().lo(),
344 |arg| arg.span().hi(),
345 |arg| arg.rewrite(context, list_shape),
351 let item_vec: Vec<_> = items.collect();
352 let tactic = get_tactics(&item_vec, &output, shape);
353 let trailing_separator = if !context.use_block_indent() || variadic {
354 SeparatorTactic::Never
356 context.config.trailing_comma()
359 let fmt = ListFormatting::new(list_shape, context.config)
361 .trailing_separator(trailing_separator)
362 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
363 .preserve_newline(true);
364 (write_list(&item_vec, &fmt)?, tactic)
367 let args = if tactic == DefinitiveListTactic::Horizontal
368 || !context.use_block_indent()
371 format!("({})", list_str)
375 list_shape.indent.to_string_with_newline(context.config),
377 shape.block().indent.to_string_with_newline(context.config),
380 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
381 Some(format!("{}{}", args, output))
386 list_shape.indent.to_string(context.config),
392 fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
393 colon_spaces(context.config)
396 // If the return type is multi-lined, then force to use multiple lines for
397 // arguments as well.
398 fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
399 if output.contains('\n') {
400 DefinitiveListTactic::Vertical
404 ListTactic::HorizontalVertical,
406 // 2 is for the case of ',\n'
407 shape.width.saturating_sub(2 + output.len()),
412 impl Rewrite for ast::WherePredicate {
413 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
414 // FIXME: dead spans?
415 let result = match *self {
416 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
417 ref bound_generic_params,
422 let type_str = bounded_ty.rewrite(context, shape)?;
423 let colon = type_bound_colon(context).trim_end();
424 let lhs = if let Some(lifetime_str) =
425 rewrite_lifetime_param(context, shape, bound_generic_params)
427 format!("for<{}> {}{}", lifetime_str, type_str, colon)
429 format!("{}{}", type_str, colon)
432 rewrite_assign_rhs(context, lhs, bounds, shape)?
434 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
438 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
439 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
444 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
445 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
453 impl Rewrite for ast::GenericArg {
454 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
456 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
457 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
458 ast::GenericArg::Const(ref const_) => const_.rewrite(context, shape),
463 fn rewrite_generic_args(
464 gen_args: &ast::GenericArgs,
465 context: &RewriteContext<'_>,
468 ) -> Option<String> {
470 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
475 ast::AngleBracketedArg::Arg(generic_arg) => {
476 SegmentParam::from_generic_arg(generic_arg)
478 ast::AngleBracketedArg::Constraint(constraint) => {
479 SegmentParam::Binding(constraint)
482 .collect::<Vec<_>>();
484 overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
486 ast::GenericArgs::Parenthesized(ref data) => format_function_type(
487 data.inputs.iter().map(|x| &**x),
494 _ => Some("".to_owned()),
498 fn rewrite_bounded_lifetime(
500 bounds: &[ast::GenericBound],
501 context: &RewriteContext<'_>,
503 ) -> Option<String> {
504 let result = lt.rewrite(context, shape)?;
506 if bounds.is_empty() {
509 let colon = type_bound_colon(context);
510 let overhead = last_line_width(&result) + colon.len();
511 let result = format!(
515 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
521 impl Rewrite for ast::AnonConst {
522 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
523 format_expr(&self.value, ExprType::SubExpression, context, shape)
527 impl Rewrite for ast::Lifetime {
528 fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
529 Some(rewrite_ident(context, self.ident).to_owned())
533 impl Rewrite for ast::GenericBound {
534 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
536 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
537 let snippet = context.snippet(self.span());
538 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
539 let rewrite = match trait_bound_modifier {
540 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
541 ast::TraitBoundModifier::Maybe => poly_trait_ref
542 .rewrite(context, shape.offset_left(1)?)
543 .map(|s| format!("?{}", s)),
544 ast::TraitBoundModifier::MaybeConst => poly_trait_ref
545 .rewrite(context, shape.offset_left(7)?)
546 .map(|s| format!("~const {}", s)),
547 ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
548 .rewrite(context, shape.offset_left(8)?)
549 .map(|s| format!("~const ?{}", s)),
551 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
553 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
558 impl Rewrite for ast::GenericBounds {
559 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
561 return Some(String::new());
564 join_bounds(context, shape, self, true)
568 impl Rewrite for ast::GenericParam {
569 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
570 let mut result = String::with_capacity(128);
571 // FIXME: If there are more than one attributes, this will force multiline.
572 match self.attrs.rewrite(context, shape) {
573 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
577 if let ast::GenericParamKind::Const {
583 result.push_str("const ");
584 result.push_str(rewrite_ident(context, self.ident));
585 result.push_str(": ");
586 result.push_str(&ty.rewrite(context, shape)?);
587 if let Some(default) = default {
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())?;
594 let rewrite = default.rewrite(context, Shape::legacy(budget, shape.indent))?;
595 result.push_str(&rewrite);
598 result.push_str(rewrite_ident(context, self.ident));
601 if !self.bounds.is_empty() {
602 result.push_str(type_bound_colon(context));
603 result.push_str(&self.bounds.rewrite(context, shape)?)
605 if let ast::GenericParamKind::Type {
606 default: Some(ref def),
609 let eq_str = match context.config.type_punctuation_density() {
610 TypeDensity::Compressed => "=",
611 TypeDensity::Wide => " = ",
613 result.push_str(eq_str);
614 let budget = shape.width.checked_sub(result.len())?;
616 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
617 result.push_str(&rewrite);
624 impl Rewrite for ast::PolyTraitRef {
625 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
626 if let Some(lifetime_str) =
627 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
629 // 6 is "for<> ".len()
630 let extra_offset = lifetime_str.len() + 6;
633 .rewrite(context, shape.offset_left(extra_offset)?)?;
635 Some(format!("for<{}> {}", lifetime_str, path_str))
637 self.trait_ref.rewrite(context, shape)
642 impl Rewrite for ast::TraitRef {
643 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
644 rewrite_path(context, PathContext::Type, None, &self.path, shape)
648 impl Rewrite for ast::Ty {
649 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
651 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
652 // we have to consider 'dyn' keyword is used or not!!!
653 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
654 // 4 is length of 'dyn '
655 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
656 let mut res = bounds.rewrite(context, shape)?;
657 // We may have falsely removed a trailing `+` inside macro call.
658 if context.inside_macro() && bounds.len() == 1 {
659 if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
664 Some(format!("dyn {}", res))
669 ast::TyKind::Ptr(ref mt) => {
670 let prefix = match mt.mutbl {
671 Mutability::Mut => "*mut ",
672 Mutability::Not => "*const ",
675 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
677 ast::TyKind::Rptr(ref lifetime, ref mt) => {
678 let mut_str = format_mutability(mt.mutbl);
679 let mut_len = mut_str.len();
680 let mut result = String::with_capacity(128);
682 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
683 let mut cmnt_lo = ref_hi;
685 if let Some(ref lifetime) = *lifetime {
686 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
687 let lt_str = lifetime.rewrite(
689 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
691 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
692 if contains_comment(context.snippet(before_lt_span)) {
693 result = combine_strs_with_missing_comments(
702 result.push_str(<_str);
705 cmnt_lo = lifetime.ident.span.hi();
708 if ast::Mutability::Mut == mt.mutbl {
709 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
710 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
711 if contains_comment(context.snippet(before_mut_span)) {
712 result = combine_strs_with_missing_comments(
721 result.push_str(mut_str);
726 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
727 if contains_comment(context.snippet(before_ty_span)) {
728 result = combine_strs_with_missing_comments(
731 &mt.ty.rewrite(&context, shape)?,
737 let used_width = last_line_width(&result);
738 let budget = shape.width.checked_sub(used_width)?;
741 .rewrite(&context, Shape::legacy(budget, shape.indent + used_width))?;
742 result.push_str(&ty_str);
747 // FIXME: we drop any comments here, even though it's a silly place to put
749 ast::TyKind::Paren(ref ty) => {
750 if context.config.version() == Version::One
751 || context.config.indent_style() == IndentStyle::Visual
753 let budget = shape.width.checked_sub(2)?;
755 .rewrite(context, Shape::legacy(budget, shape.indent + 1))
756 .map(|ty_str| format!("({})", ty_str));
760 if let Some(sh) = shape.sub_width(2) {
761 if let Some(ref s) = ty.rewrite(context, sh) {
762 if !s.contains('\n') {
763 return Some(format!("({})", s));
768 let indent_str = shape.indent.to_string_with_newline(context.config);
770 .block_indent(context.config.tab_spaces())
771 .with_max_width(context.config);
772 let rw = ty.rewrite(context, shape)?;
775 shape.to_string_with_newline(context.config),
780 ast::TyKind::Slice(ref ty) => {
781 let budget = shape.width.checked_sub(4)?;
782 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
783 .map(|ty_str| format!("[{}]", ty_str))
785 ast::TyKind::Tup(ref items) => {
786 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
788 ast::TyKind::Path(ref q_self, ref path) => {
789 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
791 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
794 PairParts::new("[", "; ", "]"),
797 SeparatorPlace::Back,
799 ast::TyKind::Infer => {
800 if shape.width >= 1 {
806 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
807 ast::TyKind::Never => Some(String::from("!")),
808 ast::TyKind::MacCall(ref mac) => {
809 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
811 ast::TyKind::ImplicitSelf => Some(String::from("")),
812 ast::TyKind::ImplTrait(_, ref it) => {
813 // Empty trait is not a parser error.
815 return Some("impl".to_owned());
817 let rw = if context.config.version() == Version::One {
818 it.rewrite(context, shape)
820 join_bounds(context, shape, it, false)
823 let space = if it_str.is_empty() { "" } else { " " };
824 format!("impl{}{}", space, it_str)
827 ast::TyKind::CVarArgs => Some("...".to_owned()),
828 ast::TyKind::Err => Some(context.snippet(self.span).to_owned()),
829 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
832 &[anon_const.value.clone()],
841 bare_fn: &ast::BareFnTy,
843 context: &RewriteContext<'_>,
845 ) -> Option<String> {
846 debug!("rewrite_bare_fn {:#?}", shape);
848 let mut result = String::with_capacity(128);
850 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
852 result.push_str("for<");
853 // 6 = "for<> ".len(), 4 = "for<".
854 // This doesn't work out so nicely for multiline situation with lots of
855 // rightward drift. If that is a problem, we could use the list stuff.
856 result.push_str(lifetime_str);
857 result.push_str("> ");
860 result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
862 result.push_str(&format_extern(
864 context.config.force_explicit_abi(),
868 result.push_str("fn");
870 let func_ty_shape = if context.use_block_indent() {
871 shape.offset_left(result.len())?
873 shape.visual_indent(result.len()).sub_width(result.len())?
876 let rewrite = format_function_type(
877 bare_fn.decl.inputs.iter(),
878 &bare_fn.decl.output,
879 bare_fn.decl.c_variadic(),
885 result.push_str(&rewrite);
890 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
891 let is_trait = |b: &ast::GenericBound| match b {
892 ast::GenericBound::Outlives(..) => false,
893 ast::GenericBound::Trait(..) => true,
895 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
896 let last_trait_index = generic_bounds.iter().rposition(is_trait);
897 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
898 match (last_trait_index, first_lifetime_index) {
899 (Some(last_trait_index), Some(first_lifetime_index)) => {
900 last_trait_index < first_lifetime_index
907 context: &RewriteContext<'_>,
909 items: &[ast::GenericBound],
911 ) -> Option<String> {
912 join_bounds_inner(context, shape, items, need_indent, false)
915 fn join_bounds_inner(
916 context: &RewriteContext<'_>,
918 items: &[ast::GenericBound],
921 ) -> Option<String> {
922 debug_assert!(!items.is_empty());
924 let generic_bounds_in_order = is_generic_bounds_in_order(items);
925 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
926 ast::GenericBound::Outlives(..) => true,
927 ast::GenericBound::Trait(..) => last_line_extendable(s),
930 let result = items.iter().enumerate().try_fold(
931 (String::new(), None, false),
932 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
933 let trailing_span = if i < items.len() - 1 {
936 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
938 Some(mk_sp(item.span().hi(), hi))
942 let (leading_span, has_leading_comment) = if i > 0 {
945 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
947 let span = mk_sp(lo, item.span().lo());
949 let has_comments = contains_comment(context.snippet(span));
951 (Some(mk_sp(lo, item.span().lo())), has_comments)
955 let prev_has_trailing_comment = match prev_trailing_span {
956 Some(ts) => contains_comment(context.snippet(ts)),
960 let shape = if need_indent && force_newline {
962 .block_indent(context.config.tab_spaces())
963 .with_max_width(context.config)
967 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
970 .to_string_with_newline(context.config)
976 let joiner = match context.config.type_punctuation_density() {
977 TypeDensity::Compressed => String::from("+"),
978 TypeDensity::Wide => whitespace + "+ ",
980 let joiner = if has_leading_comment {
985 let joiner = if prev_has_trailing_comment {
991 let (extendable, trailing_str) = if i == 0 {
992 let bound_str = item.rewrite(context, shape)?;
993 (is_bound_extendable(&bound_str, item), bound_str)
995 let bound_str = &item.rewrite(context, shape)?;
997 Some(ls) if has_leading_comment => (
998 is_bound_extendable(bound_str, item),
999 combine_strs_with_missing_comments(
1000 context, joiner, bound_str, ls, shape, true,
1004 is_bound_extendable(bound_str, item),
1005 String::from(joiner) + bound_str,
1009 match prev_trailing_span {
1010 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1018 .map(|v| (v, trailing_span, extendable)),
1019 _ => Some((strs + &trailing_str, trailing_span, extendable)),
1026 && (result.0.contains('\n') || result.0.len() > shape.width)
1028 join_bounds_inner(context, shape, items, need_indent, true)
1034 pub(crate) fn can_be_overflowed_type(
1035 context: &RewriteContext<'_>,
1040 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1041 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
1042 can_be_overflowed_type(context, &*mutty.ty, len)
1048 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
1049 fn rewrite_lifetime_param(
1050 context: &RewriteContext<'_>,
1052 generic_params: &[ast::GenericParam],
1053 ) -> Option<String> {
1054 let result = generic_params
1056 .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime))
1057 .map(|lt| lt.rewrite(context, shape))
1058 .collect::<Option<Vec<_>>>()?
1060 if result.is_empty() {