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