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