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