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