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