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