1 use std::iter::ExactSizeIterator;
4 use rustc_ast::ast::{self, FnRetTy, Mutability, Term};
6 use rustc_span::{symbol::kw, BytePos, Pos, Span};
8 use crate::comment::{combine_strs_with_missing_comments, contains_comment};
9 use crate::config::lists::*;
10 use crate::config::{IndentStyle, TypeDensity, Version};
12 format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, rewrite_unary_prefix, ExprType,
16 definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
18 use crate::macros::{rewrite_macro, MacroPosition};
20 use crate::pairs::{rewrite_pair, PairParts};
21 use crate::rewrite::{Rewrite, RewriteContext};
22 use crate::shape::Shape;
23 use crate::source_map::SpanUtils;
24 use crate::spanned::Spanned;
26 colon_spaces, extra_offset, first_line_width, format_extern, format_mutability,
27 last_line_extendable, last_line_width, mk_sp, rewrite_ident,
30 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
31 pub(crate) enum PathContext {
37 // Does not wrap on simple segments.
38 pub(crate) fn rewrite_path(
39 context: &RewriteContext<'_>,
40 path_context: PathContext,
41 qself: Option<&ast::QSelf>,
45 let skip_count = qself.map_or(0, |x| x.position);
47 let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
53 let mut span_lo = path.span.lo();
55 if let Some(qself) = qself {
58 let fmt_ty = qself.ty.rewrite(context, shape)?;
59 result.push_str(&fmt_ty);
62 result.push_str(" as ");
63 if path.is_global() && path_context != PathContext::Import {
64 result.push_str("::");
68 let shape = shape.sub_width(3)?;
70 result = rewrite_path_segments(
73 path.segments.iter().take(skip_count),
81 result.push_str(">::");
82 span_lo = qself.ty.span.hi() + BytePos(1);
85 rewrite_path_segments(
88 path.segments.iter().skip(skip_count),
96 fn rewrite_path_segments<'a, I>(
97 path_context: PathContext,
100 mut span_lo: BytePos,
102 context: &RewriteContext<'_>,
106 I: Iterator<Item = &'a ast::PathSegment>,
108 let mut first = true;
109 let shape = shape.visual_indent(0);
111 for segment in iter {
112 // Indicates a global path, shouldn't be rendered.
113 if segment.ident.name == kw::PathRoot {
119 buffer.push_str("::");
122 let extra_offset = extra_offset(&buffer, shape);
123 let new_shape = shape.shrink_left(extra_offset)?;
124 let segment_string = rewrite_segment(
133 buffer.push_str(&segment_string);
140 pub(crate) enum SegmentParam<'a> {
141 Const(&'a ast::AnonConst),
142 LifeTime(&'a ast::Lifetime),
144 Binding(&'a ast::AssocConstraint),
147 impl<'a> SegmentParam<'a> {
148 fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_> {
150 ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
151 ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
152 ast::GenericArg::Const(const_) => SegmentParam::Const(const_),
157 impl<'a> Spanned for SegmentParam<'a> {
158 fn span(&self) -> Span {
160 SegmentParam::Const(const_) => const_.value.span,
161 SegmentParam::LifeTime(lt) => lt.ident.span,
162 SegmentParam::Type(ty) => ty.span,
163 SegmentParam::Binding(binding) => binding.span,
168 impl<'a> Rewrite for SegmentParam<'a> {
169 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
171 SegmentParam::Const(const_) => const_.rewrite(context, shape),
172 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
173 SegmentParam::Type(ty) => ty.rewrite(context, shape),
174 SegmentParam::Binding(atc) => atc.rewrite(context, shape),
179 impl Rewrite for ast::AssocConstraint {
180 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
181 use ast::AssocConstraintKind::{Bound, Equality};
183 let mut result = String::with_capacity(128);
184 result.push_str(rewrite_ident(context, self.ident));
186 if let Some(ref gen_args) = self.gen_args {
187 let budget = shape.width.checked_sub(result.len())?;
188 let shape = Shape::legacy(budget, shape.indent + result.len());
189 let gen_str = rewrite_generic_args(gen_args, context, shape, gen_args.span())?;
190 result.push_str(&gen_str);
193 let infix = match (&self.kind, context.config.type_punctuation_density()) {
194 (Bound { .. }, _) => ": ",
195 (Equality { .. }, TypeDensity::Wide) => " = ",
196 (Equality { .. }, TypeDensity::Compressed) => "=",
198 result.push_str(infix);
200 let budget = shape.width.checked_sub(result.len())?;
201 let shape = Shape::legacy(budget, shape.indent + result.len());
202 let rewrite = self.kind.rewrite(context, shape)?;
203 result.push_str(&rewrite);
209 impl Rewrite for ast::AssocConstraintKind {
210 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
212 ast::AssocConstraintKind::Equality { term } => match term {
213 Term::Ty(ty) => ty.rewrite(context, shape),
214 Term::Const(c) => c.rewrite(context, shape),
216 ast::AssocConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
221 // Formats a path segment. There are some hacks involved to correctly determine
222 // the segment's associated span since it's not part of the AST.
224 // The span_lo is assumed to be greater than the end of any previous segment's
225 // parameters and lesser or equal than the start of current segment.
227 // span_hi is assumed equal to the end of the entire path.
229 // When the segment contains a positive number of parameters, we update span_lo
230 // so that invariants described above will hold for the next segment.
232 path_context: PathContext,
233 segment: &ast::PathSegment,
234 span_lo: &mut BytePos,
236 context: &RewriteContext<'_>,
238 ) -> Option<String> {
239 let mut result = String::with_capacity(128);
240 result.push_str(rewrite_ident(context, segment.ident));
242 let ident_len = result.len();
243 let shape = if context.use_block_indent() {
244 shape.offset_left(ident_len)?
246 shape.shrink_left(ident_len)?
249 if let Some(ref args) = segment.args {
250 let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?;
252 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
253 // HACK: squeeze out the span between the identifier and the parameters.
254 // The hack is required 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 // Update position of last bracket.
271 .span_after(mk_sp(*span_lo, span_hi), "<");
275 result.push_str(&generics_str)
281 fn format_function_type<'a, I>(
286 context: &RewriteContext<'_>,
290 I: ExactSizeIterator,
291 <I as Iterator>::Item: Deref,
292 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
294 debug!("format_function_type {:#?}", shape);
296 let ty_shape = match context.config.indent_style() {
298 IndentStyle::Block => shape.offset_left(4)?,
299 IndentStyle::Visual => shape.block_left(4)?,
301 let output = match *output {
302 FnRetTy::Ty(ref ty) => {
303 let type_str = ty.rewrite(context, ty_shape)?;
304 format!(" -> {}", type_str)
306 FnRetTy::Default(..) => String::new(),
309 let list_shape = if context.use_block_indent() {
311 shape.block().indent.block_indent(context.config),
316 let budget = shape.width.checked_sub(2)?;
318 let offset = shape.indent + 1;
319 Shape::legacy(budget, offset)
322 let is_inputs_empty = inputs.len() == 0;
323 let list_lo = context.snippet_provider.span_after(span, "(");
324 let (list_str, tactic) = if is_inputs_empty {
325 let tactic = get_tactics(&[], &output, shape);
326 let list_hi = context.snippet_provider.span_before(span, ")");
327 let comment = context
329 .span_to_snippet(mk_sp(list_lo, list_hi))?
331 let comment = if comment.starts_with("//") {
334 &list_shape.indent.to_string_with_newline(context.config),
336 &shape.block().indent.to_string_with_newline(context.config)
343 let items = itemize_list(
344 context.snippet_provider,
348 |arg| arg.span().lo(),
349 |arg| arg.span().hi(),
350 |arg| arg.rewrite(context, list_shape),
356 let item_vec: Vec<_> = items.collect();
357 let tactic = get_tactics(&item_vec, &output, shape);
358 let trailing_separator = if !context.use_block_indent() || variadic {
359 SeparatorTactic::Never
361 context.config.trailing_comma()
364 let fmt = ListFormatting::new(list_shape, context.config)
366 .trailing_separator(trailing_separator)
367 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
368 .preserve_newline(true);
369 (write_list(&item_vec, &fmt)?, tactic)
372 let args = if tactic == DefinitiveListTactic::Horizontal
373 || !context.use_block_indent()
376 format!("({})", list_str)
380 list_shape.indent.to_string_with_newline(context.config),
382 shape.block().indent.to_string_with_newline(context.config),
385 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
386 Some(format!("{}{}", args, output))
391 list_shape.indent.to_string(context.config),
397 fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
398 colon_spaces(context.config)
401 // If the return type is multi-lined, then force to use multiple lines for
402 // arguments as well.
403 fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
404 if output.contains('\n') {
405 DefinitiveListTactic::Vertical
409 ListTactic::HorizontalVertical,
411 // 2 is for the case of ',\n'
412 shape.width.saturating_sub(2 + output.len()),
417 impl Rewrite for ast::WherePredicate {
418 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
419 // FIXME: dead spans?
420 let result = match *self {
421 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
422 ref bound_generic_params,
427 let type_str = bounded_ty.rewrite(context, shape)?;
428 let colon = type_bound_colon(context).trim_end();
429 let lhs = if let Some(lifetime_str) =
430 rewrite_lifetime_param(context, shape, bound_generic_params)
432 format!("for<{}> {}{}", lifetime_str, type_str, colon)
434 format!("{}{}", type_str, colon)
437 rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
439 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
443 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
444 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
449 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
450 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)?
458 impl Rewrite for ast::GenericArg {
459 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
461 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
462 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
463 ast::GenericArg::Const(ref const_) => const_.rewrite(context, shape),
468 fn rewrite_generic_args(
469 gen_args: &ast::GenericArgs,
470 context: &RewriteContext<'_>,
473 ) -> Option<String> {
475 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
480 ast::AngleBracketedArg::Arg(generic_arg) => {
481 SegmentParam::from_generic_arg(generic_arg)
483 ast::AngleBracketedArg::Constraint(constraint) => {
484 SegmentParam::Binding(constraint)
487 .collect::<Vec<_>>();
489 overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
491 ast::GenericArgs::Parenthesized(ref data) => format_function_type(
492 data.inputs.iter().map(|x| &**x),
499 _ => Some("".to_owned()),
503 fn rewrite_bounded_lifetime(
505 bounds: &[ast::GenericBound],
506 context: &RewriteContext<'_>,
508 ) -> Option<String> {
509 let result = lt.rewrite(context, shape)?;
511 if bounds.is_empty() {
514 let colon = type_bound_colon(context);
515 let overhead = last_line_width(&result) + colon.len();
516 let result = format!(
520 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
526 impl Rewrite for ast::AnonConst {
527 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
528 format_expr(&self.value, ExprType::SubExpression, context, shape)
532 impl Rewrite for ast::Lifetime {
533 fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
534 Some(rewrite_ident(context, self.ident).to_owned())
538 impl Rewrite for ast::GenericBound {
539 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
541 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
542 let snippet = context.snippet(self.span());
543 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
544 let rewrite = match trait_bound_modifier {
545 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
546 ast::TraitBoundModifier::Maybe => poly_trait_ref
547 .rewrite(context, shape.offset_left(1)?)
548 .map(|s| format!("?{}", s)),
549 ast::TraitBoundModifier::MaybeConst => poly_trait_ref
550 .rewrite(context, shape.offset_left(7)?)
551 .map(|s| format!("~const {}", s)),
552 ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
553 .rewrite(context, shape.offset_left(8)?)
554 .map(|s| format!("~const ?{}", s)),
556 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
558 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
563 impl Rewrite for ast::GenericBounds {
564 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
566 return Some(String::new());
569 join_bounds(context, shape, self, true)
573 impl Rewrite for ast::GenericParam {
574 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
575 let mut result = String::with_capacity(128);
576 // FIXME: If there are more than one attributes, this will force multiline.
577 match self.attrs.rewrite(context, shape) {
578 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
582 if let ast::GenericParamKind::Const {
588 result.push_str("const ");
589 result.push_str(rewrite_ident(context, self.ident));
590 result.push_str(": ");
591 result.push_str(&ty.rewrite(context, shape)?);
592 if let Some(default) = default {
593 let eq_str = match context.config.type_punctuation_density() {
594 TypeDensity::Compressed => "=",
595 TypeDensity::Wide => " = ",
597 result.push_str(eq_str);
598 let budget = shape.width.checked_sub(result.len())?;
599 let rewrite = default.rewrite(context, Shape::legacy(budget, shape.indent))?;
600 result.push_str(&rewrite);
603 result.push_str(rewrite_ident(context, self.ident));
606 if !self.bounds.is_empty() {
607 result.push_str(type_bound_colon(context));
608 result.push_str(&self.bounds.rewrite(context, shape)?)
610 if let ast::GenericParamKind::Type {
611 default: Some(ref def),
614 let eq_str = match context.config.type_punctuation_density() {
615 TypeDensity::Compressed => "=",
616 TypeDensity::Wide => " = ",
618 result.push_str(eq_str);
619 let budget = shape.width.checked_sub(result.len())?;
621 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
622 result.push_str(&rewrite);
629 impl Rewrite for ast::PolyTraitRef {
630 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
631 if let Some(lifetime_str) =
632 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
634 // 6 is "for<> ".len()
635 let extra_offset = lifetime_str.len() + 6;
638 .rewrite(context, shape.offset_left(extra_offset)?)?;
640 Some(format!("for<{}> {}", lifetime_str, path_str))
642 self.trait_ref.rewrite(context, shape)
647 impl Rewrite for ast::TraitRef {
648 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
649 rewrite_path(context, PathContext::Type, None, &self.path, shape)
653 impl Rewrite for ast::Ty {
654 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
656 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
657 // we have to consider 'dyn' keyword is used or not!!!
658 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
659 // 4 is length of 'dyn '
660 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
661 let mut res = bounds.rewrite(context, shape)?;
662 // We may have falsely removed a trailing `+` inside macro call.
663 if context.inside_macro() && bounds.len() == 1 {
664 if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
669 Some(format!("dyn {}", res))
674 ast::TyKind::Ptr(ref mt) => {
675 let prefix = match mt.mutbl {
676 Mutability::Mut => "*mut ",
677 Mutability::Not => "*const ",
680 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
682 ast::TyKind::Rptr(ref lifetime, ref mt) => {
683 let mut_str = format_mutability(mt.mutbl);
684 let mut_len = mut_str.len();
685 let mut result = String::with_capacity(128);
687 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
688 let mut cmnt_lo = ref_hi;
690 if let Some(ref lifetime) = *lifetime {
691 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
692 let lt_str = lifetime.rewrite(
694 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
696 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
697 if contains_comment(context.snippet(before_lt_span)) {
698 result = combine_strs_with_missing_comments(
707 result.push_str(<_str);
710 cmnt_lo = lifetime.ident.span.hi();
713 if ast::Mutability::Mut == mt.mutbl {
714 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
715 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
716 if contains_comment(context.snippet(before_mut_span)) {
717 result = combine_strs_with_missing_comments(
726 result.push_str(mut_str);
731 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
732 if contains_comment(context.snippet(before_ty_span)) {
733 result = combine_strs_with_missing_comments(
736 &mt.ty.rewrite(context, shape)?,
742 let used_width = last_line_width(&result);
743 let budget = shape.width.checked_sub(used_width)?;
746 .rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
747 result.push_str(&ty_str);
752 // FIXME: we drop any comments here, even though it's a silly place to put
754 ast::TyKind::Paren(ref ty) => {
755 if context.config.version() == Version::One
756 || context.config.indent_style() == IndentStyle::Visual
758 let budget = shape.width.checked_sub(2)?;
760 .rewrite(context, Shape::legacy(budget, shape.indent + 1))
761 .map(|ty_str| format!("({})", ty_str));
765 if let Some(sh) = shape.sub_width(2) {
766 if let Some(ref s) = ty.rewrite(context, sh) {
767 if !s.contains('\n') {
768 return Some(format!("({})", s));
773 let indent_str = shape.indent.to_string_with_newline(context.config);
775 .block_indent(context.config.tab_spaces())
776 .with_max_width(context.config);
777 let rw = ty.rewrite(context, shape)?;
780 shape.to_string_with_newline(context.config),
785 ast::TyKind::Slice(ref ty) => {
786 let budget = shape.width.checked_sub(4)?;
787 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
788 .map(|ty_str| format!("[{}]", ty_str))
790 ast::TyKind::Tup(ref items) => {
791 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
793 ast::TyKind::Path(ref q_self, ref path) => {
794 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
796 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
799 PairParts::new("[", "; ", "]"),
802 SeparatorPlace::Back,
804 ast::TyKind::Infer => {
805 if shape.width >= 1 {
811 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
812 ast::TyKind::Never => Some(String::from("!")),
813 ast::TyKind::MacCall(ref mac) => {
814 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
816 ast::TyKind::ImplicitSelf => Some(String::from("")),
817 ast::TyKind::ImplTrait(_, ref it) => {
818 // Empty trait is not a parser error.
820 return Some("impl".to_owned());
822 let rw = if context.config.version() == Version::One {
823 it.rewrite(context, shape)
825 join_bounds(context, shape, it, false)
828 let space = if it_str.is_empty() { "" } else { " " };
829 format!("impl{}{}", space, it_str)
832 ast::TyKind::CVarArgs => Some("...".to_owned()),
833 ast::TyKind::Err => Some(context.snippet(self.span).to_owned()),
834 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
837 &[anon_const.value.clone()],
846 bare_fn: &ast::BareFnTy,
848 context: &RewriteContext<'_>,
850 ) -> Option<String> {
851 debug!("rewrite_bare_fn {:#?}", shape);
853 let mut result = String::with_capacity(128);
855 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
857 result.push_str("for<");
858 // 6 = "for<> ".len(), 4 = "for<".
859 // This doesn't work out so nicely for multiline situation with lots of
860 // rightward drift. If that is a problem, we could use the list stuff.
861 result.push_str(lifetime_str);
862 result.push_str("> ");
865 result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
867 result.push_str(&format_extern(
869 context.config.force_explicit_abi(),
873 result.push_str("fn");
875 let func_ty_shape = if context.use_block_indent() {
876 shape.offset_left(result.len())?
878 shape.visual_indent(result.len()).sub_width(result.len())?
881 let rewrite = format_function_type(
882 bare_fn.decl.inputs.iter(),
883 &bare_fn.decl.output,
884 bare_fn.decl.c_variadic(),
890 result.push_str(&rewrite);
895 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
896 let is_trait = |b: &ast::GenericBound| match b {
897 ast::GenericBound::Outlives(..) => false,
898 ast::GenericBound::Trait(..) => true,
900 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
901 let last_trait_index = generic_bounds.iter().rposition(is_trait);
902 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
903 match (last_trait_index, first_lifetime_index) {
904 (Some(last_trait_index), Some(first_lifetime_index)) => {
905 last_trait_index < first_lifetime_index
912 context: &RewriteContext<'_>,
914 items: &[ast::GenericBound],
916 ) -> Option<String> {
917 join_bounds_inner(context, shape, items, need_indent, false)
920 fn join_bounds_inner(
921 context: &RewriteContext<'_>,
923 items: &[ast::GenericBound],
926 ) -> Option<String> {
927 debug_assert!(!items.is_empty());
929 let generic_bounds_in_order = is_generic_bounds_in_order(items);
930 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
931 ast::GenericBound::Outlives(..) => true,
932 ast::GenericBound::Trait(..) => last_line_extendable(s),
935 let result = items.iter().enumerate().try_fold(
936 (String::new(), None, false),
937 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
938 let trailing_span = if i < items.len() - 1 {
941 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
943 Some(mk_sp(item.span().hi(), hi))
947 let (leading_span, has_leading_comment) = if i > 0 {
950 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
952 let span = mk_sp(lo, item.span().lo());
954 let has_comments = contains_comment(context.snippet(span));
956 (Some(mk_sp(lo, item.span().lo())), has_comments)
960 let prev_has_trailing_comment = match prev_trailing_span {
961 Some(ts) => contains_comment(context.snippet(ts)),
965 let shape = if need_indent && force_newline {
967 .block_indent(context.config.tab_spaces())
968 .with_max_width(context.config)
972 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
975 .to_string_with_newline(context.config)
981 let joiner = match context.config.type_punctuation_density() {
982 TypeDensity::Compressed => String::from("+"),
983 TypeDensity::Wide => whitespace + "+ ",
985 let joiner = if has_leading_comment {
990 let joiner = if prev_has_trailing_comment {
996 let (extendable, trailing_str) = if i == 0 {
997 let bound_str = item.rewrite(context, shape)?;
998 (is_bound_extendable(&bound_str, item), bound_str)
1000 let bound_str = &item.rewrite(context, shape)?;
1001 match leading_span {
1002 Some(ls) if has_leading_comment => (
1003 is_bound_extendable(bound_str, item),
1004 combine_strs_with_missing_comments(
1005 context, joiner, bound_str, ls, shape, true,
1009 is_bound_extendable(bound_str, item),
1010 String::from(joiner) + bound_str,
1014 match prev_trailing_span {
1015 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1023 .map(|v| (v, trailing_span, extendable)),
1024 _ => Some((strs + &trailing_str, trailing_span, extendable)),
1031 && (result.0.contains('\n') || result.0.len() > shape.width)
1033 join_bounds_inner(context, shape, items, need_indent, true)
1039 pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
1040 ty.as_ref().and_then(|t| match &t.kind {
1041 ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1046 pub(crate) fn can_be_overflowed_type(
1047 context: &RewriteContext<'_>,
1052 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1053 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
1054 can_be_overflowed_type(context, &*mutty.ty, len)
1060 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
1061 fn rewrite_lifetime_param(
1062 context: &RewriteContext<'_>,
1064 generic_params: &[ast::GenericParam],
1065 ) -> Option<String> {
1066 let result = generic_params
1068 .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime))
1069 .map(|lt| lt.rewrite(context, shape))
1070 .collect::<Option<Vec<_>>>()?
1072 if result.is_empty() {