]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #3017 from matthiaskrgr/typo
[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, ToExpr};
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 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(source_map::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     debug!("format_function_type {:#?}", shape);
302
303     // Code for handling variadics is somewhat duplicated for items, but they
304     // are different enough to need some serious refactoring to share code.
305     enum ArgumentKind<T>
306     where
307         T: Deref,
308         <T as Deref>::Target: Rewrite + Spanned,
309     {
310         Regular(T),
311         Variadic(BytePos),
312     }
313
314     let variadic_arg = if variadic {
315         let variadic_start = context.snippet_provider.span_before(span, "...");
316         Some(ArgumentKind::Variadic(variadic_start))
317     } else {
318         None
319     };
320
321     // 2 for ()
322     let budget = shape.width.checked_sub(2)?;
323     // 1 for (
324     let offset = match context.config.indent_style() {
325         IndentStyle::Block => {
326             shape
327                 .block()
328                 .block_indent(context.config.tab_spaces())
329                 .indent
330         }
331         IndentStyle::Visual => shape.indent + 1,
332     };
333     let list_shape = Shape::legacy(budget, offset);
334     let list_lo = context.snippet_provider.span_after(span, "(");
335     let items = itemize_list(
336         context.snippet_provider,
337         inputs.map(ArgumentKind::Regular).chain(variadic_arg),
338         ")",
339         ",",
340         |arg| match *arg {
341             ArgumentKind::Regular(ref ty) => ty.span().lo(),
342             ArgumentKind::Variadic(start) => start,
343         },
344         |arg| match *arg {
345             ArgumentKind::Regular(ref ty) => ty.span().hi(),
346             ArgumentKind::Variadic(start) => start + BytePos(3),
347         },
348         |arg| match *arg {
349             ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
350             ArgumentKind::Variadic(_) => Some("...".to_owned()),
351         },
352         list_lo,
353         span.hi(),
354         false,
355     );
356
357     let item_vec: Vec<_> = items.collect();
358
359     let tactic = definitive_tactic(
360         &*item_vec,
361         ListTactic::HorizontalVertical,
362         Separator::Comma,
363         budget,
364     );
365     let trailing_separator = if !context.use_block_indent() || variadic {
366         SeparatorTactic::Never
367     } else {
368         context.config.trailing_comma()
369     };
370
371     let fmt = ListFormatting::new(list_shape, context.config)
372         .tactic(tactic)
373         .trailing_separator(trailing_separator)
374         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
375         .preserve_newline(true);
376     let list_str = write_list(&item_vec, &fmt)?;
377
378     let ty_shape = match context.config.indent_style() {
379         // 4 = " -> "
380         IndentStyle::Block => shape.offset_left(4)?,
381         IndentStyle::Visual => shape.block_left(4)?,
382     };
383     let output = match *output {
384         FunctionRetTy::Ty(ref ty) => {
385             let type_str = ty.rewrite(context, ty_shape)?;
386             format!(" -> {}", type_str)
387         }
388         FunctionRetTy::Default(..) => String::new(),
389     };
390
391     let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
392         || !context.use_block_indent()
393     {
394         format!("({})", list_str)
395     } else {
396         format!(
397             "({}{}{})",
398             offset.to_string_with_newline(context.config),
399             list_str,
400             shape.block().indent.to_string_with_newline(context.config),
401         )
402     };
403     if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
404         Some(format!("{}{}", args, output))
405     } else {
406         Some(format!(
407             "{}\n{}{}",
408             args,
409             offset.to_string(context.config),
410             output.trim_left()
411         ))
412     }
413 }
414
415 fn type_bound_colon(context: &RewriteContext) -> &'static str {
416     colon_spaces(
417         context.config.space_before_colon(),
418         context.config.space_after_colon(),
419     )
420 }
421
422 impl Rewrite for ast::WherePredicate {
423     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
424         // FIXME: dead spans?
425         let result = match *self {
426             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
427                 ref bound_generic_params,
428                 ref bounded_ty,
429                 ref bounds,
430                 ..
431             }) => {
432                 let type_str = bounded_ty.rewrite(context, shape)?;
433                 let colon = type_bound_colon(context).trim_right();
434                 let lhs = if let Some(lifetime_str) =
435                     rewrite_lifetime_param(context, shape, bound_generic_params)
436                 {
437                     format!("for<{}> {}{}", lifetime_str, type_str, colon)
438                 } else {
439                     format!("{}{}", type_str, colon)
440                 };
441
442                 rewrite_assign_rhs(context, lhs, bounds, shape)?
443             }
444             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
445                 ref lifetime,
446                 ref bounds,
447                 ..
448             }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
449             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
450                 ref lhs_ty,
451                 ref rhs_ty,
452                 ..
453             }) => {
454                 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
455                 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
456             }
457         };
458
459         Some(result)
460     }
461 }
462
463 impl Rewrite for ast::GenericArg {
464     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
465         match *self {
466             ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
467             ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
468         }
469     }
470 }
471
472 fn rewrite_bounded_lifetime(
473     lt: &ast::Lifetime,
474     bounds: &[ast::GenericBound],
475     context: &RewriteContext,
476     shape: Shape,
477 ) -> Option<String> {
478     let result = lt.rewrite(context, shape)?;
479
480     if bounds.is_empty() {
481         Some(result)
482     } else {
483         let colon = type_bound_colon(context);
484         let overhead = last_line_width(&result) + colon.len();
485         let result = format!(
486             "{}{}{}",
487             result,
488             colon,
489             join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
490         );
491         Some(result)
492     }
493 }
494
495 impl Rewrite for ast::Lifetime {
496     fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
497         Some(rewrite_ident(context, self.ident).to_owned())
498     }
499 }
500
501 impl Rewrite for ast::GenericBound {
502     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
503         match *self {
504             ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
505                 match trait_bound_modifier {
506                     ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
507                     ast::TraitBoundModifier::Maybe => {
508                         let rw = poly_trait_ref.rewrite(context, shape.offset_left(1)?)?;
509                         Some(format!("?{}", rw))
510                     }
511                 }
512             }
513             ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
514         }
515     }
516 }
517
518 impl Rewrite for ast::GenericBounds {
519     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
520         if self.is_empty() {
521             return Some(String::new());
522         }
523
524         let span = mk_sp(self.get(0)?.span().lo(), self.last()?.span().hi());
525         let has_paren = context.snippet(span).starts_with('(');
526         let bounds_shape = if has_paren {
527             shape.offset_left(1)?.sub_width(1)?
528         } else {
529             shape
530         };
531         join_bounds(context, bounds_shape, self, true).map(|s| {
532             if has_paren {
533                 format!("({})", s)
534             } else {
535                 s
536             }
537         })
538     }
539 }
540
541 impl Rewrite for ast::GenericParam {
542     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
543         let mut result = String::with_capacity(128);
544         // FIXME: If there are more than one attributes, this will force multiline.
545         match self.attrs.rewrite(context, shape) {
546             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
547             _ => (),
548         }
549         result.push_str(rewrite_ident(context, self.ident));
550         if !self.bounds.is_empty() {
551             result.push_str(type_bound_colon(context));
552             result.push_str(&self.bounds.rewrite(context, shape)?)
553         }
554         if let ast::GenericParamKind::Type {
555             default: Some(ref def),
556         } = self.kind
557         {
558             let eq_str = match context.config.type_punctuation_density() {
559                 TypeDensity::Compressed => "=",
560                 TypeDensity::Wide => " = ",
561             };
562             result.push_str(eq_str);
563             let budget = shape.width.checked_sub(result.len())?;
564             let rewrite =
565                 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
566             result.push_str(&rewrite);
567         }
568
569         Some(result)
570     }
571 }
572
573 impl Rewrite for ast::PolyTraitRef {
574     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
575         if let Some(lifetime_str) =
576             rewrite_lifetime_param(context, shape, &self.bound_generic_params)
577         {
578             // 6 is "for<> ".len()
579             let extra_offset = lifetime_str.len() + 6;
580             let path_str = self
581                 .trait_ref
582                 .rewrite(context, shape.offset_left(extra_offset)?)?;
583
584             Some(format!("for<{}> {}", lifetime_str, path_str))
585         } else {
586             self.trait_ref.rewrite(context, shape)
587         }
588     }
589 }
590
591 impl Rewrite for ast::TraitRef {
592     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
593         rewrite_path(context, PathContext::Type, None, &self.path, shape)
594     }
595 }
596
597 impl Rewrite for ast::Ty {
598     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
599         match self.node {
600             ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
601                 // we have to consider 'dyn' keyword is used or not!!!
602                 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
603                 // 4 is length of 'dyn '
604                 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
605                 let res = bounds.rewrite(context, shape)?;
606                 if is_dyn {
607                     Some(format!("dyn {}", res))
608                 } else {
609                     Some(res)
610                 }
611             }
612             ast::TyKind::Ptr(ref mt) => {
613                 let prefix = match mt.mutbl {
614                     Mutability::Mutable => "*mut ",
615                     Mutability::Immutable => "*const ",
616                 };
617
618                 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
619             }
620             ast::TyKind::Rptr(ref lifetime, ref mt) => {
621                 let mut_str = format_mutability(mt.mutbl);
622                 let mut_len = mut_str.len();
623                 Some(match *lifetime {
624                     Some(ref lifetime) => {
625                         let lt_budget = shape.width.checked_sub(2 + mut_len)?;
626                         let lt_str = lifetime.rewrite(
627                             context,
628                             Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
629                         )?;
630                         let lt_len = lt_str.len();
631                         let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
632                         format!(
633                             "&{} {}{}",
634                             lt_str,
635                             mut_str,
636                             mt.ty.rewrite(
637                                 context,
638                                 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
639                             )?
640                         )
641                     }
642                     None => {
643                         let budget = shape.width.checked_sub(1 + mut_len)?;
644                         format!(
645                             "&{}{}",
646                             mut_str,
647                             mt.ty.rewrite(
648                                 context,
649                                 Shape::legacy(budget, shape.indent + 1 + mut_len)
650                             )?
651                         )
652                     }
653                 })
654             }
655             // FIXME: we drop any comments here, even though it's a silly place to put
656             // comments.
657             ast::TyKind::Paren(ref ty) => {
658                 let budget = shape.width.checked_sub(2)?;
659                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
660                     .map(|ty_str| format!("({})", ty_str))
661             }
662             ast::TyKind::Slice(ref ty) => {
663                 let budget = shape.width.checked_sub(4)?;
664                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
665                     .map(|ty_str| format!("[{}]", ty_str))
666             }
667             ast::TyKind::Tup(ref items) => rewrite_tuple(
668                 context,
669                 &::utils::ptr_vec_to_ref_vec(items),
670                 self.span,
671                 shape,
672             ),
673             ast::TyKind::Path(ref q_self, ref path) => {
674                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
675             }
676             ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
677                 &**ty,
678                 &*repeats.value,
679                 PairParts::new("[", "; ", "]"),
680                 context,
681                 shape,
682                 SeparatorPlace::Back,
683             ),
684             ast::TyKind::Infer => {
685                 if shape.width >= 1 {
686                     Some("_".to_owned())
687                 } else {
688                     None
689                 }
690             }
691             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
692             ast::TyKind::Never => Some(String::from("!")),
693             ast::TyKind::Mac(ref mac) => {
694                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
695             }
696             ast::TyKind::ImplicitSelf => Some(String::from("")),
697             ast::TyKind::ImplTrait(_, ref it) => it
698                 .rewrite(context, shape)
699                 .map(|it_str| format!("impl {}", it_str)),
700             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
701         }
702     }
703 }
704
705 fn rewrite_bare_fn(
706     bare_fn: &ast::BareFnTy,
707     span: Span,
708     context: &RewriteContext,
709     shape: Shape,
710 ) -> Option<String> {
711     debug!("rewrite_bare_fn {:#?}", shape);
712
713     let mut result = String::with_capacity(128);
714
715     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
716     {
717         result.push_str("for<");
718         // 6 = "for<> ".len(), 4 = "for<".
719         // This doesn't work out so nicely for multiline situation with lots of
720         // rightward drift. If that is a problem, we could use the list stuff.
721         result.push_str(lifetime_str);
722         result.push_str("> ");
723     }
724
725     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
726
727     result.push_str(&format_abi(
728         bare_fn.abi,
729         context.config.force_explicit_abi(),
730         false,
731     ));
732
733     result.push_str("fn");
734
735     let func_ty_shape = if context.use_block_indent() {
736         shape.offset_left(result.len())?
737     } else {
738         shape.visual_indent(result.len()).sub_width(result.len())?
739     };
740
741     let rewrite = format_function_type(
742         bare_fn.decl.inputs.iter(),
743         &bare_fn.decl.output,
744         bare_fn.decl.variadic,
745         span,
746         context,
747         func_ty_shape,
748     )?;
749
750     result.push_str(&rewrite);
751
752     Some(result)
753 }
754
755 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
756     let is_trait = |b: &ast::GenericBound| match b {
757         ast::GenericBound::Outlives(..) => false,
758         ast::GenericBound::Trait(..) => true,
759     };
760     let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
761     let last_trait_index = generic_bounds.iter().rposition(is_trait);
762     let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
763     match (last_trait_index, first_lifetime_index) {
764         (Some(last_trait_index), Some(first_lifetime_index)) => {
765             last_trait_index < first_lifetime_index
766         }
767         _ => true,
768     }
769 }
770
771 fn join_bounds(
772     context: &RewriteContext,
773     shape: Shape,
774     items: &[ast::GenericBound],
775     need_indent: bool,
776 ) -> Option<String> {
777     // Try to join types in a single line
778     let joiner = match context.config.type_punctuation_density() {
779         TypeDensity::Compressed => "+",
780         TypeDensity::Wide => " + ",
781     };
782     let type_strs = items
783         .iter()
784         .map(|item| item.rewrite(context, shape))
785         .collect::<Option<Vec<_>>>()?;
786     let result = type_strs.join(joiner);
787     if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
788         return Some(result);
789     }
790
791     // We need to use multiple lines.
792     let (type_strs, offset) = if need_indent {
793         // Rewrite with additional indentation.
794         let nested_shape = shape.block_indent(context.config.tab_spaces());
795         let type_strs = items
796             .iter()
797             .map(|item| item.rewrite(context, nested_shape))
798             .collect::<Option<Vec<_>>>()?;
799         (type_strs, nested_shape.indent)
800     } else {
801         (type_strs, shape.indent)
802     };
803
804     let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
805         ast::GenericBound::Outlives(..) => true,
806         ast::GenericBound::Trait(..) => last_line_extendable(s),
807     };
808     let mut result = String::with_capacity(128);
809     result.push_str(&type_strs[0]);
810     let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
811     let generic_bounds_in_order = is_generic_bounds_in_order(items);
812     for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
813         if generic_bounds_in_order && can_be_put_on_the_same_line {
814             result.push_str(joiner);
815         } else {
816             result.push_str(&offset.to_string_with_newline(context.config));
817             result.push_str("+ ");
818         }
819         result.push_str(bound_str);
820         can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
821     }
822
823     Some(result)
824 }
825
826 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
827     match ty.node {
828         ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
829         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
830             can_be_overflowed_type(context, &*mutty.ty, len)
831         }
832         _ => false,
833     }
834 }
835
836 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
837 fn rewrite_lifetime_param(
838     context: &RewriteContext,
839     shape: Shape,
840     generic_params: &[ast::GenericParam],
841 ) -> Option<String> {
842     let result = generic_params
843         .iter()
844         .filter(|p| match p.kind {
845             ast::GenericParamKind::Lifetime => true,
846             _ => false,
847         }).map(|lt| lt.rewrite(context, shape))
848         .collect::<Option<Vec<_>>>()?
849         .join(", ");
850     if result.is_empty() {
851         None
852     } else {
853         Some(result)
854     }
855 }