]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Fixed comment dropped between & and type issue (#4482)
[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, Pos, 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                 let mut result = String::with_capacity(128);
652                 result.push_str("&");
653                 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
654                 let mut cmnt_lo = ref_hi;
655
656                 if let Some(ref lifetime) = *lifetime {
657                     let lt_budget = shape.width.checked_sub(2 + mut_len)?;
658                     let lt_str = lifetime.rewrite(
659                         context,
660                         Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
661                     )?;
662                     let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
663                     if contains_comment(context.snippet(before_lt_span)) {
664                         result = combine_strs_with_missing_comments(
665                             context,
666                             &result,
667                             &lt_str,
668                             before_lt_span,
669                             shape,
670                             true,
671                         )?;
672                     } else {
673                         result.push_str(&lt_str);
674                     }
675                     result.push_str(" ");
676                     cmnt_lo = lifetime.ident.span.hi();
677                 }
678
679                 if ast::Mutability::Mut == mt.mutbl {
680                     let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
681                     let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
682                     if contains_comment(context.snippet(before_mut_span)) {
683                         result = combine_strs_with_missing_comments(
684                             context,
685                             result.trim_end(),
686                             mut_str,
687                             before_mut_span,
688                             shape,
689                             true,
690                         )?;
691                     } else {
692                         result.push_str(mut_str);
693                     }
694                     cmnt_lo = mut_hi;
695                 }
696
697                 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
698                 if contains_comment(context.snippet(before_ty_span)) {
699                     result = combine_strs_with_missing_comments(
700                         context,
701                         result.trim_end(),
702                         &mt.ty.rewrite(&context, shape)?,
703                         before_ty_span,
704                         shape,
705                         true,
706                     )?;
707                 } else {
708                     let used_width = last_line_width(&result);
709                     let budget = shape.width.checked_sub(used_width)?;
710                     let ty_str = mt
711                         .ty
712                         .rewrite(&context, Shape::legacy(budget, shape.indent + used_width))?;
713                     result.push_str(&ty_str);
714                 }
715
716                 Some(result)
717             }
718             // FIXME: we drop any comments here, even though it's a silly place to put
719             // comments.
720             ast::TyKind::Paren(ref ty) => {
721                 if context.config.version() == Version::One
722                     || context.config.indent_style() == IndentStyle::Visual
723                 {
724                     let budget = shape.width.checked_sub(2)?;
725                     return ty
726                         .rewrite(context, Shape::legacy(budget, shape.indent + 1))
727                         .map(|ty_str| format!("({})", ty_str));
728                 }
729
730                 // 2 = ()
731                 if let Some(sh) = shape.sub_width(2) {
732                     if let Some(ref s) = ty.rewrite(context, sh) {
733                         if !s.contains('\n') {
734                             return Some(format!("({})", s));
735                         }
736                     }
737                 }
738
739                 let indent_str = shape.indent.to_string_with_newline(context.config);
740                 let shape = shape
741                     .block_indent(context.config.tab_spaces())
742                     .with_max_width(context.config);
743                 let rw = ty.rewrite(context, shape)?;
744                 Some(format!(
745                     "({}{}{})",
746                     shape.to_string_with_newline(context.config),
747                     rw,
748                     indent_str
749                 ))
750             }
751             ast::TyKind::Slice(ref ty) => {
752                 let budget = shape.width.checked_sub(4)?;
753                 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
754                     .map(|ty_str| format!("[{}]", ty_str))
755             }
756             ast::TyKind::Tup(ref items) => {
757                 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
758             }
759             ast::TyKind::Path(ref q_self, ref path) => {
760                 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
761             }
762             ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
763                 &**ty,
764                 &*repeats.value,
765                 PairParts::new("[", "; ", "]"),
766                 context,
767                 shape,
768                 SeparatorPlace::Back,
769             ),
770             ast::TyKind::Infer => {
771                 if shape.width >= 1 {
772                     Some("_".to_owned())
773                 } else {
774                     None
775                 }
776             }
777             ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
778             ast::TyKind::Never => Some(String::from("!")),
779             ast::TyKind::MacCall(ref mac) => {
780                 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
781             }
782             ast::TyKind::ImplicitSelf => Some(String::from("")),
783             ast::TyKind::ImplTrait(_, ref it) => {
784                 // Empty trait is not a parser error.
785                 if it.is_empty() {
786                     return Some("impl".to_owned());
787                 }
788                 let rw = if context.config.version() == Version::One {
789                     it.rewrite(context, shape)
790                 } else {
791                     join_bounds(context, shape, it, false)
792                 };
793                 rw.map(|it_str| {
794                     let space = if it_str.is_empty() { "" } else { " " };
795                     format!("impl{}{}", space, it_str)
796                 })
797             }
798             ast::TyKind::CVarArgs => Some("...".to_owned()),
799             ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
800         }
801     }
802 }
803
804 fn rewrite_bare_fn(
805     bare_fn: &ast::BareFnTy,
806     span: Span,
807     context: &RewriteContext<'_>,
808     shape: Shape,
809 ) -> Option<String> {
810     debug!("rewrite_bare_fn {:#?}", shape);
811
812     let mut result = String::with_capacity(128);
813
814     if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
815     {
816         result.push_str("for<");
817         // 6 = "for<> ".len(), 4 = "for<".
818         // This doesn't work out so nicely for multiline situation with lots of
819         // rightward drift. If that is a problem, we could use the list stuff.
820         result.push_str(lifetime_str);
821         result.push_str("> ");
822     }
823
824     result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
825
826     result.push_str(&format_extern(
827         bare_fn.ext,
828         context.config.force_explicit_abi(),
829         false,
830     ));
831
832     result.push_str("fn");
833
834     let func_ty_shape = if context.use_block_indent() {
835         shape.offset_left(result.len())?
836     } else {
837         shape.visual_indent(result.len()).sub_width(result.len())?
838     };
839
840     let rewrite = format_function_type(
841         bare_fn.decl.inputs.iter(),
842         &bare_fn.decl.output,
843         bare_fn.decl.c_variadic(),
844         span,
845         context,
846         func_ty_shape,
847     )?;
848
849     result.push_str(&rewrite);
850
851     Some(result)
852 }
853
854 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
855     let is_trait = |b: &ast::GenericBound| match b {
856         ast::GenericBound::Outlives(..) => false,
857         ast::GenericBound::Trait(..) => true,
858     };
859     let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
860     let last_trait_index = generic_bounds.iter().rposition(is_trait);
861     let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
862     match (last_trait_index, first_lifetime_index) {
863         (Some(last_trait_index), Some(first_lifetime_index)) => {
864             last_trait_index < first_lifetime_index
865         }
866         _ => true,
867     }
868 }
869
870 fn join_bounds(
871     context: &RewriteContext<'_>,
872     shape: Shape,
873     items: &[ast::GenericBound],
874     need_indent: bool,
875 ) -> Option<String> {
876     debug_assert!(!items.is_empty());
877
878     // Try to join types in a single line
879     let joiner = match context.config.type_punctuation_density() {
880         TypeDensity::Compressed => "+",
881         TypeDensity::Wide => " + ",
882     };
883     let type_strs = items
884         .iter()
885         .map(|item| item.rewrite(context, shape))
886         .collect::<Option<Vec<_>>>()?;
887     let result = type_strs.join(joiner);
888     if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
889         return Some(result);
890     }
891
892     // We need to use multiple lines.
893     let (type_strs, offset) = if need_indent {
894         // Rewrite with additional indentation.
895         let nested_shape = shape
896             .block_indent(context.config.tab_spaces())
897             .with_max_width(context.config);
898         let type_strs = items
899             .iter()
900             .map(|item| item.rewrite(context, nested_shape))
901             .collect::<Option<Vec<_>>>()?;
902         (type_strs, nested_shape.indent)
903     } else {
904         (type_strs, shape.indent)
905     };
906
907     let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
908         ast::GenericBound::Outlives(..) => true,
909         ast::GenericBound::Trait(..) => last_line_extendable(s),
910     };
911     let mut result = String::with_capacity(128);
912     result.push_str(&type_strs[0]);
913     let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
914     let generic_bounds_in_order = is_generic_bounds_in_order(items);
915     for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
916         if generic_bounds_in_order && can_be_put_on_the_same_line {
917             result.push_str(joiner);
918         } else {
919             result.push_str(&offset.to_string_with_newline(context.config));
920             result.push_str("+ ");
921         }
922         result.push_str(bound_str);
923         can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
924     }
925
926     Some(result)
927 }
928
929 pub(crate) fn can_be_overflowed_type(
930     context: &RewriteContext<'_>,
931     ty: &ast::Ty,
932     len: usize,
933 ) -> bool {
934     match ty.kind {
935         ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
936         ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
937             can_be_overflowed_type(context, &*mutty.ty, len)
938         }
939         _ => false,
940     }
941 }
942
943 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
944 fn rewrite_lifetime_param(
945     context: &RewriteContext<'_>,
946     shape: Shape,
947     generic_params: &[ast::GenericParam],
948 ) -> Option<String> {
949     let result = generic_params
950         .iter()
951         .filter(|p| match p.kind {
952             ast::GenericParamKind::Lifetime => true,
953             _ => false,
954         })
955         .map(|lt| lt.rewrite(context, shape))
956         .collect::<Option<Vec<_>>>()?
957         .join(", ");
958     if result.is_empty() {
959         None
960     } else {
961         Some(result)
962     }
963 }