]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #3225 from scampi/issue-3224
[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::PathRoot.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 force_separator =
233                     context.inside_macro() && context.snippet(data.span).starts_with("::");
234                 let separator = if path_context == PathContext::Expr || force_separator {
235                     "::"
236                 } else {
237                     ""
238                 };
239                 result.push_str(separator);
240
241                 let generics_str = overflow::rewrite_with_angle_brackets(
242                     context,
243                     "",
244                     param_list.iter(),
245                     shape,
246                     mk_sp(*span_lo, span_hi),
247                 )?;
248
249                 // Update position of last bracket.
250                 *span_lo = context
251                     .snippet_provider
252                     .span_after(mk_sp(*span_lo, span_hi), "<");
253
254                 result.push_str(&generics_str)
255             }
256             ast::GenericArgs::Parenthesized(ref data) => {
257                 let output = match data.output {
258                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
259                     None => FunctionRetTy::Default(source_map::DUMMY_SP),
260                 };
261                 result.push_str(&format_function_type(
262                     data.inputs.iter().map(|x| &**x),
263                     &output,
264                     false,
265                     data.span,
266                     context,
267                     shape,
268                 )?);
269             }
270             _ => (),
271         }
272     }
273
274     Some(result)
275 }
276
277 fn format_function_type<'a, I>(
278     inputs: I,
279     output: &FunctionRetTy,
280     variadic: bool,
281     span: Span,
282     context: &RewriteContext,
283     shape: Shape,
284 ) -> Option<String>
285 where
286     I: ExactSizeIterator,
287     <I as Iterator>::Item: Deref,
288     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
289 {
290     debug!("format_function_type {:#?}", shape);
291
292     let ty_shape = match context.config.indent_style() {
293         // 4 = " -> "
294         IndentStyle::Block => shape.offset_left(4)?,
295         IndentStyle::Visual => shape.block_left(4)?,
296     };
297     let output = match *output {
298         FunctionRetTy::Ty(ref ty) => {
299             let type_str = ty.rewrite(context, ty_shape)?;
300             format!(" -> {}", type_str)
301         }
302         FunctionRetTy::Default(..) => String::new(),
303     };
304
305     // Code for handling variadics is somewhat duplicated for items, but they
306     // are different enough to need some serious refactoring to share code.
307     enum ArgumentKind<T>
308     where
309         T: Deref,
310         <T as Deref>::Target: Rewrite + Spanned,
311     {
312         Regular(T),
313         Variadic(BytePos),
314     }
315
316     let variadic_arg = if variadic {
317         let variadic_start = context.snippet_provider.span_before(span, "...");
318         Some(ArgumentKind::Variadic(variadic_start))
319     } else {
320         None
321     };
322
323     let list_shape = if context.use_block_indent() {
324         Shape::indented(
325             shape.block().indent.block_indent(context.config),
326             context.config,
327         )
328     } else {
329         // 2 for ()
330         let budget = shape.width.checked_sub(2)?;
331         // 1 for (
332         let offset = shape.indent + 1;
333         Shape::legacy(budget, offset)
334     };
335     let list_lo = context.snippet_provider.span_after(span, "(");
336     let items = itemize_list(
337         context.snippet_provider,
338         inputs.map(ArgumentKind::Regular).chain(variadic_arg),
339         ")",
340         ",",
341         |arg| match *arg {
342             ArgumentKind::Regular(ref ty) => ty.span().lo(),
343             ArgumentKind::Variadic(start) => start,
344         },
345         |arg| match *arg {
346             ArgumentKind::Regular(ref ty) => ty.span().hi(),
347             ArgumentKind::Variadic(start) => start + BytePos(3),
348         },
349         |arg| match *arg {
350             ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
351             ArgumentKind::Variadic(_) => Some("...".to_owned()),
352         },
353         list_lo,
354         span.hi(),
355         false,
356     );
357
358     let item_vec: Vec<_> = items.collect();
359
360     // If the return type is multi-lined, then force to use multiple lines for
361     // arguments as well.
362     let tactic = if output.contains('\n') {
363         DefinitiveListTactic::Vertical
364     } else {
365         definitive_tactic(
366             &*item_vec,
367             ListTactic::HorizontalVertical,
368             Separator::Comma,
369             shape.width.saturating_sub(2 + output.len()),
370         )
371     };
372     let trailing_separator = if !context.use_block_indent() || variadic {
373         SeparatorTactic::Never
374     } else {
375         context.config.trailing_comma()
376     };
377
378     let fmt = ListFormatting::new(list_shape, context.config)
379         .tactic(tactic)
380         .trailing_separator(trailing_separator)
381         .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
382         .preserve_newline(true);
383     let list_str = write_list(&item_vec, &fmt)?;
384
385     let args = if tactic == DefinitiveListTactic::Horizontal || !context.use_block_indent() {
386         format!("({})", list_str)
387     } else {
388         format!(
389             "({}{}{})",
390             list_shape.indent.to_string_with_newline(context.config),
391             list_str,
392             shape.block().indent.to_string_with_newline(context.config),
393         )
394     };
395     if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
396         Some(format!("{}{}", args, output))
397     } else {
398         Some(format!(
399             "{}\n{}{}",
400             args,
401             list_shape.indent.to_string(context.config),
402             output.trim_start()
403         ))
404     }
405 }
406
407 fn type_bound_colon(context: &RewriteContext) -> &'static str {
408     colon_spaces(
409         context.config.space_before_colon(),
410         context.config.space_after_colon(),
411     )
412 }
413
414 impl Rewrite for ast::WherePredicate {
415     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
416         // FIXME: dead spans?
417         let result = match *self {
418             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
419                 ref bound_generic_params,
420                 ref bounded_ty,
421                 ref bounds,
422                 ..
423             }) => {
424                 let type_str = bounded_ty.rewrite(context, shape)?;
425                 let colon = type_bound_colon(context).trim_end();
426                 let lhs = if let Some(lifetime_str) =
427                     rewrite_lifetime_param(context, shape, bound_generic_params)
428                 {
429                     format!("for<{}> {}{}", lifetime_str, type_str, colon)
430                 } else {
431                     format!("{}{}", type_str, colon)
432                 };
433
434                 rewrite_assign_rhs(context, lhs, bounds, shape)?
435             }
436             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
437                 ref lifetime,
438                 ref bounds,
439                 ..
440             }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
441             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
442                 ref lhs_ty,
443                 ref rhs_ty,
444                 ..
445             }) => {
446                 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
447                 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
448             }
449         };
450
451         Some(result)
452     }
453 }
454
455 impl Rewrite for ast::GenericArg {
456     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
457         match *self {
458             ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
459             ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
460         }
461     }
462 }
463
464 fn rewrite_bounded_lifetime(
465     lt: &ast::Lifetime,
466     bounds: &[ast::GenericBound],
467     context: &RewriteContext,
468     shape: Shape,
469 ) -> Option<String> {
470     let result = lt.rewrite(context, shape)?;
471
472     if bounds.is_empty() {
473         Some(result)
474     } else {
475         let colon = type_bound_colon(context);
476         let overhead = last_line_width(&result) + colon.len();
477         let result = format!(
478             "{}{}{}",
479             result,
480             colon,
481             join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
482         );
483         Some(result)
484     }
485 }
486
487 impl Rewrite for ast::Lifetime {
488     fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
489         Some(rewrite_ident(context, self.ident).to_owned())
490     }
491 }
492
493 impl Rewrite for ast::GenericBound {
494     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
495         match *self {
496             ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
497                 let snippet = context.snippet(self.span());
498                 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
499                 let rewrite = match trait_bound_modifier {
500                     ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
501                     ast::TraitBoundModifier::Maybe => poly_trait_ref
502                         .rewrite(context, shape.offset_left(1)?)
503                         .map(|s| format!("?{}", s)),
504                 };
505                 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
506             }
507             ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
508         }
509     }
510 }
511
512 impl Rewrite for ast::GenericBounds {
513     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
514         if self.is_empty() {
515             return Some(String::new());
516         }
517
518         join_bounds(context, shape, self, true)
519     }
520 }
521
522 impl Rewrite for ast::GenericParam {
523     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
524         let mut result = String::with_capacity(128);
525         // FIXME: If there are more than one attributes, this will force multiline.
526         match self.attrs.rewrite(context, shape) {
527             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
528             _ => (),
529         }
530         result.push_str(rewrite_ident(context, self.ident));
531         if !self.bounds.is_empty() {
532             result.push_str(type_bound_colon(context));
533             result.push_str(&self.bounds.rewrite(context, shape)?)
534         }
535         if let ast::GenericParamKind::Type {
536             default: Some(ref def),
537         } = self.kind
538         {
539             let eq_str = match context.config.type_punctuation_density() {
540                 TypeDensity::Compressed => "=",
541                 TypeDensity::Wide => " = ",
542             };
543             result.push_str(eq_str);
544             let budget = shape.width.checked_sub(result.len())?;
545             let rewrite =
546                 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
547             result.push_str(&rewrite);
548         }
549
550         Some(result)
551     }
552 }
553
554 impl Rewrite for ast::PolyTraitRef {
555     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
556         if let Some(lifetime_str) =
557             rewrite_lifetime_param(context, shape, &self.bound_generic_params)
558         {
559             // 6 is "for<> ".len()
560             let extra_offset = lifetime_str.len() + 6;
561             let path_str = self
562                 .trait_ref
563                 .rewrite(context, shape.offset_left(extra_offset)?)?;
564
565             Some(format!("for<{}> {}", lifetime_str, path_str))
566         } else {
567             self.trait_ref.rewrite(context, shape)
568         }
569     }
570 }
571
572 impl Rewrite for ast::TraitRef {
573     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
574         rewrite_path(context, PathContext::Type, None, &self.path, shape)
575     }
576 }
577
578 impl Rewrite for ast::Ty {
579     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
580         match self.node {
581             ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
582                 // we have to consider 'dyn' keyword is used or not!!!
583                 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
584                 // 4 is length of 'dyn '
585                 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
586                 let mut res = bounds.rewrite(context, shape)?;
587                 // We may have falsely removed a trailing `+` inside macro call.
588                 if context.inside_macro() && bounds.len() == 1 {
589                     if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
590                         res.push('+');
591                     }
592                 }
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) => {
655                 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
656             }
657             ast::TyKind::Path(ref q_self, ref path) => {
658                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
659             }
660             ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
661                 &**ty,
662                 &*repeats.value,
663                 PairParts::new("[", "; ", "]"),
664                 context,
665                 shape,
666                 SeparatorPlace::Back,
667             ),
668             ast::TyKind::Infer => {
669                 if shape.width >= 1 {
670                     Some("_".to_owned())
671                 } else {
672                     None
673                 }
674             }
675             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
676             ast::TyKind::Never => Some(String::from("!")),
677             ast::TyKind::Mac(ref mac) => {
678                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
679             }
680             ast::TyKind::ImplicitSelf => Some(String::from("")),
681             ast::TyKind::ImplTrait(_, ref it) => it
682                 .rewrite(context, shape)
683                 .map(|it_str| format!("impl {}", it_str)),
684             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
685         }
686     }
687 }
688
689 fn rewrite_bare_fn(
690     bare_fn: &ast::BareFnTy,
691     span: Span,
692     context: &RewriteContext,
693     shape: Shape,
694 ) -> Option<String> {
695     debug!("rewrite_bare_fn {:#?}", shape);
696
697     let mut result = String::with_capacity(128);
698
699     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
700     {
701         result.push_str("for<");
702         // 6 = "for<> ".len(), 4 = "for<".
703         // This doesn't work out so nicely for multiline situation with lots of
704         // rightward drift. If that is a problem, we could use the list stuff.
705         result.push_str(lifetime_str);
706         result.push_str("> ");
707     }
708
709     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
710
711     result.push_str(&format_abi(
712         bare_fn.abi,
713         context.config.force_explicit_abi(),
714         false,
715     ));
716
717     result.push_str("fn");
718
719     let func_ty_shape = if context.use_block_indent() {
720         shape.offset_left(result.len())?
721     } else {
722         shape.visual_indent(result.len()).sub_width(result.len())?
723     };
724
725     let rewrite = format_function_type(
726         bare_fn.decl.inputs.iter(),
727         &bare_fn.decl.output,
728         bare_fn.decl.variadic,
729         span,
730         context,
731         func_ty_shape,
732     )?;
733
734     result.push_str(&rewrite);
735
736     Some(result)
737 }
738
739 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
740     let is_trait = |b: &ast::GenericBound| match b {
741         ast::GenericBound::Outlives(..) => false,
742         ast::GenericBound::Trait(..) => true,
743     };
744     let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
745     let last_trait_index = generic_bounds.iter().rposition(is_trait);
746     let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
747     match (last_trait_index, first_lifetime_index) {
748         (Some(last_trait_index), Some(first_lifetime_index)) => {
749             last_trait_index < first_lifetime_index
750         }
751         _ => true,
752     }
753 }
754
755 fn join_bounds(
756     context: &RewriteContext,
757     shape: Shape,
758     items: &[ast::GenericBound],
759     need_indent: bool,
760 ) -> Option<String> {
761     debug_assert!(!items.is_empty());
762
763     // Try to join types in a single line
764     let joiner = match context.config.type_punctuation_density() {
765         TypeDensity::Compressed => "+",
766         TypeDensity::Wide => " + ",
767     };
768     let type_strs = items
769         .iter()
770         .map(|item| item.rewrite(context, shape))
771         .collect::<Option<Vec<_>>>()?;
772     let result = type_strs.join(joiner);
773     if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
774         return Some(result);
775     }
776
777     // We need to use multiple lines.
778     let (type_strs, offset) = if need_indent {
779         // Rewrite with additional indentation.
780         let nested_shape = shape.block_indent(context.config.tab_spaces());
781         let type_strs = items
782             .iter()
783             .map(|item| item.rewrite(context, nested_shape))
784             .collect::<Option<Vec<_>>>()?;
785         (type_strs, nested_shape.indent)
786     } else {
787         (type_strs, shape.indent)
788     };
789
790     let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
791         ast::GenericBound::Outlives(..) => true,
792         ast::GenericBound::Trait(..) => last_line_extendable(s),
793     };
794     let mut result = String::with_capacity(128);
795     result.push_str(&type_strs[0]);
796     let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
797     let generic_bounds_in_order = is_generic_bounds_in_order(items);
798     for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
799         if generic_bounds_in_order && can_be_put_on_the_same_line {
800             result.push_str(joiner);
801         } else {
802             result.push_str(&offset.to_string_with_newline(context.config));
803             result.push_str("+ ");
804         }
805         result.push_str(bound_str);
806         can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
807     }
808
809     Some(result)
810 }
811
812 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
813     match ty.node {
814         ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
815         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
816             can_be_overflowed_type(context, &*mutty.ty, len)
817         }
818         _ => false,
819     }
820 }
821
822 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
823 fn rewrite_lifetime_param(
824     context: &RewriteContext,
825     shape: Shape,
826     generic_params: &[ast::GenericParam],
827 ) -> Option<String> {
828     let result = generic_params
829         .iter()
830         .filter(|p| match p.kind {
831             ast::GenericParamKind::Lifetime => true,
832             _ => false,
833         })
834         .map(|lt| lt.rewrite(context, shape))
835         .collect::<Option<Vec<_>>>()?
836         .join(", ");
837     if result.is_empty() {
838         None
839     } else {
840         Some(result)
841     }
842 }