]> git.lizzy.rs Git - rust.git/blob - src/types.rs
backport new syntax to rustfmt 1.x (#4105)
[rust.git] / src / types.rs
1 use std::iter::ExactSizeIterator;
2 use std::ops::Deref;
3
4 use rustc_ast::ast::{self, FnRetTy, Mutability};
5 use rustc_span::{symbol::kw, BytePos, Span};
6
7 use crate::config::lists::*;
8 use crate::config::{IndentStyle, TypeDensity, Version};
9 use crate::expr::{format_expr, rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, ExprType};
10 use crate::lists::{
11     definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
12 };
13 use crate::macros::{rewrite_macro, MacroPosition};
14 use crate::overflow;
15 use crate::pairs::{rewrite_pair, PairParts};
16 use crate::rewrite::{Rewrite, RewriteContext};
17 use crate::shape::Shape;
18 use crate::source_map::SpanUtils;
19 use crate::spanned::Spanned;
20 use crate::utils::{
21     colon_spaces, extra_offset, first_line_width, format_extern, format_mutability,
22     last_line_extendable, last_line_width, mk_sp, rewrite_ident,
23 };
24
25 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
26 pub(crate) enum PathContext {
27     Expr,
28     Type,
29     Import,
30 }
31
32 // Does not wrap on simple segments.
33 pub(crate) fn rewrite_path(
34     context: &RewriteContext<'_>,
35     path_context: PathContext,
36     qself: Option<&ast::QSelf>,
37     path: &ast::Path,
38     shape: Shape,
39 ) -> Option<String> {
40     let skip_count = qself.map_or(0, |x| x.position);
41
42     let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
43         "::".to_owned()
44     } else {
45         String::new()
46     };
47
48     let mut span_lo = path.span.lo();
49
50     if let Some(qself) = qself {
51         result.push('<');
52
53         let fmt_ty = qself.ty.rewrite(context, shape)?;
54         result.push_str(&fmt_ty);
55
56         if skip_count > 0 {
57             result.push_str(" as ");
58             if path.is_global() && path_context != PathContext::Import {
59                 result.push_str("::");
60             }
61
62             // 3 = ">::".len()
63             let shape = shape.sub_width(3)?;
64
65             result = rewrite_path_segments(
66                 PathContext::Type,
67                 result,
68                 path.segments.iter().take(skip_count),
69                 span_lo,
70                 path.span.hi(),
71                 context,
72                 shape,
73             )?;
74         }
75
76         result.push_str(">::");
77         span_lo = qself.ty.span.hi() + BytePos(1);
78     }
79
80     rewrite_path_segments(
81         path_context,
82         result,
83         path.segments.iter().skip(skip_count),
84         span_lo,
85         path.span.hi(),
86         context,
87         shape,
88     )
89 }
90
91 fn rewrite_path_segments<'a, I>(
92     path_context: PathContext,
93     mut buffer: String,
94     iter: I,
95     mut span_lo: BytePos,
96     span_hi: BytePos,
97     context: &RewriteContext<'_>,
98     shape: Shape,
99 ) -> Option<String>
100 where
101     I: Iterator<Item = &'a ast::PathSegment>,
102 {
103     let mut first = true;
104     let shape = shape.visual_indent(0);
105
106     for segment in iter {
107         // Indicates a global path, shouldn't be rendered.
108         if segment.ident.name == kw::PathRoot {
109             continue;
110         }
111         if first {
112             first = false;
113         } else {
114             buffer.push_str("::");
115         }
116
117         let extra_offset = extra_offset(&buffer, shape);
118         let new_shape = shape.shrink_left(extra_offset)?;
119         let segment_string = rewrite_segment(
120             path_context,
121             segment,
122             &mut span_lo,
123             span_hi,
124             context,
125             new_shape,
126         )?;
127
128         buffer.push_str(&segment_string);
129     }
130
131     Some(buffer)
132 }
133
134 #[derive(Debug)]
135 pub(crate) enum SegmentParam<'a> {
136     Const(&'a ast::AnonConst),
137     LifeTime(&'a ast::Lifetime),
138     Type(&'a ast::Ty),
139     Binding(&'a ast::AssocTyConstraint),
140 }
141
142 impl<'a> SegmentParam<'a> {
143     fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_> {
144         match arg {
145             ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
146             ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
147             ast::GenericArg::Const(const_) => SegmentParam::Const(const_),
148         }
149     }
150 }
151
152 impl<'a> Spanned for SegmentParam<'a> {
153     fn span(&self) -> Span {
154         match *self {
155             SegmentParam::Const(const_) => const_.value.span,
156             SegmentParam::LifeTime(lt) => lt.ident.span,
157             SegmentParam::Type(ty) => ty.span,
158             SegmentParam::Binding(binding) => binding.span,
159         }
160     }
161 }
162
163 impl<'a> Rewrite for SegmentParam<'a> {
164     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
165         match *self {
166             SegmentParam::Const(const_) => const_.rewrite(context, shape),
167             SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
168             SegmentParam::Type(ty) => ty.rewrite(context, shape),
169             SegmentParam::Binding(assoc_ty_constraint) => {
170                 let mut result = match assoc_ty_constraint.kind {
171                     ast::AssocTyConstraintKind::Bound { .. } => {
172                         format!("{}: ", rewrite_ident(context, assoc_ty_constraint.ident))
173                     }
174                     ast::AssocTyConstraintKind::Equality { .. } => {
175                         match context.config.type_punctuation_density() {
176                             TypeDensity::Wide => {
177                                 format!("{} = ", rewrite_ident(context, assoc_ty_constraint.ident))
178                             }
179                             TypeDensity::Compressed => {
180                                 format!("{}=", rewrite_ident(context, assoc_ty_constraint.ident))
181                             }
182                         }
183                     }
184                 };
185
186                 let budget = shape.width.checked_sub(result.len())?;
187                 let rewrite = assoc_ty_constraint
188                     .kind
189                     .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
190                 result.push_str(&rewrite);
191                 Some(result)
192             }
193         }
194     }
195 }
196
197 impl Rewrite for ast::AssocTyConstraintKind {
198     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
199         match self {
200             ast::AssocTyConstraintKind::Equality { ty } => ty.rewrite(context, shape),
201             ast::AssocTyConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
202         }
203     }
204 }
205
206 // Formats a path segment. There are some hacks involved to correctly determine
207 // the segment's associated span since it's not part of the AST.
208 //
209 // The span_lo is assumed to be greater than the end of any previous segment's
210 // parameters and lesser or equal than the start of current segment.
211 //
212 // span_hi is assumed equal to the end of the entire path.
213 //
214 // When the segment contains a positive number of parameters, we update span_lo
215 // so that invariants described above will hold for the next segment.
216 fn rewrite_segment(
217     path_context: PathContext,
218     segment: &ast::PathSegment,
219     span_lo: &mut BytePos,
220     span_hi: BytePos,
221     context: &RewriteContext<'_>,
222     shape: Shape,
223 ) -> Option<String> {
224     let mut result = String::with_capacity(128);
225     result.push_str(rewrite_ident(context, segment.ident));
226
227     let ident_len = result.len();
228     let shape = if context.use_block_indent() {
229         shape.offset_left(ident_len)?
230     } else {
231         shape.shrink_left(ident_len)?
232     };
233
234     if let Some(ref args) = segment.args {
235         match **args {
236             ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
237                 let param_list = data
238                     .args
239                     .iter()
240                     .map(|x| match x {
241                         ast::AngleBracketedArg::Arg(generic_arg) => {
242                             SegmentParam::from_generic_arg(generic_arg)
243                         }
244                         ast::AngleBracketedArg::Constraint(constraint) => {
245                             SegmentParam::Binding(constraint)
246                         }
247                     })
248                     .collect::<Vec<_>>();
249
250                 // HACK: squeeze out the span between the identifier and the parameters.
251                 // The hack is requried so that we don't remove the separator inside macro calls.
252                 // This does not work in the presence of comment, hoping that people are
253                 // sane about where to put their comment.
254                 let separator_snippet = context
255                     .snippet(mk_sp(segment.ident.span.hi(), data.span.lo()))
256                     .trim();
257                 let force_separator = context.inside_macro() && separator_snippet.starts_with("::");
258                 let separator = if path_context == PathContext::Expr || force_separator {
259                     "::"
260                 } else {
261                     ""
262                 };
263                 result.push_str(separator);
264
265                 let generics_str = overflow::rewrite_with_angle_brackets(
266                     context,
267                     "",
268                     param_list.iter(),
269                     shape,
270                     mk_sp(*span_lo, span_hi),
271                 )?;
272
273                 // Update position of last bracket.
274                 *span_lo = context
275                     .snippet_provider
276                     .span_after(mk_sp(*span_lo, span_hi), "<");
277
278                 result.push_str(&generics_str)
279             }
280             ast::GenericArgs::Parenthesized(ref data) => {
281                 result.push_str(&format_function_type(
282                     data.inputs.iter().map(|x| &**x),
283                     &data.output,
284                     false,
285                     data.span,
286                     context,
287                     shape,
288                 )?);
289             }
290             _ => (),
291         }
292     }
293
294     Some(result)
295 }
296
297 fn format_function_type<'a, I>(
298     inputs: I,
299     output: &FnRetTy,
300     variadic: bool,
301     span: Span,
302     context: &RewriteContext<'_>,
303     shape: Shape,
304 ) -> Option<String>
305 where
306     I: ExactSizeIterator,
307     <I as Iterator>::Item: Deref,
308     <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
309 {
310     debug!("format_function_type {:#?}", shape);
311
312     let ty_shape = match context.config.indent_style() {
313         // 4 = " -> "
314         IndentStyle::Block => shape.offset_left(4)?,
315         IndentStyle::Visual => shape.block_left(4)?,
316     };
317     let output = match *output {
318         FnRetTy::Ty(ref ty) => {
319             let type_str = ty.rewrite(context, ty_shape)?;
320             format!(" -> {}", type_str)
321         }
322         FnRetTy::Default(..) => String::new(),
323     };
324
325     let list_shape = if context.use_block_indent() {
326         Shape::indented(
327             shape.block().indent.block_indent(context.config),
328             context.config,
329         )
330     } else {
331         // 2 for ()
332         let budget = shape.width.checked_sub(2)?;
333         // 1 for (
334         let offset = shape.indent + 1;
335         Shape::legacy(budget, offset)
336     };
337
338     let is_inputs_empty = inputs.len() == 0;
339     let list_lo = context.snippet_provider.span_after(span, "(");
340     let (list_str, tactic) = if is_inputs_empty {
341         let tactic = get_tactics(&[], &output, shape);
342         let list_hi = context.snippet_provider.span_before(span, ")");
343         let comment = context
344             .snippet_provider
345             .span_to_snippet(mk_sp(list_lo, list_hi))?
346             .trim();
347         let comment = if comment.starts_with("//") {
348             format!(
349                 "{}{}{}",
350                 &list_shape.indent.to_string_with_newline(context.config),
351                 comment,
352                 &shape.block().indent.to_string_with_newline(context.config)
353             )
354         } else {
355             comment.to_string()
356         };
357         (comment, tactic)
358     } else {
359         let items = itemize_list(
360             context.snippet_provider,
361             inputs,
362             ")",
363             ",",
364             |arg| arg.span().lo(),
365             |arg| arg.span().hi(),
366             |arg| arg.rewrite(context, list_shape),
367             list_lo,
368             span.hi(),
369             false,
370         );
371
372         let item_vec: Vec<_> = items.collect();
373         let tactic = get_tactics(&item_vec, &output, shape);
374         let trailing_separator = if !context.use_block_indent() || variadic {
375             SeparatorTactic::Never
376         } else {
377             context.config.trailing_comma()
378         };
379
380         let fmt = ListFormatting::new(list_shape, context.config)
381             .tactic(tactic)
382             .trailing_separator(trailing_separator)
383             .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
384             .preserve_newline(true);
385         (write_list(&item_vec, &fmt)?, tactic)
386     };
387
388     let args = if tactic == DefinitiveListTactic::Horizontal
389         || !context.use_block_indent()
390         || is_inputs_empty
391     {
392         format!("({})", list_str)
393     } else {
394         format!(
395             "({}{}{})",
396             list_shape.indent.to_string_with_newline(context.config),
397             list_str,
398             shape.block().indent.to_string_with_newline(context.config),
399         )
400     };
401     if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
402         Some(format!("{}{}", args, output))
403     } else {
404         Some(format!(
405             "{}\n{}{}",
406             args,
407             list_shape.indent.to_string(context.config),
408             output.trim_start()
409         ))
410     }
411 }
412
413 fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
414     colon_spaces(context.config)
415 }
416
417 // If the return type is multi-lined, then force to use multiple lines for
418 // arguments as well.
419 fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
420     if output.contains('\n') {
421         DefinitiveListTactic::Vertical
422     } else {
423         definitive_tactic(
424             item_vec,
425             ListTactic::HorizontalVertical,
426             Separator::Comma,
427             // 2 is for the case of ',\n'
428             shape.width.saturating_sub(2 + output.len()),
429         )
430     }
431 }
432
433 impl Rewrite for ast::WherePredicate {
434     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
435         // FIXME: dead spans?
436         let result = match *self {
437             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
438                 ref bound_generic_params,
439                 ref bounded_ty,
440                 ref bounds,
441                 ..
442             }) => {
443                 let type_str = bounded_ty.rewrite(context, shape)?;
444                 let colon = type_bound_colon(context).trim_end();
445                 let lhs = if let Some(lifetime_str) =
446                     rewrite_lifetime_param(context, shape, bound_generic_params)
447                 {
448                     format!("for<{}> {}{}", lifetime_str, type_str, colon)
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::GenericArg {
475     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
476         match *self {
477             ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
478             ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
479             ast::GenericArg::Const(ref const_) => const_.rewrite(context, shape),
480         }
481     }
482 }
483
484 fn rewrite_bounded_lifetime(
485     lt: &ast::Lifetime,
486     bounds: &[ast::GenericBound],
487     context: &RewriteContext<'_>,
488     shape: Shape,
489 ) -> Option<String> {
490     let result = lt.rewrite(context, shape)?;
491
492     if bounds.is_empty() {
493         Some(result)
494     } else {
495         let colon = type_bound_colon(context);
496         let overhead = last_line_width(&result) + colon.len();
497         let result = format!(
498             "{}{}{}",
499             result,
500             colon,
501             join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
502         );
503         Some(result)
504     }
505 }
506
507 impl Rewrite for ast::AnonConst {
508     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
509         format_expr(&self.value, ExprType::SubExpression, context, shape)
510     }
511 }
512
513 impl Rewrite for ast::Lifetime {
514     fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
515         Some(rewrite_ident(context, self.ident).to_owned())
516     }
517 }
518
519 impl Rewrite for ast::GenericBound {
520     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
521         match *self {
522             ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
523                 let snippet = context.snippet(self.span());
524                 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
525                 let rewrite = match trait_bound_modifier {
526                     ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
527                     ast::TraitBoundModifier::Maybe => poly_trait_ref
528                         .rewrite(context, shape.offset_left(1)?)
529                         .map(|s| format!("?{}", s)),
530                     ast::TraitBoundModifier::MaybeConst => poly_trait_ref
531                         .rewrite(context, shape.offset_left(7)?)
532                         .map(|s| format!("?const {}", s)),
533                     ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
534                         .rewrite(context, shape.offset_left(8)?)
535                         .map(|s| format!("?const ?{}", s)),
536                 };
537                 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
538             }
539             ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
540         }
541     }
542 }
543
544 impl Rewrite for ast::GenericBounds {
545     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
546         if self.is_empty() {
547             return Some(String::new());
548         }
549
550         join_bounds(context, shape, self, true)
551     }
552 }
553
554 impl Rewrite for ast::GenericParam {
555     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
556         let mut result = String::with_capacity(128);
557         // FIXME: If there are more than one attributes, this will force multiline.
558         match self.attrs.rewrite(context, shape) {
559             Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
560             _ => (),
561         }
562
563         if let rustc_ast::ast::GenericParamKind::Const { ref ty } = &self.kind {
564             result.push_str("const ");
565             result.push_str(rewrite_ident(context, self.ident));
566             result.push_str(": ");
567             result.push_str(&ty.rewrite(context, shape)?);
568         } else {
569             result.push_str(rewrite_ident(context, self.ident));
570         }
571
572         if !self.bounds.is_empty() {
573             result.push_str(type_bound_colon(context));
574             result.push_str(&self.bounds.rewrite(context, shape)?)
575         }
576         if let ast::GenericParamKind::Type {
577             default: Some(ref def),
578         } = self.kind
579         {
580             let eq_str = match context.config.type_punctuation_density() {
581                 TypeDensity::Compressed => "=",
582                 TypeDensity::Wide => " = ",
583             };
584             result.push_str(eq_str);
585             let budget = shape.width.checked_sub(result.len())?;
586             let rewrite =
587                 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
588             result.push_str(&rewrite);
589         }
590
591         Some(result)
592     }
593 }
594
595 impl Rewrite for ast::PolyTraitRef {
596     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
597         if let Some(lifetime_str) =
598             rewrite_lifetime_param(context, shape, &self.bound_generic_params)
599         {
600             // 6 is "for<> ".len()
601             let extra_offset = lifetime_str.len() + 6;
602             let path_str = self
603                 .trait_ref
604                 .rewrite(context, shape.offset_left(extra_offset)?)?;
605
606             Some(format!("for<{}> {}", lifetime_str, path_str))
607         } else {
608             self.trait_ref.rewrite(context, shape)
609         }
610     }
611 }
612
613 impl Rewrite for ast::TraitRef {
614     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
615         rewrite_path(context, PathContext::Type, None, &self.path, shape)
616     }
617 }
618
619 impl Rewrite for ast::Ty {
620     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
621         match self.kind {
622             ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
623                 // we have to consider 'dyn' keyword is used or not!!!
624                 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
625                 // 4 is length of 'dyn '
626                 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
627                 let mut res = bounds.rewrite(context, shape)?;
628                 // We may have falsely removed a trailing `+` inside macro call.
629                 if context.inside_macro() && bounds.len() == 1 {
630                     if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
631                         res.push('+');
632                     }
633                 }
634                 if is_dyn {
635                     Some(format!("dyn {}", res))
636                 } else {
637                     Some(res)
638                 }
639             }
640             ast::TyKind::Ptr(ref mt) => {
641                 let prefix = match mt.mutbl {
642                     Mutability::Mut => "*mut ",
643                     Mutability::Not => "*const ",
644                 };
645
646                 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
647             }
648             ast::TyKind::Rptr(ref lifetime, ref mt) => {
649                 let mut_str = format_mutability(mt.mutbl);
650                 let mut_len = mut_str.len();
651                 Some(match *lifetime {
652                     Some(ref lifetime) => {
653                         let lt_budget = shape.width.checked_sub(2 + mut_len)?;
654                         let lt_str = lifetime.rewrite(
655                             context,
656                             Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
657                         )?;
658                         let lt_len = lt_str.len();
659                         let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
660                         format!(
661                             "&{} {}{}",
662                             lt_str,
663                             mut_str,
664                             mt.ty.rewrite(
665                                 context,
666                                 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
667                             )?
668                         )
669                     }
670                     None => {
671                         let budget = shape.width.checked_sub(1 + mut_len)?;
672                         format!(
673                             "&{}{}",
674                             mut_str,
675                             mt.ty.rewrite(
676                                 context,
677                                 Shape::legacy(budget, shape.indent + 1 + mut_len)
678                             )?
679                         )
680                     }
681                 })
682             }
683             // FIXME: we drop any comments here, even though it's a silly place to put
684             // comments.
685             ast::TyKind::Paren(ref ty) => {
686                 if context.config.version() == Version::One
687                     || context.config.indent_style() == IndentStyle::Visual
688                 {
689                     let budget = shape.width.checked_sub(2)?;
690                     return ty
691                         .rewrite(context, Shape::legacy(budget, shape.indent + 1))
692                         .map(|ty_str| format!("({})", ty_str));
693                 }
694
695                 // 2 = ()
696                 if let Some(sh) = shape.sub_width(2) {
697                     if let Some(ref s) = ty.rewrite(context, sh) {
698                         if !s.contains('\n') {
699                             return Some(format!("({})", s));
700                         }
701                     }
702                 }
703
704                 let indent_str = shape.indent.to_string_with_newline(context.config);
705                 let shape = shape
706                     .block_indent(context.config.tab_spaces())
707                     .with_max_width(context.config);
708                 let rw = ty.rewrite(context, shape)?;
709                 Some(format!(
710                     "({}{}{})",
711                     shape.to_string_with_newline(context.config),
712                     rw,
713                     indent_str
714                 ))
715             }
716             ast::TyKind::Slice(ref ty) => {
717                 let budget = shape.width.checked_sub(4)?;
718                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
719                     .map(|ty_str| format!("[{}]", ty_str))
720             }
721             ast::TyKind::Tup(ref items) => {
722                 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
723             }
724             ast::TyKind::Path(ref q_self, ref path) => {
725                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
726             }
727             ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
728                 &**ty,
729                 &*repeats.value,
730                 PairParts::new("[", "; ", "]"),
731                 context,
732                 shape,
733                 SeparatorPlace::Back,
734             ),
735             ast::TyKind::Infer => {
736                 if shape.width >= 1 {
737                     Some("_".to_owned())
738                 } else {
739                     None
740                 }
741             }
742             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
743             ast::TyKind::Never => Some(String::from("!")),
744             ast::TyKind::MacCall(ref mac) => {
745                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
746             }
747             ast::TyKind::ImplicitSelf => Some(String::from("")),
748             ast::TyKind::ImplTrait(_, ref it) => {
749                 // Empty trait is not a parser error.
750                 if it.is_empty() {
751                     return Some("impl".to_owned());
752                 }
753                 let rw = if context.config.version() == Version::One {
754                     it.rewrite(context, shape)
755                 } else {
756                     join_bounds(context, shape, it, false)
757                 };
758                 rw.map(|it_str| {
759                     let space = if it_str.is_empty() { "" } else { " " };
760                     format!("impl{}{}", space, it_str)
761                 })
762             }
763             ast::TyKind::CVarArgs => Some("...".to_owned()),
764             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
765         }
766     }
767 }
768
769 fn rewrite_bare_fn(
770     bare_fn: &ast::BareFnTy,
771     span: Span,
772     context: &RewriteContext<'_>,
773     shape: Shape,
774 ) -> Option<String> {
775     debug!("rewrite_bare_fn {:#?}", shape);
776
777     let mut result = String::with_capacity(128);
778
779     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
780     {
781         result.push_str("for<");
782         // 6 = "for<> ".len(), 4 = "for<".
783         // This doesn't work out so nicely for multiline situation with lots of
784         // rightward drift. If that is a problem, we could use the list stuff.
785         result.push_str(lifetime_str);
786         result.push_str("> ");
787     }
788
789     result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
790
791     result.push_str(&format_extern(
792         bare_fn.ext,
793         context.config.force_explicit_abi(),
794         false,
795     ));
796
797     result.push_str("fn");
798
799     let func_ty_shape = if context.use_block_indent() {
800         shape.offset_left(result.len())?
801     } else {
802         shape.visual_indent(result.len()).sub_width(result.len())?
803     };
804
805     let rewrite = format_function_type(
806         bare_fn.decl.inputs.iter(),
807         &bare_fn.decl.output,
808         bare_fn.decl.c_variadic(),
809         span,
810         context,
811         func_ty_shape,
812     )?;
813
814     result.push_str(&rewrite);
815
816     Some(result)
817 }
818
819 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
820     let is_trait = |b: &ast::GenericBound| match b {
821         ast::GenericBound::Outlives(..) => false,
822         ast::GenericBound::Trait(..) => true,
823     };
824     let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
825     let last_trait_index = generic_bounds.iter().rposition(is_trait);
826     let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
827     match (last_trait_index, first_lifetime_index) {
828         (Some(last_trait_index), Some(first_lifetime_index)) => {
829             last_trait_index < first_lifetime_index
830         }
831         _ => true,
832     }
833 }
834
835 fn join_bounds(
836     context: &RewriteContext<'_>,
837     shape: Shape,
838     items: &[ast::GenericBound],
839     need_indent: bool,
840 ) -> Option<String> {
841     debug_assert!(!items.is_empty());
842
843     // Try to join types in a single line
844     let joiner = match context.config.type_punctuation_density() {
845         TypeDensity::Compressed => "+",
846         TypeDensity::Wide => " + ",
847     };
848     let type_strs = items
849         .iter()
850         .map(|item| item.rewrite(context, shape))
851         .collect::<Option<Vec<_>>>()?;
852     let result = type_strs.join(joiner);
853     if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
854         return Some(result);
855     }
856
857     // We need to use multiple lines.
858     let (type_strs, offset) = if need_indent {
859         // Rewrite with additional indentation.
860         let nested_shape = shape
861             .block_indent(context.config.tab_spaces())
862             .with_max_width(context.config);
863         let type_strs = items
864             .iter()
865             .map(|item| item.rewrite(context, nested_shape))
866             .collect::<Option<Vec<_>>>()?;
867         (type_strs, nested_shape.indent)
868     } else {
869         (type_strs, shape.indent)
870     };
871
872     let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
873         ast::GenericBound::Outlives(..) => true,
874         ast::GenericBound::Trait(..) => last_line_extendable(s),
875     };
876     let mut result = String::with_capacity(128);
877     result.push_str(&type_strs[0]);
878     let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
879     let generic_bounds_in_order = is_generic_bounds_in_order(items);
880     for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
881         if generic_bounds_in_order && can_be_put_on_the_same_line {
882             result.push_str(joiner);
883         } else {
884             result.push_str(&offset.to_string_with_newline(context.config));
885             result.push_str("+ ");
886         }
887         result.push_str(bound_str);
888         can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
889     }
890
891     Some(result)
892 }
893
894 pub(crate) fn can_be_overflowed_type(
895     context: &RewriteContext<'_>,
896     ty: &ast::Ty,
897     len: usize,
898 ) -> bool {
899     match ty.kind {
900         ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
901         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
902             can_be_overflowed_type(context, &*mutty.ty, len)
903         }
904         _ => false,
905     }
906 }
907
908 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
909 fn rewrite_lifetime_param(
910     context: &RewriteContext<'_>,
911     shape: Shape,
912     generic_params: &[ast::GenericParam],
913 ) -> Option<String> {
914     let result = generic_params
915         .iter()
916         .filter(|p| match p.kind {
917             ast::GenericParamKind::Lifetime => true,
918             _ => false,
919         })
920         .map(|lt| lt.rewrite(context, shape))
921         .collect::<Option<Vec<_>>>()?
922         .join(", ");
923     if result.is_empty() {
924         None
925     } else {
926         Some(result)
927     }
928 }