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