]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Cargo fmt and update a test
[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, TypeDensity};
22 use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens, PairParts};
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, first_line_width, format_abi, format_mutability,
29             last_line_width, mk_sp};
30
31 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
32 pub enum PathContext {
33     Expr,
34     Type,
35     Import,
36 }
37
38 // Does not wrap on simple segments.
39 pub fn rewrite_path(
40     context: &RewriteContext,
41     path_context: PathContext,
42     qself: Option<&ast::QSelf>,
43     path: &ast::Path,
44     shape: Shape,
45 ) -> Option<String> {
46     let skip_count = qself.map_or(0, |x| x.position);
47
48     let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
49         "::".to_owned()
50     } else {
51         String::new()
52     };
53
54     let mut span_lo = path.span.lo();
55
56     if let Some(qself) = qself {
57         result.push('<');
58         if context.config.spaces_within_parens_and_brackets() {
59             result.push_str(" ")
60         }
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         if context.config.spaces_within_parens_and_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                     ",",
235                     |param| param.get_span().lo(),
236                     |param| param.get_span().hi(),
237                     |seg| seg.rewrite(context, generics_shape),
238                     list_lo,
239                     span_hi,
240                     false,
241                 );
242                 let generics_str =
243                     format_generics_item_list(context, items, generics_shape, one_line_width)?;
244
245                 // Update position of last bracket.
246                 *span_lo = next_span_lo;
247
248                 format!("{}{}", separator, generics_str)
249             }
250             ast::PathParameters::Parenthesized(ref data) => {
251                 let output = match data.output {
252                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
253                     None => FunctionRetTy::Default(codemap::DUMMY_SP),
254                 };
255                 format_function_type(
256                     data.inputs.iter().map(|x| &**x),
257                     &output,
258                     false,
259                     data.span,
260                     context,
261                     shape,
262                 )?
263             }
264             _ => String::new(),
265         }
266     } else {
267         String::new()
268     };
269
270     Some(format!("{}{}", segment.identifier, params))
271 }
272
273 fn format_function_type<'a, I>(
274     inputs: I,
275     output: &FunctionRetTy,
276     variadic: bool,
277     span: Span,
278     context: &RewriteContext,
279     shape: Shape,
280 ) -> Option<String>
281 where
282     I: ExactSizeIterator,
283     <I as Iterator>::Item: Deref,
284     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
285 {
286     // Code for handling variadics is somewhat duplicated for items, but they
287     // are different enough to need some serious refactoring to share code.
288     enum ArgumentKind<T>
289     where
290         T: Deref,
291         <T as Deref>::Target: Rewrite + Spanned,
292     {
293         Regular(Box<T>),
294         Variadic(BytePos),
295     }
296
297     let variadic_arg = if variadic {
298         let variadic_start = context.codemap.span_before(span, "...");
299         Some(ArgumentKind::Variadic(variadic_start))
300     } else {
301         None
302     };
303
304     // 2 for ()
305     let budget = shape.width.checked_sub(2)?;
306     // 1 for (
307     let offset = match context.config.indent_style() {
308         IndentStyle::Block => {
309             shape
310                 .block()
311                 .block_indent(context.config.tab_spaces())
312                 .indent
313         }
314         IndentStyle::Visual => shape.indent + 1,
315     };
316     let list_shape = Shape::legacy(budget, offset);
317     let list_lo = context.codemap.span_after(span, "(");
318     let items = itemize_list(
319         context.codemap,
320         // FIXME Would be nice to avoid this allocation,
321         // but I couldn't get the types to work out.
322         inputs
323             .map(|i| ArgumentKind::Regular(Box::new(i)))
324             .chain(variadic_arg),
325         ")",
326         ",",
327         |arg| match *arg {
328             ArgumentKind::Regular(ref ty) => ty.span().lo(),
329             ArgumentKind::Variadic(start) => start,
330         },
331         |arg| match *arg {
332             ArgumentKind::Regular(ref ty) => ty.span().hi(),
333             ArgumentKind::Variadic(start) => start + BytePos(3),
334         },
335         |arg| match *arg {
336             ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
337             ArgumentKind::Variadic(_) => Some("...".to_owned()),
338         },
339         list_lo,
340         span.hi(),
341         false,
342     );
343
344     let item_vec: Vec<_> = items.collect();
345
346     let tactic = definitive_tactic(
347         &*item_vec,
348         ListTactic::HorizontalVertical,
349         Separator::Comma,
350         budget,
351     );
352
353     let fmt = ListFormatting {
354         tactic: tactic,
355         separator: ",",
356         trailing_separator: if !context.use_block_indent() || variadic {
357             SeparatorTactic::Never
358         } else {
359             context.config.trailing_comma()
360         },
361         separator_place: SeparatorPlace::Back,
362         shape: list_shape,
363         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
364         preserve_newline: true,
365         config: context.config,
366     };
367
368     let list_str = write_list(&item_vec, &fmt)?;
369
370     let ty_shape = match context.config.indent_style() {
371         // 4 = " -> "
372         IndentStyle::Block => shape.offset_left(4)?,
373         IndentStyle::Visual => shape.block_left(4)?,
374     };
375     let output = match *output {
376         FunctionRetTy::Ty(ref ty) => {
377             let type_str = ty.rewrite(context, ty_shape)?;
378             format!(" -> {}", type_str)
379         }
380         FunctionRetTy::Default(..) => String::new(),
381     };
382
383     let extendable = (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n');
384     let args = wrap_args_with_parens(
385         context,
386         &list_str,
387         extendable,
388         shape.sub_width(first_line_width(&output))?,
389         Shape::indented(offset, context.config),
390     );
391     if last_line_width(&args) + first_line_width(&output) <= shape.width {
392         Some(format!("{}{}", args, output))
393     } else {
394         Some(format!(
395             "{}\n{}{}",
396             args,
397             offset.to_string(context.config),
398             output.trim_left()
399         ))
400     }
401 }
402
403 fn type_bound_colon(context: &RewriteContext) -> &'static str {
404     colon_spaces(
405         context.config.space_before_colon(),
406         context.config.space_after_colon(),
407     )
408 }
409
410 impl Rewrite for ast::WherePredicate {
411     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
412         // TODO: dead spans?
413         let result = match *self {
414             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
415                 ref bound_lifetimes,
416                 ref bounded_ty,
417                 ref bounds,
418                 ..
419             }) => {
420                 let type_str = bounded_ty.rewrite(context, shape)?;
421
422                 let colon = type_bound_colon(context);
423
424                 if !bound_lifetimes.is_empty() {
425                     let lifetime_str: String = bound_lifetimes
426                         .iter()
427                         .map(|lt| lt.rewrite(context, shape))
428                         .collect::<Option<Vec<_>>>()?
429                         .join(", ");
430
431                     // 6 = "for<> ".len()
432                     let used_width = lifetime_str.len() + type_str.len() + colon.len() + 6;
433                     let ty_shape = shape.offset_left(used_width)?;
434                     let bounds = bounds
435                         .iter()
436                         .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
437                         .collect::<Option<Vec<_>>>()?;
438                     let bounds_str = join_bounds(context, ty_shape, &bounds);
439
440                     if context.config.spaces_within_parens_and_brackets()
441                         && !lifetime_str.is_empty()
442                     {
443                         format!(
444                             "for< {} > {}{}{}",
445                             lifetime_str, type_str, colon, bounds_str
446                         )
447                     } else {
448                         format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str)
449                     }
450                 } else {
451                     let used_width = type_str.len() + colon.len();
452                     let ty_shape = match context.config.indent_style() {
453                         IndentStyle::Visual => shape.block_left(used_width)?,
454                         IndentStyle::Block => shape,
455                     };
456                     let bounds = bounds
457                         .iter()
458                         .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
459                         .collect::<Option<Vec<_>>>()?;
460                     let overhead = type_str.len() + colon.len();
461                     let bounds_str = join_bounds(context, ty_shape.sub_width(overhead)?, &bounds);
462
463                     format!("{}{}{}", type_str, colon, bounds_str)
464                 }
465             }
466             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
467                 ref lifetime,
468                 ref bounds,
469                 ..
470             }) => rewrite_bounded_lifetime(lifetime, bounds.iter(), context, shape)?,
471             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
472                 ref lhs_ty,
473                 ref rhs_ty,
474                 ..
475             }) => {
476                 let lhs_ty_str = lhs_ty.rewrite(context, shape)?;
477                 // 3 = " = ".len()
478                 let used_width = 3 + lhs_ty_str.len();
479                 let budget = shape.width.checked_sub(used_width)?;
480                 let rhs_ty_str =
481                     rhs_ty.rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
482                 format!("{} = {}", lhs_ty_str, rhs_ty_str)
483             }
484         };
485
486         Some(result)
487     }
488 }
489
490 impl Rewrite for ast::LifetimeDef {
491     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
492         rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, shape)
493     }
494 }
495
496 fn rewrite_bounded_lifetime<'b, I>(
497     lt: &ast::Lifetime,
498     bounds: I,
499     context: &RewriteContext,
500     shape: Shape,
501 ) -> Option<String>
502 where
503     I: ExactSizeIterator<Item = &'b ast::Lifetime>,
504 {
505     let result = lt.rewrite(context, shape)?;
506
507     if bounds.len() == 0 {
508         Some(result)
509     } else {
510         let appendix = bounds
511             .into_iter()
512             .map(|b| b.rewrite(context, shape))
513             .collect::<Option<Vec<_>>>()?;
514         let colon = type_bound_colon(context);
515         let overhead = last_line_width(&result) + colon.len();
516         let result = format!(
517             "{}{}{}",
518             result,
519             colon,
520             join_bounds(context, shape.sub_width(overhead)?, &appendix)
521         );
522         Some(result)
523     }
524 }
525
526 impl Rewrite for ast::TyParamBound {
527     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
528         match *self {
529             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
530                 tref.rewrite(context, shape)
531             }
532             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
533                 Some(format!(
534                     "?{}",
535                     tref.rewrite(context, shape.offset_left(1)?)?
536                 ))
537             }
538             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
539         }
540     }
541 }
542
543 impl Rewrite for ast::Lifetime {
544     fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
545         Some(pprust::lifetime_to_string(self))
546     }
547 }
548
549 impl Rewrite for ast::TyParamBounds {
550     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
551         let strs = self.iter()
552             .map(|b| b.rewrite(context, shape))
553             .collect::<Option<Vec<_>>>()?;
554         Some(join_bounds(context, shape, &strs))
555     }
556 }
557
558 impl Rewrite for ast::TyParam {
559     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
560         let mut result = String::with_capacity(128);
561         // FIXME: If there are more than one attributes, this will force multiline.
562         match self.attrs.rewrite(context, shape) {
563             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
564             _ => (),
565         }
566         result.push_str(&self.ident.to_string());
567         if !self.bounds.is_empty() {
568             result.push_str(type_bound_colon(context));
569             let strs = self.bounds
570                 .iter()
571                 .map(|ty_bound| ty_bound.rewrite(context, shape))
572                 .collect::<Option<Vec<_>>>()?;
573             result.push_str(&join_bounds(context, shape, &strs));
574         }
575         if let Some(ref def) = self.default {
576             let eq_str = match context.config.type_punctuation_density() {
577                 TypeDensity::Compressed => "=",
578                 TypeDensity::Wide => " = ",
579             };
580             result.push_str(eq_str);
581             let budget = shape.width.checked_sub(result.len())?;
582             let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
583             result.push_str(&rewrite);
584         }
585
586         Some(result)
587     }
588 }
589
590 impl Rewrite for ast::PolyTraitRef {
591     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
592         if !self.bound_lifetimes.is_empty() {
593             let lifetime_str: String = self.bound_lifetimes
594                 .iter()
595                 .map(|lt| lt.rewrite(context, shape))
596                 .collect::<Option<Vec<_>>>()?
597                 .join(", ");
598
599             // 6 is "for<> ".len()
600             let extra_offset = lifetime_str.len() + 6;
601             let path_str = self.trait_ref
602                 .rewrite(context, shape.offset_left(extra_offset)?)?;
603
604             Some(
605                 if context.config.spaces_within_parens_and_brackets() && !lifetime_str.is_empty() {
606                     format!("for< {} > {}", lifetime_str, path_str)
607                 } else {
608                     format!("for<{}> {}", lifetime_str, path_str)
609                 },
610             )
611         } else {
612             self.trait_ref.rewrite(context, shape)
613         }
614     }
615 }
616
617 impl Rewrite for ast::TraitRef {
618     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
619         rewrite_path(context, PathContext::Type, None, &self.path, shape)
620     }
621 }
622
623 impl Rewrite for ast::Ty {
624     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
625         match self.node {
626             ast::TyKind::TraitObject(ref bounds, ..) => bounds.rewrite(context, shape),
627             ast::TyKind::Ptr(ref mt) => {
628                 let prefix = match mt.mutbl {
629                     Mutability::Mutable => "*mut ",
630                     Mutability::Immutable => "*const ",
631                 };
632
633                 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
634             }
635             ast::TyKind::Rptr(ref lifetime, ref mt) => {
636                 let mut_str = format_mutability(mt.mutbl);
637                 let mut_len = mut_str.len();
638                 Some(match *lifetime {
639                     Some(ref lifetime) => {
640                         let lt_budget = shape.width.checked_sub(2 + mut_len)?;
641                         let lt_str = lifetime.rewrite(
642                             context,
643                             Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
644                         )?;
645                         let lt_len = lt_str.len();
646                         let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
647                         format!(
648                             "&{} {}{}",
649                             lt_str,
650                             mut_str,
651                             mt.ty.rewrite(
652                                 context,
653                                 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
654                             )?
655                         )
656                     }
657                     None => {
658                         let budget = shape.width.checked_sub(1 + mut_len)?;
659                         format!(
660                             "&{}{}",
661                             mut_str,
662                             mt.ty.rewrite(
663                                 context,
664                                 Shape::legacy(budget, shape.indent + 1 + mut_len)
665                             )?
666                         )
667                     }
668                 })
669             }
670             // FIXME: we drop any comments here, even though it's a silly place to put
671             // comments.
672             ast::TyKind::Paren(ref ty) => {
673                 let budget = shape.width.checked_sub(2)?;
674                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
675                     .map(|ty_str| {
676                         if context.config.spaces_within_parens_and_brackets() {
677                             format!("( {} )", ty_str)
678                         } else {
679                             format!("({})", ty_str)
680                         }
681                     })
682             }
683             ast::TyKind::Slice(ref ty) => {
684                 let budget = if context.config.spaces_within_parens_and_brackets() {
685                     shape.width.checked_sub(4)?
686                 } else {
687                     shape.width.checked_sub(2)?
688                 };
689                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
690                     .map(|ty_str| {
691                         if context.config.spaces_within_parens_and_brackets() {
692                             format!("[ {} ]", ty_str)
693                         } else {
694                             format!("[{}]", ty_str)
695                         }
696                     })
697             }
698             ast::TyKind::Tup(ref items) => rewrite_tuple(
699                 context,
700                 &::utils::ptr_vec_to_ref_vec(items),
701                 self.span,
702                 shape,
703             ),
704             ast::TyKind::Path(ref q_self, ref path) => {
705                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
706             }
707             ast::TyKind::Array(ref ty, ref repeats) => {
708                 let use_spaces = context.config.spaces_within_parens_and_brackets();
709                 let lbr = if use_spaces { "[ " } else { "[" };
710                 let rbr = if use_spaces { " ]" } else { "]" };
711                 rewrite_pair(
712                     &**ty,
713                     &**repeats,
714                     PairParts::new(lbr, "; ", rbr),
715                     context,
716                     shape,
717                     SeparatorPlace::Back,
718                 )
719             }
720             ast::TyKind::Infer => {
721                 if shape.width >= 1 {
722                     Some("_".to_owned())
723                 } else {
724                     None
725                 }
726             }
727             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
728             ast::TyKind::Never => Some(String::from("!")),
729             ast::TyKind::Mac(..) => None,
730             ast::TyKind::ImplicitSelf => Some(String::from("")),
731             ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
732                 .map(|it_str| format!("impl {}", it_str)),
733             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
734         }
735     }
736 }
737
738 fn rewrite_bare_fn(
739     bare_fn: &ast::BareFnTy,
740     span: Span,
741     context: &RewriteContext,
742     shape: Shape,
743 ) -> Option<String> {
744     let mut result = String::with_capacity(128);
745
746     if !bare_fn.lifetimes.is_empty() {
747         result.push_str("for<");
748         // 6 = "for<> ".len(), 4 = "for<".
749         // This doesn't work out so nicely for mutliline situation with lots of
750         // rightward drift. If that is a problem, we could use the list stuff.
751         result.push_str(&bare_fn
752             .lifetimes
753             .iter()
754             .map(|l| {
755                 l.rewrite(
756                     context,
757                     Shape::legacy(shape.width.checked_sub(6)?, shape.indent + 4),
758                 )
759             })
760             .collect::<Option<Vec<_>>>()?
761             .join(", "));
762         result.push_str("> ");
763     }
764
765     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
766
767     result.push_str(&format_abi(
768         bare_fn.abi,
769         context.config.force_explicit_abi(),
770         false,
771     ));
772
773     result.push_str("fn");
774
775     let func_ty_shape = shape.offset_left(result.len())?;
776
777     let rewrite = format_function_type(
778         bare_fn.decl.inputs.iter(),
779         &bare_fn.decl.output,
780         bare_fn.decl.variadic,
781         span,
782         context,
783         func_ty_shape,
784     )?;
785
786     result.push_str(&rewrite);
787
788     Some(result)
789 }
790
791 pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
792     // Try to join types in a single line
793     let joiner = match context.config.type_punctuation_density() {
794         TypeDensity::Compressed => "+",
795         TypeDensity::Wide => " + ",
796     };
797     let result = type_strs.join(joiner);
798     if result.contains('\n') || result.len() > shape.width {
799         let joiner_indent = shape.indent.block_indent(context.config);
800         let joiner = format!("\n{}+ ", joiner_indent.to_string(context.config));
801         type_strs.join(&joiner)
802     } else {
803         result
804     }
805 }
806
807 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
808     match ty.node {
809         ast::TyKind::Path(..) | ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
810         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
811             can_be_overflowed_type(context, &*mutty.ty, len)
812         }
813         _ => false,
814     }
815 }