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