]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #2499 from davidalber/add-rust-code-of-conduct
[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::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens, PairParts};
22 use items::{format_generics_item_list, generics_shape_from_config};
23 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
24 use macros::{rewrite_macro, MacroPosition};
25 use rewrite::{Rewrite, RewriteContext};
26 use shape::Shape;
27 use spanned::Spanned;
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 mut result = String::with_capacity(128);
204     result.push_str(&segment.identifier.name.as_str());
205
206     let ident_len = result.len();
207     let shape = shape.shrink_left(ident_len)?;
208
209     if let Some(ref params) = segment.parameters {
210         match **params {
211             ast::PathParameters::AngleBracketed(ref data)
212                 if !data.lifetimes.is_empty() || !data.types.is_empty()
213                     || !data.bindings.is_empty() =>
214             {
215                 let param_list = data.lifetimes
216                     .iter()
217                     .map(SegmentParam::LifeTime)
218                     .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
219                     .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
220                     .collect::<Vec<_>>();
221
222                 let next_span_lo = param_list.last().unwrap().get_span().hi() + BytePos(1);
223                 let list_lo = context
224                     .snippet_provider
225                     .span_after(mk_sp(*span_lo, span_hi), "<");
226                 let separator = if path_context == PathContext::Expr {
227                     "::"
228                 } else {
229                     ""
230                 };
231                 result.push_str(separator);
232
233                 let generics_shape =
234                     generics_shape_from_config(context.config, shape, separator.len())?;
235                 let one_line_width = shape.width.checked_sub(separator.len() + 2)?;
236                 let items = itemize_list(
237                     context.snippet_provider,
238                     param_list.into_iter(),
239                     ">",
240                     ",",
241                     |param| param.get_span().lo(),
242                     |param| param.get_span().hi(),
243                     |seg| seg.rewrite(context, generics_shape),
244                     list_lo,
245                     span_hi,
246                     false,
247                 );
248                 let generics_str =
249                     format_generics_item_list(context, items, generics_shape, one_line_width)?;
250
251                 // Update position of last bracket.
252                 *span_lo = next_span_lo;
253
254                 result.push_str(&generics_str)
255             }
256             ast::PathParameters::Parenthesized(ref data) => {
257                 let output = match data.output {
258                     Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
259                     None => FunctionRetTy::Default(codemap::DUMMY_SP),
260                 };
261                 result.push_str(&format_function_type(
262                     data.inputs.iter().map(|x| &**x),
263                     &output,
264                     false,
265                     data.span,
266                     context,
267                     shape,
268                 )?);
269             }
270             _ => (),
271         }
272     }
273
274     Some(result)
275 }
276
277 fn format_function_type<'a, I>(
278     inputs: I,
279     output: &FunctionRetTy,
280     variadic: bool,
281     span: Span,
282     context: &RewriteContext,
283     shape: Shape,
284 ) -> Option<String>
285 where
286     I: ExactSizeIterator,
287     <I as Iterator>::Item: Deref,
288     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
289 {
290     // Code for handling variadics is somewhat duplicated for items, but they
291     // are different enough to need some serious refactoring to share code.
292     enum ArgumentKind<T>
293     where
294         T: Deref,
295         <T as Deref>::Target: Rewrite + Spanned,
296     {
297         Regular(Box<T>),
298         Variadic(BytePos),
299     }
300
301     let variadic_arg = if variadic {
302         let variadic_start = context.snippet_provider.span_before(span, "...");
303         Some(ArgumentKind::Variadic(variadic_start))
304     } else {
305         None
306     };
307
308     // 2 for ()
309     let budget = shape.width.checked_sub(2)?;
310     // 1 for (
311     let offset = match context.config.indent_style() {
312         IndentStyle::Block => {
313             shape
314                 .block()
315                 .block_indent(context.config.tab_spaces())
316                 .indent
317         }
318         IndentStyle::Visual => shape.indent + 1,
319     };
320     let list_shape = Shape::legacy(budget, offset);
321     let list_lo = context.snippet_provider.span_after(span, "(");
322     let items = itemize_list(
323         context.snippet_provider,
324         // FIXME Would be nice to avoid this allocation,
325         // but I couldn't get the types to work out.
326         inputs
327             .map(|i| ArgumentKind::Regular(Box::new(i)))
328             .chain(variadic_arg),
329         ")",
330         ",",
331         |arg| match *arg {
332             ArgumentKind::Regular(ref ty) => ty.span().lo(),
333             ArgumentKind::Variadic(start) => start,
334         },
335         |arg| match *arg {
336             ArgumentKind::Regular(ref ty) => ty.span().hi(),
337             ArgumentKind::Variadic(start) => start + BytePos(3),
338         },
339         |arg| match *arg {
340             ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
341             ArgumentKind::Variadic(_) => Some("...".to_owned()),
342         },
343         list_lo,
344         span.hi(),
345         false,
346     );
347
348     let item_vec: Vec<_> = items.collect();
349
350     let tactic = definitive_tactic(
351         &*item_vec,
352         ListTactic::HorizontalVertical,
353         Separator::Comma,
354         budget,
355     );
356
357     let fmt = ListFormatting {
358         tactic,
359         separator: ",",
360         trailing_separator: if !context.use_block_indent() || variadic {
361             SeparatorTactic::Never
362         } else {
363             context.config.trailing_comma()
364         },
365         separator_place: SeparatorPlace::Back,
366         shape: list_shape,
367         ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
368         preserve_newline: true,
369         config: context.config,
370     };
371
372     let list_str = write_list(&item_vec, &fmt)?;
373
374     let ty_shape = match context.config.indent_style() {
375         // 4 = " -> "
376         IndentStyle::Block => shape.offset_left(4)?,
377         IndentStyle::Visual => shape.block_left(4)?,
378     };
379     let output = match *output {
380         FunctionRetTy::Ty(ref ty) => {
381             let type_str = ty.rewrite(context, ty_shape)?;
382             format!(" -> {}", type_str)
383         }
384         FunctionRetTy::Default(..) => String::new(),
385     };
386
387     let extendable = (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n');
388     let args = wrap_args_with_parens(
389         context,
390         &list_str,
391         extendable,
392         shape.sub_width(first_line_width(&output))?,
393         Shape::indented(offset, context.config),
394     );
395     if last_line_width(&args) + first_line_width(&output) <= shape.width {
396         Some(format!("{}{}", args, output))
397     } else {
398         Some(format!(
399             "{}\n{}{}",
400             args,
401             offset.to_string(context.config),
402             output.trim_left()
403         ))
404     }
405 }
406
407 fn type_bound_colon(context: &RewriteContext) -> &'static str {
408     colon_spaces(
409         context.config.space_before_colon(),
410         context.config.space_after_colon(),
411     )
412 }
413
414 impl Rewrite for ast::WherePredicate {
415     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
416         // TODO: dead spans?
417         let result = match *self {
418             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
419                 ref bound_generic_params,
420                 ref bounded_ty,
421                 ref bounds,
422                 ..
423             }) => {
424                 let type_str = bounded_ty.rewrite(context, shape)?;
425
426                 let colon = type_bound_colon(context);
427
428                 if let Some(lifetime_str) =
429                     rewrite_lifetime_param(context, shape, bound_generic_params)
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) => Some(
533                 format!("?{}", tref.rewrite(context, shape.offset_left(1)?)?),
534             ),
535             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
536         }
537     }
538 }
539
540 impl Rewrite for ast::Lifetime {
541     fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
542         Some(self.ident.to_string())
543     }
544 }
545
546 impl Rewrite for ast::TyParamBounds {
547     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
548         let strs = self.iter()
549             .map(|b| b.rewrite(context, shape))
550             .collect::<Option<Vec<_>>>()?;
551         Some(join_bounds(context, shape, &strs))
552     }
553 }
554
555 impl Rewrite for ast::TyParam {
556     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
557         let mut result = String::with_capacity(128);
558         // FIXME: If there are more than one attributes, this will force multiline.
559         match self.attrs.rewrite(context, shape) {
560             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
561             _ => (),
562         }
563         result.push_str(&self.ident.to_string());
564         if !self.bounds.is_empty() {
565             result.push_str(type_bound_colon(context));
566             let strs = self.bounds
567                 .iter()
568                 .map(|ty_bound| ty_bound.rewrite(context, shape))
569                 .collect::<Option<Vec<_>>>()?;
570             result.push_str(&join_bounds(context, shape, &strs));
571         }
572         if let Some(ref def) = self.default {
573             let eq_str = match context.config.type_punctuation_density() {
574                 TypeDensity::Compressed => "=",
575                 TypeDensity::Wide => " = ",
576             };
577             result.push_str(eq_str);
578             let budget = shape.width.checked_sub(result.len())?;
579             let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
580             result.push_str(&rewrite);
581         }
582
583         Some(result)
584     }
585 }
586
587 impl Rewrite for ast::PolyTraitRef {
588     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
589         if let Some(lifetime_str) =
590             rewrite_lifetime_param(context, shape, &self.bound_generic_params)
591         {
592             // 6 is "for<> ".len()
593             let extra_offset = lifetime_str.len() + 6;
594             let path_str = self.trait_ref
595                 .rewrite(context, shape.offset_left(extra_offset)?)?;
596
597             Some(
598                 if context.config.spaces_within_parens_and_brackets() && !lifetime_str.is_empty() {
599                     format!("for< {} > {}", lifetime_str, path_str)
600                 } else {
601                     format!("for<{}> {}", lifetime_str, path_str)
602                 },
603             )
604         } else {
605             self.trait_ref.rewrite(context, shape)
606         }
607     }
608 }
609
610 impl Rewrite for ast::TraitRef {
611     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
612         rewrite_path(context, PathContext::Type, None, &self.path, shape)
613     }
614 }
615
616 impl Rewrite for ast::Ty {
617     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
618         match self.node {
619             ast::TyKind::TraitObject(ref bounds, ..) => bounds.rewrite(context, shape),
620             ast::TyKind::Ptr(ref mt) => {
621                 let prefix = match mt.mutbl {
622                     Mutability::Mutable => "*mut ",
623                     Mutability::Immutable => "*const ",
624                 };
625
626                 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
627             }
628             ast::TyKind::Rptr(ref lifetime, ref mt) => {
629                 let mut_str = format_mutability(mt.mutbl);
630                 let mut_len = mut_str.len();
631                 Some(match *lifetime {
632                     Some(ref lifetime) => {
633                         let lt_budget = shape.width.checked_sub(2 + mut_len)?;
634                         let lt_str = lifetime.rewrite(
635                             context,
636                             Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
637                         )?;
638                         let lt_len = lt_str.len();
639                         let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
640                         format!(
641                             "&{} {}{}",
642                             lt_str,
643                             mut_str,
644                             mt.ty.rewrite(
645                                 context,
646                                 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
647                             )?
648                         )
649                     }
650                     None => {
651                         let budget = shape.width.checked_sub(1 + mut_len)?;
652                         format!(
653                             "&{}{}",
654                             mut_str,
655                             mt.ty.rewrite(
656                                 context,
657                                 Shape::legacy(budget, shape.indent + 1 + mut_len)
658                             )?
659                         )
660                     }
661                 })
662             }
663             // FIXME: we drop any comments here, even though it's a silly place to put
664             // comments.
665             ast::TyKind::Paren(ref ty) => {
666                 let budget = shape.width.checked_sub(2)?;
667                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
668                     .map(|ty_str| {
669                         if context.config.spaces_within_parens_and_brackets() {
670                             format!("( {} )", ty_str)
671                         } else {
672                             format!("({})", ty_str)
673                         }
674                     })
675             }
676             ast::TyKind::Slice(ref ty) => {
677                 let budget = if context.config.spaces_within_parens_and_brackets() {
678                     shape.width.checked_sub(4)?
679                 } else {
680                     shape.width.checked_sub(2)?
681                 };
682                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
683                     .map(|ty_str| {
684                         if context.config.spaces_within_parens_and_brackets() {
685                             format!("[ {} ]", ty_str)
686                         } else {
687                             format!("[{}]", ty_str)
688                         }
689                     })
690             }
691             ast::TyKind::Tup(ref items) => rewrite_tuple(
692                 context,
693                 &::utils::ptr_vec_to_ref_vec(items),
694                 self.span,
695                 shape,
696             ),
697             ast::TyKind::Path(ref q_self, ref path) => {
698                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
699             }
700             ast::TyKind::Array(ref ty, ref repeats) => {
701                 let use_spaces = context.config.spaces_within_parens_and_brackets();
702                 let lbr = if use_spaces { "[ " } else { "[" };
703                 let rbr = if use_spaces { " ]" } else { "]" };
704                 rewrite_pair(
705                     &**ty,
706                     &**repeats,
707                     PairParts::new(lbr, "; ", rbr),
708                     context,
709                     shape,
710                     SeparatorPlace::Back,
711                 )
712             }
713             ast::TyKind::Infer => {
714                 if shape.width >= 1 {
715                     Some("_".to_owned())
716                 } else {
717                     None
718                 }
719             }
720             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
721             ast::TyKind::Never => Some(String::from("!")),
722             ast::TyKind::Mac(ref mac) => {
723                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
724             }
725             ast::TyKind::ImplicitSelf => Some(String::from("")),
726             ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
727                 .map(|it_str| format!("impl {}", it_str)),
728             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
729         }
730     }
731 }
732
733 fn rewrite_bare_fn(
734     bare_fn: &ast::BareFnTy,
735     span: Span,
736     context: &RewriteContext,
737     shape: Shape,
738 ) -> Option<String> {
739     let mut result = String::with_capacity(128);
740
741     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
742     {
743         result.push_str("for<");
744         // 6 = "for<> ".len(), 4 = "for<".
745         // This doesn't work out so nicely for mutliline situation with lots of
746         // rightward drift. If that is a problem, we could use the list stuff.
747         result.push_str(lifetime_str);
748         result.push_str("> ");
749     }
750
751     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
752
753     result.push_str(&format_abi(
754         bare_fn.abi,
755         context.config.force_explicit_abi(),
756         false,
757     ));
758
759     result.push_str("fn");
760
761     let func_ty_shape = shape.offset_left(result.len())?;
762
763     let rewrite = format_function_type(
764         bare_fn.decl.inputs.iter(),
765         &bare_fn.decl.output,
766         bare_fn.decl.variadic,
767         span,
768         context,
769         func_ty_shape,
770     )?;
771
772     result.push_str(&rewrite);
773
774     Some(result)
775 }
776
777 pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
778     // Try to join types in a single line
779     let joiner = match context.config.type_punctuation_density() {
780         TypeDensity::Compressed => "+",
781         TypeDensity::Wide => " + ",
782     };
783     let result = type_strs.join(joiner);
784     if result.contains('\n') || result.len() > shape.width {
785         let joiner_indent = shape.indent.block_indent(context.config);
786         let joiner = format!("{}+ ", joiner_indent.to_string_with_newline(context.config));
787         type_strs.join(&joiner)
788     } else {
789         result
790     }
791 }
792
793 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
794     match ty.node {
795         ast::TyKind::Path(..) | ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
796         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
797             can_be_overflowed_type(context, &*mutty.ty, len)
798         }
799         _ => false,
800     }
801 }
802
803 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
804 fn rewrite_lifetime_param(
805     context: &RewriteContext,
806     shape: Shape,
807     generic_params: &[ast::GenericParam],
808 ) -> Option<String> {
809     let result = generic_params
810         .iter()
811         .filter(|p| p.is_lifetime_param())
812         .map(|lt| lt.rewrite(context, shape))
813         .collect::<Option<Vec<_>>>()?
814         .join(", ");
815     if result.is_empty() {
816         None
817     } else {
818         Some(result)
819     }
820 }