1 use std::iter::ExactSizeIterator;
2 use std::ops::Deref;
3
4 use rustc_ast::ast::{self, FnRetTy, Mutability, Term};
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.
rewrite_path( context: &RewriteContext<'_>, path_context: PathContext, qself: &Option<ptr::P<ast::QSelf>>, path: &ast::Path, shape: Shape, ) -> Option<String>38 pub(crate) fn rewrite_path(
39 context: &RewriteContext<'_>,
40 path_context: PathContext,
41 qself: &Option<ptr::P<ast::QSelf>>,
42 path: &ast::Path,
43 shape: Shape,
44 ) -> Option<String> {
45 let skip_count = qself.as_ref().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
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>,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::AssocConstraint),
145 }
146
147 impl<'a> SegmentParam<'a> {
from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_>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> {
span(&self) -> Span158 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> {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>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::AssocConstraint {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>180 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
181 use ast::AssocConstraintKind::{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::AssocConstraintKind {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>210 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
211 match self {
212 ast::AssocConstraintKind::Equality { term } => match term {
213 Term::Ty(ty) => ty.rewrite(context, shape),
214 Term::Const(c) => c.rewrite(context, shape),
215 },
216 ast::AssocConstraintKind::Bound { bounds } => bounds.rewrite(context, shape),
217 }
218 }
219 }
220
221 // Formats a path segment. There are some hacks involved to correctly determine
222 // the segment's associated span since it's not part of the AST.
223 //
224 // The span_lo is assumed to be greater than the end of any previous segment's
225 // parameters and lesser or equal than the start of current segment.
226 //
227 // span_hi is assumed equal to the end of the entire path.
228 //
229 // When the segment contains a positive number of parameters, we update span_lo
230 // 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>231 fn rewrite_segment(
232 path_context: PathContext,
233 segment: &ast::PathSegment,
234 span_lo: &mut BytePos,
235 span_hi: BytePos,
236 context: &RewriteContext<'_>,
237 shape: Shape,
238 ) -> Option<String> {
239 let mut result = String::with_capacity(128);
240 result.push_str(rewrite_ident(context, segment.ident));
241
242 let ident_len = result.len();
243 let shape = if context.use_block_indent() {
244 shape.offset_left(ident_len)?
245 } else {
246 shape.shrink_left(ident_len)?
247 };
248
249 if let Some(ref args) = segment.args {
250 let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?;
251 match **args {
252 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
253 // HACK: squeeze out the span between the identifier and the parameters.
254 // The hack is required so that we don't remove the separator inside macro calls.
255 // This does not work in the presence of comment, hoping that people are
256 // sane about where to put their comment.
257 let separator_snippet = context
258 .snippet(mk_sp(segment.ident.span.hi(), data.span.lo()))
259 .trim();
260 let force_separator = context.inside_macro() && separator_snippet.starts_with("::");
261 let separator = if path_context == PathContext::Expr || force_separator {
262 "::"
263 } else {
264 ""
265 };
266 result.push_str(separator);
267
268 // Update position of last bracket.
269 *span_lo = context
270 .snippet_provider
271 .span_after(mk_sp(*span_lo, span_hi), "<");
272 }
273 _ => (),
274 }
275 result.push_str(&generics_str)
276 }
277
278 Some(result)
279 }
280
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,281 fn format_function_type<'a, I>(
282 inputs: I,
283 output: &FnRetTy,
284 variadic: bool,
285 span: Span,
286 context: &RewriteContext<'_>,
287 shape: Shape,
288 ) -> Option<String>
289 where
290 I: ExactSizeIterator,
291 <I as Iterator>::Item: Deref,
292 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
293 {
294 debug!("format_function_type {:#?}", shape);
295
296 let ty_shape = match context.config.indent_style() {
297 // 4 = " -> "
298 IndentStyle::Block => shape.offset_left(4)?,
299 IndentStyle::Visual => shape.block_left(4)?,
300 };
301 let output = match *output {
302 FnRetTy::Ty(ref ty) => {
303 let type_str = ty.rewrite(context, ty_shape)?;
304 format!(" -> {}", type_str)
305 }
306 FnRetTy::Default(..) => String::new(),
307 };
308
309 let list_shape = if context.use_block_indent() {
310 Shape::indented(
311 shape.block().indent.block_indent(context.config),
312 context.config,
313 )
314 } else {
315 // 2 for ()
316 let budget = shape.width.checked_sub(2)?;
317 // 1 for (
318 let offset = shape.indent + 1;
319 Shape::legacy(budget, offset)
320 };
321
322 let is_inputs_empty = inputs.len() == 0;
323 let list_lo = context.snippet_provider.span_after(span, "(");
324 let (list_str, tactic) = if is_inputs_empty {
325 let tactic = get_tactics(&[], &output, shape);
326 let list_hi = context.snippet_provider.span_before(span, ")");
327 let comment = context
328 .snippet_provider
329 .span_to_snippet(mk_sp(list_lo, list_hi))?
330 .trim();
331 let comment = if comment.starts_with("//") {
332 format!(
333 "{}{}{}",
334 &list_shape.indent.to_string_with_newline(context.config),
335 comment,
336 &shape.block().indent.to_string_with_newline(context.config)
337 )
338 } else {
339 comment.to_string()
340 };
341 (comment, tactic)
342 } else {
343 let items = itemize_list(
344 context.snippet_provider,
345 inputs,
346 ")",
347 ",",
348 |arg| arg.span().lo(),
349 |arg| arg.span().hi(),
350 |arg| arg.rewrite(context, list_shape),
351 list_lo,
352 span.hi(),
353 false,
354 );
355
356 let item_vec: Vec<_> = items.collect();
357 let tactic = get_tactics(&item_vec, &output, shape);
358 let trailing_separator = if !context.use_block_indent() || variadic {
359 SeparatorTactic::Never
360 } else {
361 context.config.trailing_comma()
362 };
363
364 let fmt = ListFormatting::new(list_shape, context.config)
365 .tactic(tactic)
366 .trailing_separator(trailing_separator)
367 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
368 .preserve_newline(true);
369 (write_list(&item_vec, &fmt)?, tactic)
370 };
371
372 let args = if tactic == DefinitiveListTactic::Horizontal
373 || !context.use_block_indent()
374 || is_inputs_empty
375 {
376 format!("({})", list_str)
377 } else {
378 format!(
379 "({}{}{})",
380 list_shape.indent.to_string_with_newline(context.config),
381 list_str,
382 shape.block().indent.to_string_with_newline(context.config),
383 )
384 };
385 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
386 Some(format!("{}{}", args, output))
387 } else {
388 Some(format!(
389 "{}\n{}{}",
390 args,
391 list_shape.indent.to_string(context.config),
392 output.trim_start()
393 ))
394 }
395 }
396
type_bound_colon(context: &RewriteContext<'_>) -> &'static str397 fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
398 colon_spaces(context.config)
399 }
400
401 // If the return type is multi-lined, then force to use multiple lines for
402 // arguments as well.
get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic403 fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
404 if output.contains('\n') {
405 DefinitiveListTactic::Vertical
406 } else {
407 definitive_tactic(
408 item_vec,
409 ListTactic::HorizontalVertical,
410 Separator::Comma,
411 // 2 is for the case of ',\n'
412 shape.width.saturating_sub(2 + output.len()),
413 )
414 }
415 }
416
417 impl Rewrite for ast::WherePredicate {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>418 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
419 // FIXME: dead spans?
420 let result = match *self {
421 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
422 ref bound_generic_params,
423 ref bounded_ty,
424 ref bounds,
425 ..
426 }) => {
427 let type_str = bounded_ty.rewrite(context, shape)?;
428 let colon = type_bound_colon(context).trim_end();
429 let lhs = if let Some(lifetime_str) =
430 rewrite_lifetime_param(context, shape, bound_generic_params)
431 {
432 format!("for<{}> {}{}", lifetime_str, type_str, colon)
433 } else {
434 format!("{}{}", type_str, colon)
435 };
436
437 rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
438 }
439 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
440 ref lifetime,
441 ref bounds,
442 ..
443 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
444 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
445 ref lhs_ty,
446 ref rhs_ty,
447 ..
448 }) => {
449 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
450 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)?
451 }
452 };
453
454 Some(result)
455 }
456 }
457
458 impl Rewrite for ast::GenericArg {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>459 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
460 match *self {
461 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
462 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
463 ast::GenericArg::Const(ref const_) => const_.rewrite(context, shape),
464 }
465 }
466 }
467
rewrite_generic_args( gen_args: &ast::GenericArgs, context: &RewriteContext<'_>, shape: Shape, span: Span, ) -> Option<String>468 fn rewrite_generic_args(
469 gen_args: &ast::GenericArgs,
470 context: &RewriteContext<'_>,
471 shape: Shape,
472 span: Span,
473 ) -> Option<String> {
474 match gen_args {
475 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
476 let args = data
477 .args
478 .iter()
479 .map(|x| match x {
480 ast::AngleBracketedArg::Arg(generic_arg) => {
481 SegmentParam::from_generic_arg(generic_arg)
482 }
483 ast::AngleBracketedArg::Constraint(constraint) => {
484 SegmentParam::Binding(constraint)
485 }
486 })
487 .collect::<Vec<_>>();
488
489 overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
490 }
491 ast::GenericArgs::Parenthesized(ref data) => format_function_type(
492 data.inputs.iter().map(|x| &**x),
493 &data.output,
494 false,
495 data.span,
496 context,
497 shape,
498 ),
499 _ => Some("".to_owned()),
500 }
501 }
502
rewrite_bounded_lifetime( lt: &ast::Lifetime, bounds: &[ast::GenericBound], context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>503 fn rewrite_bounded_lifetime(
504 lt: &ast::Lifetime,
505 bounds: &[ast::GenericBound],
506 context: &RewriteContext<'_>,
507 shape: Shape,
508 ) -> Option<String> {
509 let result = lt.rewrite(context, shape)?;
510
511 if bounds.is_empty() {
512 Some(result)
513 } else {
514 let colon = type_bound_colon(context);
515 let overhead = last_line_width(&result) + colon.len();
516 let result = format!(
517 "{}{}{}",
518 result,
519 colon,
520 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
521 );
522 Some(result)
523 }
524 }
525
526 impl Rewrite for ast::AnonConst {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>527 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
528 format_expr(&self.value, ExprType::SubExpression, context, shape)
529 }
530 }
531
532 impl Rewrite for ast::Lifetime {
rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String>533 fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
534 Some(rewrite_ident(context, self.ident).to_owned())
535 }
536 }
537
538 impl Rewrite for ast::GenericBound {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>539 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
540 match *self {
541 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
542 let snippet = context.snippet(self.span());
543 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
544 let rewrite = match trait_bound_modifier {
545 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
546 ast::TraitBoundModifier::Maybe => poly_trait_ref
547 .rewrite(context, shape.offset_left(1)?)
548 .map(|s| format!("?{}", s)),
549 ast::TraitBoundModifier::MaybeConst => poly_trait_ref
550 .rewrite(context, shape.offset_left(7)?)
551 .map(|s| format!("~const {}", s)),
552 ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
553 .rewrite(context, shape.offset_left(8)?)
554 .map(|s| format!("~const ?{}", s)),
555 ast::TraitBoundModifier::Negative => poly_trait_ref
556 .rewrite(context, shape.offset_left(1)?)
557 .map(|s| format!("!{}", s)),
558 ast::TraitBoundModifier::MaybeConstNegative => poly_trait_ref
559 .rewrite(context, shape.offset_left(8)?)
560 .map(|s| format!("~const !{}", s)),
561 };
562 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
563 }
564 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
565 }
566 }
567 }
568
569 impl Rewrite for ast::GenericBounds {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>570 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
571 if self.is_empty() {
572 return Some(String::new());
573 }
574
575 join_bounds(context, shape, self, true)
576 }
577 }
578
579 impl Rewrite for ast::GenericParam {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>580 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
581 // FIXME: If there are more than one attributes, this will force multiline.
582 let mut result = self.attrs.rewrite(context, shape).unwrap_or(String::new());
583 let has_attrs = !result.is_empty();
584
585 let mut param = String::with_capacity(128);
586
587 let param_start = if let ast::GenericParamKind::Const {
588 ref ty,
589 kw_span,
590 default,
591 } = &self.kind
592 {
593 param.push_str("const ");
594 param.push_str(rewrite_ident(context, self.ident));
595 param.push_str(": ");
596 param.push_str(&ty.rewrite(context, shape)?);
597 if let Some(default) = default {
598 let eq_str = match context.config.type_punctuation_density() {
599 TypeDensity::Compressed => "=",
600 TypeDensity::Wide => " = ",
601 };
602 param.push_str(eq_str);
603 let budget = shape.width.checked_sub(param.len())?;
604 let rewrite = default.rewrite(context, Shape::legacy(budget, shape.indent))?;
605 param.push_str(&rewrite);
606 }
607 kw_span.lo()
608 } else {
609 param.push_str(rewrite_ident(context, self.ident));
610 self.ident.span.lo()
611 };
612
613 if !self.bounds.is_empty() {
614 param.push_str(type_bound_colon(context));
615 param.push_str(&self.bounds.rewrite(context, shape)?)
616 }
617 if let ast::GenericParamKind::Type {
618 default: Some(ref def),
619 } = self.kind
620 {
621 let eq_str = match context.config.type_punctuation_density() {
622 TypeDensity::Compressed => "=",
623 TypeDensity::Wide => " = ",
624 };
625 param.push_str(eq_str);
626 let budget = shape.width.checked_sub(param.len())?;
627 let rewrite =
628 def.rewrite(context, Shape::legacy(budget, shape.indent + param.len()))?;
629 param.push_str(&rewrite);
630 }
631
632 if let Some(last_attr) = self.attrs.last().filter(|last_attr| {
633 contains_comment(context.snippet(mk_sp(last_attr.span.hi(), param_start)))
634 }) {
635 result = combine_strs_with_missing_comments(
636 context,
637 &result,
638 ¶m,
639 mk_sp(last_attr.span.hi(), param_start),
640 shape,
641 !last_attr.is_doc_comment(),
642 )?;
643 } else {
644 // When rewriting generic params, an extra newline should be put
645 // if the attributes end with a doc comment
646 if let Some(true) = self.attrs.last().map(|a| a.is_doc_comment()) {
647 result.push_str(&shape.indent.to_string_with_newline(context.config));
648 } else if has_attrs {
649 result.push(' ');
650 }
651 result.push_str(¶m);
652 }
653
654 Some(result)
655 }
656 }
657
658 impl Rewrite for ast::PolyTraitRef {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>659 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
660 if let Some(lifetime_str) =
661 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
662 {
663 // 6 is "for<> ".len()
664 let extra_offset = lifetime_str.len() + 6;
665 let path_str = self
666 .trait_ref
667 .rewrite(context, shape.offset_left(extra_offset)?)?;
668
669 Some(format!("for<{}> {}", lifetime_str, path_str))
670 } else {
671 self.trait_ref.rewrite(context, shape)
672 }
673 }
674 }
675
676 impl Rewrite for ast::TraitRef {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>677 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
678 rewrite_path(context, PathContext::Type, &None, &self.path, shape)
679 }
680 }
681
682 impl Rewrite for ast::Ty {
rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>683 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
684 match self.kind {
685 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
686 // we have to consider 'dyn' keyword is used or not!!!
687 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
688 // 4 is length of 'dyn '
689 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
690 let mut res = bounds.rewrite(context, shape)?;
691 // We may have falsely removed a trailing `+` inside macro call.
692 if context.inside_macro() && bounds.len() == 1 {
693 if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
694 res.push('+');
695 }
696 }
697 if is_dyn {
698 Some(format!("dyn {}", res))
699 } else {
700 Some(res)
701 }
702 }
703 ast::TyKind::Ptr(ref mt) => {
704 let prefix = match mt.mutbl {
705 Mutability::Mut => "*mut ",
706 Mutability::Not => "*const ",
707 };
708
709 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
710 }
711 ast::TyKind::Ref(ref lifetime, ref mt) => {
712 let mut_str = format_mutability(mt.mutbl);
713 let mut_len = mut_str.len();
714 let mut result = String::with_capacity(128);
715 result.push('&');
716 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
717 let mut cmnt_lo = ref_hi;
718
719 if let Some(ref lifetime) = *lifetime {
720 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
721 let lt_str = lifetime.rewrite(
722 context,
723 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
724 )?;
725 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
726 if contains_comment(context.snippet(before_lt_span)) {
727 result = combine_strs_with_missing_comments(
728 context,
729 &result,
730 <_str,
731 before_lt_span,
732 shape,
733 true,
734 )?;
735 } else {
736 result.push_str(<_str);
737 }
738 result.push(' ');
739 cmnt_lo = lifetime.ident.span.hi();
740 }
741
742 if ast::Mutability::Mut == mt.mutbl {
743 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
744 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
745 if contains_comment(context.snippet(before_mut_span)) {
746 result = combine_strs_with_missing_comments(
747 context,
748 result.trim_end(),
749 mut_str,
750 before_mut_span,
751 shape,
752 true,
753 )?;
754 } else {
755 result.push_str(mut_str);
756 }
757 cmnt_lo = mut_hi;
758 }
759
760 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
761 if contains_comment(context.snippet(before_ty_span)) {
762 result = combine_strs_with_missing_comments(
763 context,
764 result.trim_end(),
765 &mt.ty.rewrite(context, shape)?,
766 before_ty_span,
767 shape,
768 true,
769 )?;
770 } else {
771 let used_width = last_line_width(&result);
772 let budget = shape.width.checked_sub(used_width)?;
773 let ty_str = mt
774 .ty
775 .rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
776 result.push_str(&ty_str);
777 }
778
779 Some(result)
780 }
781 // FIXME: we drop any comments here, even though it's a silly place to put
782 // comments.
783 ast::TyKind::Paren(ref ty) => {
784 if context.config.version() == Version::One
785 || context.config.indent_style() == IndentStyle::Visual
786 {
787 let budget = shape.width.checked_sub(2)?;
788 return ty
789 .rewrite(context, Shape::legacy(budget, shape.indent + 1))
790 .map(|ty_str| format!("({})", ty_str));
791 }
792
793 // 2 = ()
794 if let Some(sh) = shape.sub_width(2) {
795 if let Some(ref s) = ty.rewrite(context, sh) {
796 if !s.contains('\n') {
797 return Some(format!("({})", s));
798 }
799 }
800 }
801
802 let indent_str = shape.indent.to_string_with_newline(context.config);
803 let shape = shape
804 .block_indent(context.config.tab_spaces())
805 .with_max_width(context.config);
806 let rw = ty.rewrite(context, shape)?;
807 Some(format!(
808 "({}{}{})",
809 shape.to_string_with_newline(context.config),
810 rw,
811 indent_str
812 ))
813 }
814 ast::TyKind::Slice(ref ty) => {
815 let budget = shape.width.checked_sub(4)?;
816 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
817 .map(|ty_str| format!("[{}]", ty_str))
818 }
819 ast::TyKind::Tup(ref items) => {
820 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
821 }
822 ast::TyKind::Path(ref q_self, ref path) => {
823 rewrite_path(context, PathContext::Type, q_self, path, shape)
824 }
825 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
826 &**ty,
827 &*repeats.value,
828 PairParts::new("[", "; ", "]"),
829 context,
830 shape,
831 SeparatorPlace::Back,
832 ),
833 ast::TyKind::Infer => {
834 if shape.width >= 1 {
835 Some("_".to_owned())
836 } else {
837 None
838 }
839 }
840 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
841 ast::TyKind::Never => Some(String::from("!")),
842 ast::TyKind::MacCall(ref mac) => {
843 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
844 }
845 ast::TyKind::ImplicitSelf => Some(String::from("")),
846 ast::TyKind::ImplTrait(_, ref it) => {
847 // Empty trait is not a parser error.
848 if it.is_empty() {
849 return Some("impl".to_owned());
850 }
851 let rw = if context.config.version() == Version::One {
852 it.rewrite(context, shape)
853 } else {
854 join_bounds(context, shape, it, false)
855 };
856 rw.map(|it_str| {
857 let space = if it_str.is_empty() { "" } else { " " };
858 format!("impl{}{}", space, it_str)
859 })
860 }
861 ast::TyKind::CVarArgs => Some("...".to_owned()),
862 ast::TyKind::Err => Some(context.snippet(self.span).to_owned()),
863 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
864 context,
865 "typeof",
866 &[anon_const.value.clone()],
867 self.span,
868 shape,
869 ),
870 }
871 }
872 }
873
rewrite_bare_fn( bare_fn: &ast::BareFnTy, span: Span, context: &RewriteContext<'_>, shape: Shape, ) -> Option<String>874 fn rewrite_bare_fn(
875 bare_fn: &ast::BareFnTy,
876 span: Span,
877 context: &RewriteContext<'_>,
878 shape: Shape,
879 ) -> Option<String> {
880 debug!("rewrite_bare_fn {:#?}", shape);
881
882 let mut result = String::with_capacity(128);
883
884 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
885 {
886 result.push_str("for<");
887 // 6 = "for<> ".len(), 4 = "for<".
888 // This doesn't work out so nicely for multiline situation with lots of
889 // rightward drift. If that is a problem, we could use the list stuff.
890 result.push_str(lifetime_str);
891 result.push_str("> ");
892 }
893
894 result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
895
896 result.push_str(&format_extern(
897 bare_fn.ext,
898 context.config.force_explicit_abi(),
899 false,
900 ));
901
902 result.push_str("fn");
903
904 let func_ty_shape = if context.use_block_indent() {
905 shape.offset_left(result.len())?
906 } else {
907 shape.visual_indent(result.len()).sub_width(result.len())?
908 };
909
910 let rewrite = format_function_type(
911 bare_fn.decl.inputs.iter(),
912 &bare_fn.decl.output,
913 bare_fn.decl.c_variadic(),
914 span,
915 context,
916 func_ty_shape,
917 )?;
918
919 result.push_str(&rewrite);
920
921 Some(result)
922 }
923
is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool924 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
925 let is_trait = |b: &ast::GenericBound| match b {
926 ast::GenericBound::Outlives(..) => false,
927 ast::GenericBound::Trait(..) => true,
928 };
929 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
930 let last_trait_index = generic_bounds.iter().rposition(is_trait);
931 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
932 match (last_trait_index, first_lifetime_index) {
933 (Some(last_trait_index), Some(first_lifetime_index)) => {
934 last_trait_index < first_lifetime_index
935 }
936 _ => true,
937 }
938 }
939
join_bounds( context: &RewriteContext<'_>, shape: Shape, items: &[ast::GenericBound], need_indent: bool, ) -> Option<String>940 fn join_bounds(
941 context: &RewriteContext<'_>,
942 shape: Shape,
943 items: &[ast::GenericBound],
944 need_indent: bool,
945 ) -> Option<String> {
946 join_bounds_inner(context, shape, items, need_indent, false)
947 }
948
join_bounds_inner( context: &RewriteContext<'_>, shape: Shape, items: &[ast::GenericBound], need_indent: bool, force_newline: bool, ) -> Option<String>949 fn join_bounds_inner(
950 context: &RewriteContext<'_>,
951 shape: Shape,
952 items: &[ast::GenericBound],
953 need_indent: bool,
954 force_newline: bool,
955 ) -> Option<String> {
956 debug_assert!(!items.is_empty());
957
958 let generic_bounds_in_order = is_generic_bounds_in_order(items);
959 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
960 ast::GenericBound::Outlives(..) => true,
961 ast::GenericBound::Trait(..) => last_line_extendable(s),
962 };
963
964 // Whether a GenericBound item is a PathSegment segment that includes internal array
965 // that contains more than one item
966 let is_item_with_multi_items_array = |item: &ast::GenericBound| match item {
967 ast::GenericBound::Trait(ref poly_trait_ref, ..) => {
968 let segments = &poly_trait_ref.trait_ref.path.segments;
969 if segments.len() > 1 {
970 true
971 } else {
972 if let Some(args_in) = &segments[0].args {
973 matches!(
974 args_in.deref(),
975 ast::GenericArgs::AngleBracketed(bracket_args)
976 if bracket_args.args.len() > 1
977 )
978 } else {
979 false
980 }
981 }
982 }
983 _ => false,
984 };
985
986 let result = items.iter().enumerate().try_fold(
987 (String::new(), None, false),
988 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
989 let trailing_span = if i < items.len() - 1 {
990 let hi = context
991 .snippet_provider
992 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
993
994 Some(mk_sp(item.span().hi(), hi))
995 } else {
996 None
997 };
998 let (leading_span, has_leading_comment) = if i > 0 {
999 let lo = context
1000 .snippet_provider
1001 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
1002
1003 let span = mk_sp(lo, item.span().lo());
1004
1005 let has_comments = contains_comment(context.snippet(span));
1006
1007 (Some(mk_sp(lo, item.span().lo())), has_comments)
1008 } else {
1009 (None, false)
1010 };
1011 let prev_has_trailing_comment = match prev_trailing_span {
1012 Some(ts) => contains_comment(context.snippet(ts)),
1013 _ => false,
1014 };
1015
1016 let shape = if need_indent && force_newline {
1017 shape
1018 .block_indent(context.config.tab_spaces())
1019 .with_max_width(context.config)
1020 } else {
1021 shape
1022 };
1023 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
1024 shape
1025 .indent
1026 .to_string_with_newline(context.config)
1027 .to_string()
1028 } else {
1029 String::from(" ")
1030 };
1031
1032 let joiner = match context.config.type_punctuation_density() {
1033 TypeDensity::Compressed => String::from("+"),
1034 TypeDensity::Wide => whitespace + "+ ",
1035 };
1036 let joiner = if has_leading_comment {
1037 joiner.trim_end()
1038 } else {
1039 &joiner
1040 };
1041 let joiner = if prev_has_trailing_comment {
1042 joiner.trim_start()
1043 } else {
1044 joiner
1045 };
1046
1047 let (extendable, trailing_str) = if i == 0 {
1048 let bound_str = item.rewrite(context, shape)?;
1049 (is_bound_extendable(&bound_str, item), bound_str)
1050 } else {
1051 let bound_str = &item.rewrite(context, shape)?;
1052 match leading_span {
1053 Some(ls) if has_leading_comment => (
1054 is_bound_extendable(bound_str, item),
1055 combine_strs_with_missing_comments(
1056 context, joiner, bound_str, ls, shape, true,
1057 )?,
1058 ),
1059 _ => (
1060 is_bound_extendable(bound_str, item),
1061 String::from(joiner) + bound_str,
1062 ),
1063 }
1064 };
1065 match prev_trailing_span {
1066 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1067 context,
1068 &strs,
1069 &trailing_str,
1070 ts,
1071 shape,
1072 true,
1073 )
1074 .map(|v| (v, trailing_span, extendable)),
1075 _ => Some((strs + &trailing_str, trailing_span, extendable)),
1076 }
1077 },
1078 )?;
1079
1080 // Whether to retry with a forced newline:
1081 // Only if result is not already multiline and did not exceed line width,
1082 // and either there is more than one item;
1083 // or the single item is of type `Trait`,
1084 // and any of the internal arrays contains more than one item;
1085 let retry_with_force_newline = match context.config.version() {
1086 Version::One => {
1087 !force_newline
1088 && items.len() > 1
1089 && (result.0.contains('\n') || result.0.len() > shape.width)
1090 }
1091 Version::Two if force_newline => false,
1092 Version::Two if (!result.0.contains('\n') && result.0.len() <= shape.width) => false,
1093 Version::Two if items.len() > 1 => true,
1094 Version::Two => is_item_with_multi_items_array(&items[0]),
1095 };
1096
1097 if retry_with_force_newline {
1098 join_bounds_inner(context, shape, items, need_indent, true)
1099 } else {
1100 Some(result.0)
1101 }
1102 }
1103
opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds>1104 pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
1105 ty.as_ref().and_then(|t| match &t.kind {
1106 ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1107 _ => None,
1108 })
1109 }
1110
can_be_overflowed_type( context: &RewriteContext<'_>, ty: &ast::Ty, len: usize, ) -> bool1111 pub(crate) fn can_be_overflowed_type(
1112 context: &RewriteContext<'_>,
1113 ty: &ast::Ty,
1114 len: usize,
1115 ) -> bool {
1116 match ty.kind {
1117 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1118 ast::TyKind::Ref(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
1119 can_be_overflowed_type(context, &*mutty.ty, len)
1120 }
1121 _ => false,
1122 }
1123 }
1124
1125 /// 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>1126 pub(crate) fn rewrite_lifetime_param(
1127 context: &RewriteContext<'_>,
1128 shape: Shape,
1129 generic_params: &[ast::GenericParam],
1130 ) -> Option<String> {
1131 let result = generic_params
1132 .iter()
1133 .filter(|p| matches!(p.kind, ast::GenericParamKind::Lifetime))
1134 .map(|lt| lt.rewrite(context, shape))
1135 .collect::<Option<Vec<_>>>()?
1136 .join(", ");
1137 if result.is_empty() {
1138 None
1139 } else {
1140 Some(result)
1141 }
1142 }
1143