]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Simplify handling parens on generic bound trait
[rust.git] / src / types.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::iter::ExactSizeIterator;
12 use std::ops::Deref;
13
14 use config::lists::*;
15 use syntax::ast::{self, FunctionRetTy, Mutability};
16 use syntax::source_map::{self, BytePos, Span};
17 use syntax::symbol::keywords;
18
19 use config::{IndentStyle, TypeDensity};
20 use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix};
21 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
22 use macros::{rewrite_macro, MacroPosition};
23 use overflow;
24 use pairs::{rewrite_pair, PairParts};
25 use rewrite::{Rewrite, RewriteContext};
26 use shape::Shape;
27 use source_map::SpanUtils;
28 use spanned::Spanned;
29 use utils::{
30     colon_spaces, extra_offset, first_line_width, format_abi, format_mutability,
31     last_line_extendable, last_line_width, mk_sp, rewrite_ident,
32 };
33
34 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
35 pub enum PathContext {
36     Expr,
37     Type,
38     Import,
39 }
40
41 // Does not wrap on simple segments.
42 pub fn rewrite_path(
43     context: &RewriteContext,
44     path_context: PathContext,
45     qself: Option<&ast::QSelf>,
46     path: &ast::Path,
47     shape: Shape,
48 ) -> Option<String> {
49     let skip_count = qself.map_or(0, |x| x.position);
50
51     let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
52         "::".to_owned()
53     } else {
54         String::new()
55     };
56
57     let mut span_lo = path.span.lo();
58
59     if let Some(qself) = qself {
60         result.push('<');
61
62         let fmt_ty = qself.ty.rewrite(context, shape)?;
63         result.push_str(&fmt_ty);
64
65         if skip_count > 0 {
66             result.push_str(" as ");
67             if path.is_global() && path_context != PathContext::Import {
68                 result.push_str("::");
69             }
70
71             // 3 = ">::".len()
72             let shape = shape.sub_width(3)?;
73
74             result = rewrite_path_segments(
75                 PathContext::Type,
76                 result,
77                 path.segments.iter().take(skip_count),
78                 span_lo,
79                 path.span.hi(),
80                 context,
81                 shape,
82             )?;
83         }
84
85         result.push_str(">::");
86         span_lo = qself.ty.span.hi() + BytePos(1);
87     }
88
89     rewrite_path_segments(
90         path_context,
91         result,
92         path.segments.iter().skip(skip_count),
93         span_lo,
94         path.span.hi(),
95         context,
96         shape,
97     )
98 }
99
100 fn rewrite_path_segments<'a, I>(
101     path_context: PathContext,
102     mut buffer: String,
103     iter: I,
104     mut span_lo: BytePos,
105     span_hi: BytePos,
106     context: &RewriteContext,
107     shape: Shape,
108 ) -> Option<String>
109 where
110     I: Iterator<Item = &'a ast::PathSegment>,
111 {
112     let mut first = true;
113     let shape = shape.visual_indent(0);
114
115     for segment in iter {
116         // Indicates a global path, shouldn't be rendered.
117         if segment.ident.name == keywords::CrateRoot.name() {
118             continue;
119         }
120         if first {
121             first = false;
122         } else {
123             buffer.push_str("::");
124         }
125
126         let extra_offset = extra_offset(&buffer, shape);
127         let new_shape = shape.shrink_left(extra_offset)?;
128         let segment_string = rewrite_segment(
129             path_context,
130             segment,
131             &mut span_lo,
132             span_hi,
133             context,
134             new_shape,
135         )?;
136
137         buffer.push_str(&segment_string);
138     }
139
140     Some(buffer)
141 }
142
143 #[derive(Debug)]
144 pub enum SegmentParam<'a> {
145     LifeTime(&'a ast::Lifetime),
146     Type(&'a ast::Ty),
147     Binding(&'a ast::TypeBinding),
148 }
149
150 impl<'a> SegmentParam<'a> {
151     fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam {
152         match arg {
153             ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
154             ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
155         }
156     }
157 }
158
159 impl<'a> Spanned for SegmentParam<'a> {
160     fn span(&self) -> Span {
161         match *self {
162             SegmentParam::LifeTime(lt) => lt.ident.span,
163             SegmentParam::Type(ty) => ty.span,
164             SegmentParam::Binding(binding) => binding.span,
165         }
166     }
167 }
168
169 impl<'a> Rewrite for SegmentParam<'a> {
170     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
171         match *self {
172             SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
173             SegmentParam::Type(ty) => ty.rewrite(context, shape),
174             SegmentParam::Binding(binding) => {
175                 let mut result = match context.config.type_punctuation_density() {
176                     TypeDensity::Wide => format!("{} = ", rewrite_ident(context, binding.ident)),
177                     TypeDensity::Compressed => {
178                         format!("{}=", rewrite_ident(context, binding.ident))
179                     }
180                 };
181                 let budget = shape.width.checked_sub(result.len())?;
182                 let rewrite = binding
183                     .ty
184                     .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
185                 result.push_str(&rewrite);
186                 Some(result)
187             }
188         }
189     }
190 }
191
192 // Formats a path segment. There are some hacks involved to correctly determine
193 // the segment's associated span since it's not part of the AST.
194 //
195 // The span_lo is assumed to be greater than the end of any previous segment's
196 // parameters and lesser or equal than the start of current segment.
197 //
198 // span_hi is assumed equal to the end of the entire path.
199 //
200 // When the segment contains a positive number of parameters, we update span_lo
201 // so that invariants described above will hold for the next segment.
202 fn rewrite_segment(
203     path_context: PathContext,
204     segment: &ast::PathSegment,
205     span_lo: &mut BytePos,
206     span_hi: BytePos,
207     context: &RewriteContext,
208     shape: Shape,
209 ) -> Option<String> {
210     let mut result = String::with_capacity(128);
211     result.push_str(rewrite_ident(context, segment.ident));
212
213     let ident_len = result.len();
214     let shape = if context.use_block_indent() {
215         shape.offset_left(ident_len)?
216     } else {
217         shape.shrink_left(ident_len)?
218     };
219
220     if let Some(ref args) = segment.args {
221         match **args {
222             ast::GenericArgs::AngleBracketed(ref data)
223                 if !data.args.is_empty() || !data.bindings.is_empty() =>
224             {
225                 let param_list = data
226                     .args
227                     .iter()
228                     .map(SegmentParam::from_generic_arg)
229                     .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
230                     .collect::<Vec<_>>();
231
232                 let separator = if path_context == PathContext::Expr {
233                     "::"
234                 } else {
235                     ""
236                 };
237                 result.push_str(separator);
238
239                 let generics_str = overflow::rewrite_with_angle_brackets(
240                     context,
241                     "",
242                     param_list.iter(),
243                     shape,
244                     mk_sp(*span_lo, span_hi),
245                 )?;
246
247                 // Update position of last bracket.
248                 *span_lo = context
249                     .snippet_provider
250                     .span_after(mk_sp(*span_lo, span_hi), "<");
251
252                 result.push_str(&generics_str)
253             }
254             ast::GenericArgs::Parenthesized(ref data) => {
255                 let output = match data.output {
256                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
257                     None => FunctionRetTy::Default(source_map::DUMMY_SP),
258                 };
259                 result.push_str(&format_function_type(
260                     data.inputs.iter().map(|x| &**x),
261                     &output,
262                     false,
263                     data.span,
264                     context,
265                     shape,
266                 )?);
267             }
268             _ => (),
269         }
270     }
271
272     Some(result)
273 }
274
275 fn format_function_type<'a, I>(
276     inputs: I,
277     output: &FunctionRetTy,
278     variadic: bool,
279     span: Span,
280     context: &RewriteContext,
281     shape: Shape,
282 ) -> Option<String>
283 where
284     I: ExactSizeIterator,
285     <I as Iterator>::Item: Deref,
286     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
287 {
288     debug!("format_function_type {:#?}", shape);
289
290     // Code for handling variadics is somewhat duplicated for items, but they
291     // are different enough to need some serious refactoring to share code.
292     enum ArgumentKind<T>
293     where
294         T: Deref,
295         <T as Deref>::Target: Rewrite + Spanned,
296     {
297         Regular(T),
298         Variadic(BytePos),
299     }
300
301     let variadic_arg = if variadic {
302         let variadic_start = context.snippet_provider.span_before(span, "...");
303         Some(ArgumentKind::Variadic(variadic_start))
304     } else {
305         None
306     };
307
308     // 2 for ()
309     let budget = shape.width.checked_sub(2)?;
310     // 1 for (
311     let offset = match context.config.indent_style() {
312         IndentStyle::Block => {
313             shape
314                 .block()
315                 .block_indent(context.config.tab_spaces())
316                 .indent
317         }
318         IndentStyle::Visual => shape.indent + 1,
319     };
320     let list_shape = Shape::legacy(budget, offset);
321     let list_lo = context.snippet_provider.span_after(span, "(");
322     let items = itemize_list(
323         context.snippet_provider,
324         inputs.map(ArgumentKind::Regular).chain(variadic_arg),
325         ")",
326         ",",
327         |arg| match *arg {
328             ArgumentKind::Regular(ref ty) => ty.span().lo(),
329             ArgumentKind::Variadic(start) => start,
330         },
331         |arg| match *arg {
332             ArgumentKind::Regular(ref ty) => ty.span().hi(),
333             ArgumentKind::Variadic(start) => start + BytePos(3),
334         },
335         |arg| match *arg {
336             ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
337             ArgumentKind::Variadic(_) => Some("...".to_owned()),
338         },
339         list_lo,
340         span.hi(),
341         false,
342     );
343
344     let item_vec: Vec<_> = items.collect();
345
346     let tactic = definitive_tactic(
347         &*item_vec,
348         ListTactic::HorizontalVertical,
349         Separator::Comma,
350         budget,
351     );
352     let trailing_separator = if !context.use_block_indent() || variadic {
353         SeparatorTactic::Never
354     } else {
355         context.config.trailing_comma()
356     };
357
358     let fmt = ListFormatting::new(list_shape, context.config)
359         .tactic(tactic)
360         .trailing_separator(trailing_separator)
361         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
362         .preserve_newline(true);
363     let list_str = write_list(&item_vec, &fmt)?;
364
365     let ty_shape = match context.config.indent_style() {
366         // 4 = " -> "
367         IndentStyle::Block => shape.offset_left(4)?,
368         IndentStyle::Visual => shape.block_left(4)?,
369     };
370     let output = match *output {
371         FunctionRetTy::Ty(ref ty) => {
372             let type_str = ty.rewrite(context, ty_shape)?;
373             format!(" -> {}", type_str)
374         }
375         FunctionRetTy::Default(..) => String::new(),
376     };
377
378     let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
379         || !context.use_block_indent()
380     {
381         format!("({})", list_str)
382     } else {
383         format!(
384             "({}{}{})",
385             offset.to_string_with_newline(context.config),
386             list_str,
387             shape.block().indent.to_string_with_newline(context.config),
388         )
389     };
390     if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
391         Some(format!("{}{}", args, output))
392     } else {
393         Some(format!(
394             "{}\n{}{}",
395             args,
396             offset.to_string(context.config),
397             output.trim_left()
398         ))
399     }
400 }
401
402 fn type_bound_colon(context: &RewriteContext) -> &'static str {
403     colon_spaces(
404         context.config.space_before_colon(),
405         context.config.space_after_colon(),
406     )
407 }
408
409 impl Rewrite for ast::WherePredicate {
410     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
411         // FIXME: dead spans?
412         let result = match *self {
413             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
414                 ref bound_generic_params,
415                 ref bounded_ty,
416                 ref bounds,
417                 ..
418             }) => {
419                 let type_str = bounded_ty.rewrite(context, shape)?;
420                 let colon = type_bound_colon(context).trim_right();
421                 let lhs = if let Some(lifetime_str) =
422                     rewrite_lifetime_param(context, shape, bound_generic_params)
423                 {
424                     format!("for<{}> {}{}", lifetime_str, type_str, colon)
425                 } else {
426                     format!("{}{}", type_str, colon)
427                 };
428
429                 rewrite_assign_rhs(context, lhs, bounds, shape)?
430             }
431             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
432                 ref lifetime,
433                 ref bounds,
434                 ..
435             }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
436             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
437                 ref lhs_ty,
438                 ref rhs_ty,
439                 ..
440             }) => {
441                 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
442                 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
443             }
444         };
445
446         Some(result)
447     }
448 }
449
450 impl Rewrite for ast::GenericArg {
451     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
452         match *self {
453             ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
454             ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
455         }
456     }
457 }
458
459 fn rewrite_bounded_lifetime(
460     lt: &ast::Lifetime,
461     bounds: &[ast::GenericBound],
462     context: &RewriteContext,
463     shape: Shape,
464 ) -> Option<String> {
465     let result = lt.rewrite(context, shape)?;
466
467     if bounds.is_empty() {
468         Some(result)
469     } else {
470         let colon = type_bound_colon(context);
471         let overhead = last_line_width(&result) + colon.len();
472         let result = format!(
473             "{}{}{}",
474             result,
475             colon,
476             join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
477         );
478         Some(result)
479     }
480 }
481
482 impl Rewrite for ast::Lifetime {
483     fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
484         Some(rewrite_ident(context, self.ident).to_owned())
485     }
486 }
487
488 impl Rewrite for ast::GenericBound {
489     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
490         match *self {
491             ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
492                 let snippet = context.snippet(self.span());
493                 let has_paren = snippet.starts_with("(") && snippet.ends_with(")");
494                 let rewrite = match trait_bound_modifier {
495                     ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
496                     ast::TraitBoundModifier::Maybe => poly_trait_ref
497                         .rewrite(context, shape.offset_left(1)?)
498                         .map(|s| format!("?{}", s)),
499                 };
500                 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
501             }
502             ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
503         }
504     }
505 }
506
507 impl Rewrite for ast::GenericBounds {
508     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
509         if self.is_empty() {
510             return Some(String::new());
511         }
512
513         join_bounds(context, shape, self, true)
514     }
515 }
516
517 impl Rewrite for ast::GenericParam {
518     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
519         let mut result = String::with_capacity(128);
520         // FIXME: If there are more than one attributes, this will force multiline.
521         match self.attrs.rewrite(context, shape) {
522             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
523             _ => (),
524         }
525         result.push_str(rewrite_ident(context, self.ident));
526         if !self.bounds.is_empty() {
527             result.push_str(type_bound_colon(context));
528             result.push_str(&self.bounds.rewrite(context, shape)?)
529         }
530         if let ast::GenericParamKind::Type {
531             default: Some(ref def),
532         } = self.kind
533         {
534             let eq_str = match context.config.type_punctuation_density() {
535                 TypeDensity::Compressed => "=",
536                 TypeDensity::Wide => " = ",
537             };
538             result.push_str(eq_str);
539             let budget = shape.width.checked_sub(result.len())?;
540             let rewrite =
541                 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
542             result.push_str(&rewrite);
543         }
544
545         Some(result)
546     }
547 }
548
549 impl Rewrite for ast::PolyTraitRef {
550     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
551         if let Some(lifetime_str) =
552             rewrite_lifetime_param(context, shape, &self.bound_generic_params)
553         {
554             // 6 is "for<> ".len()
555             let extra_offset = lifetime_str.len() + 6;
556             let path_str = self
557                 .trait_ref
558                 .rewrite(context, shape.offset_left(extra_offset)?)?;
559
560             Some(format!("for<{}> {}", lifetime_str, path_str))
561         } else {
562             self.trait_ref.rewrite(context, shape)
563         }
564     }
565 }
566
567 impl Rewrite for ast::TraitRef {
568     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
569         rewrite_path(context, PathContext::Type, None, &self.path, shape)
570     }
571 }
572
573 impl Rewrite for ast::Ty {
574     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
575         match self.node {
576             ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
577                 // we have to consider 'dyn' keyword is used or not!!!
578                 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
579                 // 4 is length of 'dyn '
580                 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
581                 let res = bounds.rewrite(context, shape)?;
582                 if is_dyn {
583                     Some(format!("dyn {}", res))
584                 } else {
585                     Some(res)
586                 }
587             }
588             ast::TyKind::Ptr(ref mt) => {
589                 let prefix = match mt.mutbl {
590                     Mutability::Mutable => "*mut ",
591                     Mutability::Immutable => "*const ",
592                 };
593
594                 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
595             }
596             ast::TyKind::Rptr(ref lifetime, ref mt) => {
597                 let mut_str = format_mutability(mt.mutbl);
598                 let mut_len = mut_str.len();
599                 Some(match *lifetime {
600                     Some(ref lifetime) => {
601                         let lt_budget = shape.width.checked_sub(2 + mut_len)?;
602                         let lt_str = lifetime.rewrite(
603                             context,
604                             Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
605                         )?;
606                         let lt_len = lt_str.len();
607                         let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
608                         format!(
609                             "&{} {}{}",
610                             lt_str,
611                             mut_str,
612                             mt.ty.rewrite(
613                                 context,
614                                 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
615                             )?
616                         )
617                     }
618                     None => {
619                         let budget = shape.width.checked_sub(1 + mut_len)?;
620                         format!(
621                             "&{}{}",
622                             mut_str,
623                             mt.ty.rewrite(
624                                 context,
625                                 Shape::legacy(budget, shape.indent + 1 + mut_len)
626                             )?
627                         )
628                     }
629                 })
630             }
631             // FIXME: we drop any comments here, even though it's a silly place to put
632             // comments.
633             ast::TyKind::Paren(ref ty) => {
634                 let budget = shape.width.checked_sub(2)?;
635                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
636                     .map(|ty_str| format!("({})", ty_str))
637             }
638             ast::TyKind::Slice(ref ty) => {
639                 let budget = shape.width.checked_sub(4)?;
640                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
641                     .map(|ty_str| format!("[{}]", ty_str))
642             }
643             ast::TyKind::Tup(ref items) => {
644                 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
645             }
646             ast::TyKind::Path(ref q_self, ref path) => {
647                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
648             }
649             ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
650                 &**ty,
651                 &*repeats.value,
652                 PairParts::new("[", "; ", "]"),
653                 context,
654                 shape,
655                 SeparatorPlace::Back,
656             ),
657             ast::TyKind::Infer => {
658                 if shape.width >= 1 {
659                     Some("_".to_owned())
660                 } else {
661                     None
662                 }
663             }
664             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
665             ast::TyKind::Never => Some(String::from("!")),
666             ast::TyKind::Mac(ref mac) => {
667                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
668             }
669             ast::TyKind::ImplicitSelf => Some(String::from("")),
670             ast::TyKind::ImplTrait(_, ref it) => it
671                 .rewrite(context, shape)
672                 .map(|it_str| format!("impl {}", it_str)),
673             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
674         }
675     }
676 }
677
678 fn rewrite_bare_fn(
679     bare_fn: &ast::BareFnTy,
680     span: Span,
681     context: &RewriteContext,
682     shape: Shape,
683 ) -> Option<String> {
684     debug!("rewrite_bare_fn {:#?}", shape);
685
686     let mut result = String::with_capacity(128);
687
688     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
689     {
690         result.push_str("for<");
691         // 6 = "for<> ".len(), 4 = "for<".
692         // This doesn't work out so nicely for multiline situation with lots of
693         // rightward drift. If that is a problem, we could use the list stuff.
694         result.push_str(lifetime_str);
695         result.push_str("> ");
696     }
697
698     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
699
700     result.push_str(&format_abi(
701         bare_fn.abi,
702         context.config.force_explicit_abi(),
703         false,
704     ));
705
706     result.push_str("fn");
707
708     let func_ty_shape = if context.use_block_indent() {
709         shape.offset_left(result.len())?
710     } else {
711         shape.visual_indent(result.len()).sub_width(result.len())?
712     };
713
714     let rewrite = format_function_type(
715         bare_fn.decl.inputs.iter(),
716         &bare_fn.decl.output,
717         bare_fn.decl.variadic,
718         span,
719         context,
720         func_ty_shape,
721     )?;
722
723     result.push_str(&rewrite);
724
725     Some(result)
726 }
727
728 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
729     let is_trait = |b: &ast::GenericBound| match b {
730         ast::GenericBound::Outlives(..) => false,
731         ast::GenericBound::Trait(..) => true,
732     };
733     let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
734     let last_trait_index = generic_bounds.iter().rposition(is_trait);
735     let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
736     match (last_trait_index, first_lifetime_index) {
737         (Some(last_trait_index), Some(first_lifetime_index)) => {
738             last_trait_index < first_lifetime_index
739         }
740         _ => true,
741     }
742 }
743
744 fn join_bounds(
745     context: &RewriteContext,
746     shape: Shape,
747     items: &[ast::GenericBound],
748     need_indent: bool,
749 ) -> Option<String> {
750     debug_assert!(!items.is_empty());
751
752     // Try to join types in a single line
753     let joiner = match context.config.type_punctuation_density() {
754         TypeDensity::Compressed => "+",
755         TypeDensity::Wide => " + ",
756     };
757     let type_strs = items
758         .iter()
759         .map(|item| item.rewrite(context, shape))
760         .collect::<Option<Vec<_>>>()?;
761     let result = type_strs.join(joiner);
762     if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
763         return Some(result);
764     }
765
766     // We need to use multiple lines.
767     let (type_strs, offset) = if need_indent {
768         // Rewrite with additional indentation.
769         let nested_shape = shape.block_indent(context.config.tab_spaces());
770         let type_strs = items
771             .iter()
772             .map(|item| item.rewrite(context, nested_shape))
773             .collect::<Option<Vec<_>>>()?;
774         (type_strs, nested_shape.indent)
775     } else {
776         (type_strs, shape.indent)
777     };
778
779     let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
780         ast::GenericBound::Outlives(..) => true,
781         ast::GenericBound::Trait(..) => last_line_extendable(s),
782     };
783     let mut result = String::with_capacity(128);
784     result.push_str(&type_strs[0]);
785     let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
786     let generic_bounds_in_order = is_generic_bounds_in_order(items);
787     for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
788         if generic_bounds_in_order && can_be_put_on_the_same_line {
789             result.push_str(joiner);
790         } else {
791             result.push_str(&offset.to_string_with_newline(context.config));
792             result.push_str("+ ");
793         }
794         result.push_str(bound_str);
795         can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
796     }
797
798     Some(result)
799 }
800
801 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
802     match ty.node {
803         ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
804         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
805             can_be_overflowed_type(context, &*mutty.ty, len)
806         }
807         _ => false,
808     }
809 }
810
811 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
812 fn rewrite_lifetime_param(
813     context: &RewriteContext,
814     shape: Shape,
815     generic_params: &[ast::GenericParam],
816 ) -> Option<String> {
817     let result = generic_params
818         .iter()
819         .filter(|p| match p.kind {
820             ast::GenericParamKind::Lifetime => true,
821             _ => false,
822         })
823         .map(|lt| lt.rewrite(context, shape))
824         .collect::<Option<Vec<_>>>()?
825         .join(", ");
826     if result.is_empty() {
827         None
828     } else {
829         Some(result)
830     }
831 }