1use std::ops::Deref;
2
3use rustc_ast::ast::{self, FnRetTy, Mutability, Term};
4use rustc_ast::ptr;
5use rustc_span::{BytePos, Pos, Span, symbol::kw};
6use tracing::debug;
7
8use crate::comment::{combine_strs_with_missing_comments, contains_comment};
9use crate::config::lists::*;
10use crate::config::{IndentStyle, StyleEdition, TypeDensity};
11use crate::expr::{
12 ExprType, RhsAssignKind, format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple,
13 rewrite_unary_prefix,
14};
15use crate::lists::{
16 ListFormatting, ListItem, Separator, definitive_tactic, itemize_list, write_list,
17};
18use crate::macros::{MacroPosition, rewrite_macro};
19use crate::overflow;
20use crate::pairs::{PairParts, rewrite_pair};
21use crate::patterns::rewrite_range_pat;
22use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
23use crate::shape::Shape;
24use crate::source_map::SpanUtils;
25use crate::spanned::Spanned;
26use crate::utils::{
27 colon_spaces, extra_offset, first_line_width, format_extern, format_mutability,
28 last_line_extendable, last_line_width, mk_sp, rewrite_ident,
29};
30
31#[derive(Copy, Clone, Debug, Eq, PartialEq)]
32pub(crate) enum PathContext {
33 Expr,
34 Type,
35 Import,
36}
37
38pub(crate) fn rewrite_path(
40 context: &RewriteContext<'_>,
41 path_context: PathContext,
42 qself: &Option<ptr::P<ast::QSelf>>,
43 path: &ast::Path,
44 shape: Shape,
45) -> RewriteResult {
46 let skip_count = qself.as_ref().map_or(0, |x| x.position);
47
48 let mut result = String::with_capacity(32);
51
52 if path.is_global() && qself.is_none() && path_context != PathContext::Import {
53 result.push_str("::");
54 }
55
56 let mut span_lo = path.span.lo();
57
58 if let Some(qself) = qself {
59 result.push('<');
60
61 let fmt_ty = qself.ty.rewrite_result(context, shape)?;
62 result.push_str(&fmt_ty);
63
64 if skip_count > 0 {
65 result.push_str(" as ");
66 if path.is_global() && path_context != PathContext::Import {
67 result.push_str("::");
68 }
69
70 let shape = shape.sub_width(3).max_width_error(shape.width, path.span)?;
72
73 result = rewrite_path_segments(
74 PathContext::Type,
75 result,
76 path.segments.iter().take(skip_count),
77 span_lo,
78 path.span.hi(),
79 context,
80 shape,
81 )?;
82 }
83
84 result.push_str(">::");
85 span_lo = qself.ty.span.hi() + BytePos(1);
86 }
87
88 rewrite_path_segments(
89 path_context,
90 result,
91 path.segments.iter().skip(skip_count),
92 span_lo,
93 path.span.hi(),
94 context,
95 shape,
96 )
97}
98
99fn rewrite_path_segments<'a, I>(
100 path_context: PathContext,
101 mut buffer: String,
102 iter: I,
103 mut span_lo: BytePos,
104 span_hi: BytePos,
105 context: &RewriteContext<'_>,
106 shape: Shape,
107) -> RewriteResult
108where
109 I: Iterator<Item = &'a ast::PathSegment>,
110{
111 let mut first = true;
112 let shape = shape.visual_indent(0);
113
114 for segment in iter {
115 if segment.ident.name == kw::PathRoot {
117 continue;
118 }
119 if first {
120 first = false;
121 } else {
122 buffer.push_str("::");
123 }
124
125 let extra_offset = extra_offset(&buffer, shape);
126 let new_shape = shape
127 .shrink_left(extra_offset)
128 .max_width_error(shape.width, mk_sp(span_lo, span_hi))?;
129 let segment_string = rewrite_segment(
130 path_context,
131 segment,
132 &mut span_lo,
133 span_hi,
134 context,
135 new_shape,
136 )?;
137
138 buffer.push_str(&segment_string);
139 }
140
141 Ok(buffer)
142}
143
144#[derive(Debug)]
145pub(crate) enum SegmentParam<'a> {
146 Const(&'a ast::AnonConst),
147 LifeTime(&'a ast::Lifetime),
148 Type(&'a ast::Ty),
149 Binding(&'a ast::AssocItemConstraint),
150}
151
152impl<'a> SegmentParam<'a> {
153 fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_> {
154 match arg {
155 ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
156 ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
157 ast::GenericArg::Const(const_) => SegmentParam::Const(const_),
158 }
159 }
160}
161
162impl<'a> Spanned for SegmentParam<'a> {
163 fn span(&self) -> Span {
164 match *self {
165 SegmentParam::Const(const_) => const_.value.span,
166 SegmentParam::LifeTime(lt) => lt.ident.span,
167 SegmentParam::Type(ty) => ty.span,
168 SegmentParam::Binding(binding) => binding.span,
169 }
170 }
171}
172
173impl<'a> Rewrite for SegmentParam<'a> {
174 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
175 self.rewrite_result(context, shape).ok()
176 }
177
178 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
179 match *self {
180 SegmentParam::Const(const_) => const_.rewrite_result(context, shape),
181 SegmentParam::LifeTime(lt) => lt.rewrite_result(context, shape),
182 SegmentParam::Type(ty) => ty.rewrite_result(context, shape),
183 SegmentParam::Binding(atc) => atc.rewrite_result(context, shape),
184 }
185 }
186}
187
188impl Rewrite for ast::PreciseCapturingArg {
189 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
190 self.rewrite_result(context, shape).ok()
191 }
192
193 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
194 match self {
195 ast::PreciseCapturingArg::Lifetime(lt) => lt.rewrite_result(context, shape),
196 ast::PreciseCapturingArg::Arg(p, _) => {
197 rewrite_path(context, PathContext::Type, &None, p, shape)
198 }
199 }
200 }
201}
202
203impl Rewrite for ast::AssocItemConstraint {
204 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
205 self.rewrite_result(context, shape).ok()
206 }
207
208 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
209 use ast::AssocItemConstraintKind::{Bound, Equality};
210
211 let mut result = String::with_capacity(128);
212 result.push_str(rewrite_ident(context, self.ident));
213
214 if let Some(ref gen_args) = self.gen_args {
215 let budget = shape
216 .width
217 .checked_sub(result.len())
218 .max_width_error(shape.width, self.span)?;
219 let shape = Shape::legacy(budget, shape.indent + result.len());
220 let gen_str = rewrite_generic_args(gen_args, context, shape, gen_args.span())?;
221 result.push_str(&gen_str);
222 }
223
224 let infix = match (&self.kind, context.config.type_punctuation_density()) {
225 (Bound { .. }, _) => ": ",
226 (Equality { .. }, TypeDensity::Wide) => " = ",
227 (Equality { .. }, TypeDensity::Compressed) => "=",
228 };
229 result.push_str(infix);
230
231 let budget = shape
232 .width
233 .checked_sub(result.len())
234 .max_width_error(shape.width, self.span)?;
235 let shape = Shape::legacy(budget, shape.indent + result.len());
236 let rewrite = self.kind.rewrite_result(context, shape)?;
237 result.push_str(&rewrite);
238
239 Ok(result)
240 }
241}
242
243impl Rewrite for ast::AssocItemConstraintKind {
244 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
245 self.rewrite_result(context, shape).ok()
246 }
247
248 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
249 match self {
250 ast::AssocItemConstraintKind::Equality { term } => match term {
251 Term::Ty(ty) => ty.rewrite_result(context, shape),
252 Term::Const(c) => c.rewrite_result(context, shape),
253 },
254 ast::AssocItemConstraintKind::Bound { bounds } => bounds.rewrite_result(context, shape),
255 }
256 }
257}
258
259fn rewrite_segment(
270 path_context: PathContext,
271 segment: &ast::PathSegment,
272 span_lo: &mut BytePos,
273 span_hi: BytePos,
274 context: &RewriteContext<'_>,
275 shape: Shape,
276) -> RewriteResult {
277 let mut result = String::with_capacity(128);
278 result.push_str(rewrite_ident(context, segment.ident));
279
280 let ident_len = result.len();
281 let shape = if context.use_block_indent() {
282 shape.offset_left(ident_len)
283 } else {
284 shape.shrink_left(ident_len)
285 }
286 .max_width_error(shape.width, mk_sp(*span_lo, span_hi))?;
287
288 if let Some(ref args) = segment.args {
289 let generics_str = rewrite_generic_args(args, context, shape, mk_sp(*span_lo, span_hi))?;
290 match **args {
291 ast::GenericArgs::AngleBracketed(ref data) if !data.args.is_empty() => {
292 let separator_snippet = context
297 .snippet(mk_sp(segment.ident.span.hi(), data.span.lo()))
298 .trim();
299 let force_separator = context.inside_macro() && separator_snippet.starts_with("::");
300 let separator = if path_context == PathContext::Expr || force_separator {
301 "::"
302 } else {
303 ""
304 };
305 result.push_str(separator);
306
307 *span_lo = context
309 .snippet_provider
310 .span_after(mk_sp(*span_lo, span_hi), "<");
311 }
312 _ => (),
313 }
314 result.push_str(&generics_str)
315 }
316
317 Ok(result)
318}
319
320fn format_function_type<'a, I>(
321 inputs: I,
322 output: &FnRetTy,
323 variadic: bool,
324 span: Span,
325 context: &RewriteContext<'_>,
326 shape: Shape,
327) -> RewriteResult
328where
329 I: ExactSizeIterator,
330 <I as Iterator>::Item: Deref,
331 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
332{
333 debug!("format_function_type {:#?}", shape);
334
335 let ty_shape = match context.config.indent_style() {
336 IndentStyle::Block => shape.offset_left(4).max_width_error(shape.width, span)?,
338 IndentStyle::Visual => shape.block_left(4).max_width_error(shape.width, span)?,
339 };
340 let output = match *output {
341 FnRetTy::Ty(ref ty) => {
342 let type_str = ty.rewrite_result(context, ty_shape)?;
343 format!(" -> {type_str}")
344 }
345 FnRetTy::Default(..) => String::new(),
346 };
347
348 let list_shape = if context.use_block_indent() {
349 Shape::indented(
350 shape.block().indent.block_indent(context.config),
351 context.config,
352 )
353 } else {
354 let budget = shape
356 .width
357 .checked_sub(2)
358 .max_width_error(shape.width, span)?;
359 let offset = shape.indent + 1;
361 Shape::legacy(budget, offset)
362 };
363
364 let is_inputs_empty = inputs.len() == 0;
365 let list_lo = context.snippet_provider.span_after(span, "(");
366 let (list_str, tactic) = if is_inputs_empty {
367 let tactic = get_tactics(&[], &output, shape);
368 let list_hi = context.snippet_provider.span_before(span, ")");
369 let comment = context
370 .snippet_provider
371 .span_to_snippet(mk_sp(list_lo, list_hi))
372 .unknown_error()?
373 .trim();
374 let comment = if comment.starts_with("//") {
375 format!(
376 "{}{}{}",
377 &list_shape.indent.to_string_with_newline(context.config),
378 comment,
379 &shape.block().indent.to_string_with_newline(context.config)
380 )
381 } else {
382 comment.to_string()
383 };
384 (comment, tactic)
385 } else {
386 let items = itemize_list(
387 context.snippet_provider,
388 inputs,
389 ")",
390 ",",
391 |arg| arg.span().lo(),
392 |arg| arg.span().hi(),
393 |arg| arg.rewrite_result(context, list_shape),
394 list_lo,
395 span.hi(),
396 false,
397 );
398
399 let item_vec: Vec<_> = items.collect();
400 let tactic = get_tactics(&item_vec, &output, shape);
401 let trailing_separator = if !context.use_block_indent() || variadic {
402 SeparatorTactic::Never
403 } else {
404 context.config.trailing_comma()
405 };
406
407 let fmt = ListFormatting::new(list_shape, context.config)
408 .tactic(tactic)
409 .trailing_separator(trailing_separator)
410 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
411 .preserve_newline(true);
412 (write_list(&item_vec, &fmt)?, tactic)
413 };
414
415 let args = if tactic == DefinitiveListTactic::Horizontal
416 || !context.use_block_indent()
417 || is_inputs_empty
418 {
419 format!("({list_str})")
420 } else {
421 format!(
422 "({}{}{})",
423 list_shape.indent.to_string_with_newline(context.config),
424 list_str,
425 shape.block().indent.to_string_with_newline(context.config),
426 )
427 };
428 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
429 Ok(format!("{args}{output}"))
430 } else {
431 Ok(format!(
432 "{}\n{}{}",
433 args,
434 list_shape.indent.to_string(context.config),
435 output.trim_start()
436 ))
437 }
438}
439
440fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
441 colon_spaces(context.config)
442}
443
444fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
447 if output.contains('\n') {
448 DefinitiveListTactic::Vertical
449 } else {
450 definitive_tactic(
451 item_vec,
452 ListTactic::HorizontalVertical,
453 Separator::Comma,
454 shape.width.saturating_sub(2 + output.len()),
456 )
457 }
458}
459
460impl Rewrite for ast::WherePredicate {
461 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
462 self.rewrite_result(context, shape).ok()
463 }
464
465 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
466 let attrs_str = self.attrs.rewrite_result(context, shape)?;
467 let pred_str = &match self.kind {
469 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
470 ref bound_generic_params,
471 ref bounded_ty,
472 ref bounds,
473 ..
474 }) => {
475 let type_str = bounded_ty.rewrite_result(context, shape)?;
476 let colon = type_bound_colon(context).trim_end();
477 let lhs = if let Some(binder_str) =
478 rewrite_bound_params(context, shape, bound_generic_params)
479 {
480 format!("for<{binder_str}> {type_str}{colon}")
481 } else {
482 format!("{type_str}{colon}")
483 };
484
485 rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
486 }
487 ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
488 ref lifetime,
489 ref bounds,
490 }) => rewrite_bounded_lifetime(lifetime, bounds, self.span, context, shape)?,
491 ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate {
492 ref lhs_ty,
493 ref rhs_ty,
494 ..
495 }) => {
496 let lhs_ty_str = lhs_ty
497 .rewrite_result(context, shape)
498 .map(|lhs| lhs + " =")?;
499 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, &RhsAssignKind::Ty, shape)?
500 }
501 };
502
503 let mut result = String::with_capacity(attrs_str.len() + pred_str.len() + 1);
504 result.push_str(&attrs_str);
505 let pred_start = self.span.lo();
506 let line_len = last_line_width(&attrs_str) + 1 + first_line_width(&pred_str);
507 if let Some(last_attr) = self.attrs.last().filter(|last_attr| {
508 contains_comment(context.snippet(mk_sp(last_attr.span.hi(), pred_start)))
509 }) {
510 result = combine_strs_with_missing_comments(
511 context,
512 &result,
513 &pred_str,
514 mk_sp(last_attr.span.hi(), pred_start),
515 Shape {
516 width: shape.width.min(context.config.inline_attribute_width()),
517 ..shape
518 },
519 !last_attr.is_doc_comment(),
520 )?;
521 } else {
522 if !self.attrs.is_empty() {
523 if context.config.inline_attribute_width() < line_len
524 || self.attrs.len() > 1
525 || self.attrs.last().is_some_and(|a| a.is_doc_comment())
526 {
527 result.push_str(&shape.indent.to_string_with_newline(context.config));
528 } else {
529 result.push(' ');
530 }
531 }
532 result.push_str(&pred_str);
533 }
534
535 Ok(result)
536 }
537}
538
539impl Rewrite for ast::GenericArg {
540 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
541 self.rewrite_result(context, shape).ok()
542 }
543
544 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
545 match *self {
546 ast::GenericArg::Lifetime(ref lt) => lt.rewrite_result(context, shape),
547 ast::GenericArg::Type(ref ty) => ty.rewrite_result(context, shape),
548 ast::GenericArg::Const(ref const_) => const_.rewrite_result(context, shape),
549 }
550 }
551}
552
553fn rewrite_generic_args(
554 gen_args: &ast::GenericArgs,
555 context: &RewriteContext<'_>,
556 shape: Shape,
557 span: Span,
558) -> RewriteResult {
559 match gen_args {
560 ast::GenericArgs::AngleBracketed(ref data) => {
561 if data.args.is_empty() {
562 Ok("".to_owned())
563 } else {
564 let args = data
565 .args
566 .iter()
567 .map(|x| match x {
568 ast::AngleBracketedArg::Arg(generic_arg) => {
569 SegmentParam::from_generic_arg(generic_arg)
570 }
571 ast::AngleBracketedArg::Constraint(constraint) => {
572 SegmentParam::Binding(constraint)
573 }
574 })
575 .collect::<Vec<_>>();
576
577 overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
578 }
579 }
580 ast::GenericArgs::Parenthesized(ref data) => format_function_type(
581 data.inputs.iter().map(|x| &**x),
582 &data.output,
583 false,
584 data.span,
585 context,
586 shape,
587 ),
588 ast::GenericArgs::ParenthesizedElided(..) => Ok("(..)".to_owned()),
589 }
590}
591
592fn rewrite_bounded_lifetime(
593 lt: &ast::Lifetime,
594 bounds: &[ast::GenericBound],
595 span: Span,
596 context: &RewriteContext<'_>,
597 shape: Shape,
598) -> RewriteResult {
599 let result = lt.rewrite_result(context, shape)?;
600
601 if bounds.is_empty() {
602 Ok(result)
603 } else {
604 let colon = type_bound_colon(context);
605 let overhead = last_line_width(&result) + colon.len();
606 let shape = shape
607 .sub_width(overhead)
608 .max_width_error(shape.width, span)?;
609 let result = format!(
610 "{}{}{}",
611 result,
612 colon,
613 join_bounds(context, shape, bounds, true)?
614 );
615 Ok(result)
616 }
617}
618
619impl Rewrite for ast::AnonConst {
620 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
621 self.rewrite_result(context, shape).ok()
622 }
623
624 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
625 format_expr(&self.value, ExprType::SubExpression, context, shape)
626 }
627}
628
629impl Rewrite for ast::Lifetime {
630 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
631 self.rewrite_result(context, shape).ok()
632 }
633
634 fn rewrite_result(&self, context: &RewriteContext<'_>, _: Shape) -> RewriteResult {
635 Ok(context.snippet(self.ident.span).to_owned())
636 }
637}
638
639impl Rewrite for ast::GenericBound {
640 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
641 self.rewrite_result(context, shape).ok()
642 }
643
644 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
645 match *self {
646 ast::GenericBound::Trait(ref poly_trait_ref) => {
647 let snippet = context.snippet(self.span());
648 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
649 poly_trait_ref
650 .rewrite_result(context, shape)
651 .map(|s| if has_paren { format!("({})", s) } else { s })
652 }
653 ast::GenericBound::Use(ref args, span) => {
654 overflow::rewrite_with_angle_brackets(context, "use", args.iter(), shape, span)
655 }
656 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite_result(context, shape),
657 }
658 }
659}
660
661impl Rewrite for ast::GenericBounds {
662 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
663 self.rewrite_result(context, shape).ok()
664 }
665
666 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
667 if self.is_empty() {
668 return Ok(String::new());
669 }
670
671 join_bounds(context, shape, self, true)
672 }
673}
674
675impl Rewrite for ast::GenericParam {
676 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
677 self.rewrite_result(context, shape).ok()
678 }
679
680 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
681 let mut result = self
683 .attrs
684 .rewrite_result(context, shape)
685 .unwrap_or(String::new());
686 let has_attrs = !result.is_empty();
687
688 let mut param = String::with_capacity(128);
689
690 let param_start = if let ast::GenericParamKind::Const {
691 ref ty,
692 span,
693 default,
694 } = &self.kind
695 {
696 param.push_str("const ");
697 param.push_str(rewrite_ident(context, self.ident));
698 param.push_str(": ");
699 param.push_str(&ty.rewrite_result(context, shape)?);
700 if let Some(default) = default {
701 let eq_str = match context.config.type_punctuation_density() {
702 TypeDensity::Compressed => "=",
703 TypeDensity::Wide => " = ",
704 };
705 param.push_str(eq_str);
706 let budget = shape
707 .width
708 .checked_sub(param.len())
709 .max_width_error(shape.width, self.span())?;
710 let rewrite =
711 default.rewrite_result(context, Shape::legacy(budget, shape.indent))?;
712 param.push_str(&rewrite);
713 }
714 span.lo()
715 } else {
716 param.push_str(rewrite_ident(context, self.ident));
717 self.ident.span.lo()
718 };
719
720 if !self.bounds.is_empty() {
721 param.push_str(type_bound_colon(context));
722 param.push_str(&self.bounds.rewrite_result(context, shape)?)
723 }
724 if let ast::GenericParamKind::Type {
725 default: Some(ref def),
726 } = self.kind
727 {
728 let eq_str = match context.config.type_punctuation_density() {
729 TypeDensity::Compressed => "=",
730 TypeDensity::Wide => " = ",
731 };
732 param.push_str(eq_str);
733 let budget = shape
734 .width
735 .checked_sub(param.len())
736 .max_width_error(shape.width, self.span())?;
737 let rewrite =
738 def.rewrite_result(context, Shape::legacy(budget, shape.indent + param.len()))?;
739 param.push_str(&rewrite);
740 }
741
742 if let Some(last_attr) = self.attrs.last().filter(|last_attr| {
743 contains_comment(context.snippet(mk_sp(last_attr.span.hi(), param_start)))
744 }) {
745 result = combine_strs_with_missing_comments(
746 context,
747 &result,
748 ¶m,
749 mk_sp(last_attr.span.hi(), param_start),
750 shape,
751 !last_attr.is_doc_comment(),
752 )?;
753 } else {
754 if let Some(true) = self.attrs.last().map(|a| a.is_doc_comment()) {
757 result.push_str(&shape.indent.to_string_with_newline(context.config));
758 } else if has_attrs {
759 result.push(' ');
760 }
761 result.push_str(¶m);
762 }
763
764 Ok(result)
765 }
766}
767
768impl Rewrite for ast::PolyTraitRef {
769 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
770 self.rewrite_result(context, shape).ok()
771 }
772
773 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
774 let (binder, shape) = if let Some(lifetime_str) =
775 rewrite_bound_params(context, shape, &self.bound_generic_params)
776 {
777 let extra_offset = lifetime_str.len() + 6;
779 let shape = shape
780 .offset_left(extra_offset)
781 .max_width_error(shape.width, self.span)?;
782 (format!("for<{lifetime_str}> "), shape)
783 } else {
784 (String::new(), shape)
785 };
786
787 let ast::TraitBoundModifiers {
788 constness,
789 asyncness,
790 polarity,
791 } = self.modifiers;
792 let mut constness = constness.as_str().to_string();
793 if !constness.is_empty() {
794 constness.push(' ');
795 }
796 let mut asyncness = asyncness.as_str().to_string();
797 if !asyncness.is_empty() {
798 asyncness.push(' ');
799 }
800 let polarity = polarity.as_str();
801 let shape = shape
802 .offset_left(constness.len() + polarity.len())
803 .max_width_error(shape.width, self.span)?;
804
805 let path_str = self.trait_ref.rewrite_result(context, shape)?;
806 Ok(format!(
807 "{binder}{constness}{asyncness}{polarity}{path_str}"
808 ))
809 }
810}
811
812impl Rewrite for ast::TraitRef {
813 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
814 self.rewrite_result(context, shape).ok()
815 }
816
817 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
818 rewrite_path(context, PathContext::Type, &None, &self.path, shape)
819 }
820}
821
822impl Rewrite for ast::Ty {
823 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
824 self.rewrite_result(context, shape).ok()
825 }
826
827 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
828 match self.kind {
829 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
830 let (shape, prefix) = match tobj_syntax {
832 ast::TraitObjectSyntax::Dyn => {
833 let shape = shape
834 .offset_left(4)
835 .max_width_error(shape.width, self.span())?;
836 (shape, "dyn ")
837 }
838 ast::TraitObjectSyntax::None => (shape, ""),
839 };
840 let mut res = bounds.rewrite_result(context, shape)?;
841 if context.inside_macro()
843 && bounds.len() == 1
844 && context.snippet(self.span).ends_with('+')
845 && !res.ends_with('+')
846 {
847 res.push('+');
848 }
849 Ok(format!("{prefix}{res}"))
850 }
851 ast::TyKind::Ptr(ref mt) => {
852 let prefix = match mt.mutbl {
853 Mutability::Mut => "*mut ",
854 Mutability::Not => "*const ",
855 };
856
857 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
858 }
859 ast::TyKind::Ref(ref lifetime, ref mt)
860 | ast::TyKind::PinnedRef(ref lifetime, ref mt) => {
861 let mut_str = format_mutability(mt.mutbl);
862 let mut_len = mut_str.len();
863 let mut result = String::with_capacity(128);
864 result.push('&');
865 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
866 let mut cmnt_lo = ref_hi;
867
868 if let Some(ref lifetime) = *lifetime {
869 let lt_budget = shape
870 .width
871 .checked_sub(2 + mut_len)
872 .max_width_error(shape.width, self.span())?;
873 let lt_str = lifetime.rewrite_result(
874 context,
875 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
876 )?;
877 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
878 if contains_comment(context.snippet(before_lt_span)) {
879 result = combine_strs_with_missing_comments(
880 context,
881 &result,
882 <_str,
883 before_lt_span,
884 shape,
885 true,
886 )?;
887 } else {
888 result.push_str(<_str);
889 }
890 result.push(' ');
891 cmnt_lo = lifetime.ident.span.hi();
892 }
893
894 if let ast::TyKind::PinnedRef(..) = self.kind {
895 result.push_str("pin ");
896 if ast::Mutability::Not == mt.mutbl {
897 result.push_str("const ");
898 }
899 }
900
901 if ast::Mutability::Mut == mt.mutbl {
902 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
903 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
904 if contains_comment(context.snippet(before_mut_span)) {
905 result = combine_strs_with_missing_comments(
906 context,
907 result.trim_end(),
908 mut_str,
909 before_mut_span,
910 shape,
911 true,
912 )?;
913 } else {
914 result.push_str(mut_str);
915 }
916 cmnt_lo = mut_hi;
917 }
918
919 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
920 if contains_comment(context.snippet(before_ty_span)) {
921 result = combine_strs_with_missing_comments(
922 context,
923 result.trim_end(),
924 &mt.ty.rewrite_result(context, shape)?,
925 before_ty_span,
926 shape,
927 true,
928 )?;
929 } else {
930 let used_width = last_line_width(&result);
931 let budget = shape
932 .width
933 .checked_sub(used_width)
934 .max_width_error(shape.width, self.span())?;
935 let ty_str = mt.ty.rewrite_result(
936 context,
937 Shape::legacy(budget, shape.indent + used_width),
938 )?;
939 result.push_str(&ty_str);
940 }
941
942 Ok(result)
943 }
944 ast::TyKind::Paren(ref ty) => {
947 if context.config.style_edition() <= StyleEdition::Edition2021
948 || context.config.indent_style() == IndentStyle::Visual
949 {
950 let budget = shape
951 .width
952 .checked_sub(2)
953 .max_width_error(shape.width, self.span())?;
954 return ty
955 .rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
956 .map(|ty_str| format!("({})", ty_str));
957 }
958
959 if let Some(sh) = shape.sub_width(2) {
961 if let Ok(ref s) = ty.rewrite_result(context, sh) {
962 if !s.contains('\n') {
963 return Ok(format!("({s})"));
964 }
965 }
966 }
967
968 let indent_str = shape.indent.to_string_with_newline(context.config);
969 let shape = shape
970 .block_indent(context.config.tab_spaces())
971 .with_max_width(context.config);
972 let rw = ty.rewrite_result(context, shape)?;
973 Ok(format!(
974 "({}{}{})",
975 shape.to_string_with_newline(context.config),
976 rw,
977 indent_str
978 ))
979 }
980 ast::TyKind::Slice(ref ty) => {
981 let budget = shape
982 .width
983 .checked_sub(4)
984 .max_width_error(shape.width, self.span())?;
985 ty.rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
986 .map(|ty_str| format!("[{}]", ty_str))
987 }
988 ast::TyKind::Tup(ref items) => {
989 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
990 }
991 ast::TyKind::Path(ref q_self, ref path) => {
992 rewrite_path(context, PathContext::Type, q_self, path, shape)
993 }
994 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
995 &**ty,
996 &*repeats.value,
997 PairParts::new("[", "; ", "]"),
998 context,
999 shape,
1000 SeparatorPlace::Back,
1001 ),
1002 ast::TyKind::Infer => {
1003 if shape.width >= 1 {
1004 Ok("_".to_owned())
1005 } else {
1006 Err(RewriteError::ExceedsMaxWidth {
1007 configured_width: shape.width,
1008 span: self.span(),
1009 })
1010 }
1011 }
1012 ast::TyKind::FnPtr(ref fn_ptr) => rewrite_fn_ptr(fn_ptr, self.span, context, shape),
1013 ast::TyKind::Never => Ok(String::from("!")),
1014 ast::TyKind::MacCall(ref mac) => {
1015 rewrite_macro(mac, context, shape, MacroPosition::Expression)
1016 }
1017 ast::TyKind::ImplicitSelf => Ok(String::from("")),
1018 ast::TyKind::ImplTrait(_, ref it) => {
1019 if it.is_empty() {
1021 return Ok("impl".to_owned());
1022 }
1023 let rw = if context.config.style_edition() <= StyleEdition::Edition2021 {
1024 it.rewrite_result(context, shape)
1025 } else {
1026 join_bounds(context, shape, it, false)
1027 };
1028 rw.map(|it_str| {
1029 let space = if it_str.is_empty() { "" } else { " " };
1030 format!("impl{}{}", space, it_str)
1031 })
1032 }
1033 ast::TyKind::CVarArgs => Ok("...".to_owned()),
1034 ast::TyKind::Dummy | ast::TyKind::Err(_) => Ok(context.snippet(self.span).to_owned()),
1035 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
1036 context,
1037 "typeof",
1038 &[anon_const.value.clone()],
1039 self.span,
1040 shape,
1041 ),
1042 ast::TyKind::Pat(ref ty, ref pat) => {
1043 let ty = ty.rewrite_result(context, shape)?;
1044 let pat = pat.rewrite_result(context, shape)?;
1045 Ok(format!("{ty} is {pat}"))
1046 }
1047 ast::TyKind::UnsafeBinder(ref binder) => {
1048 let mut result = String::new();
1049 if binder.generic_params.is_empty() {
1050 result.push_str("unsafe<> ")
1053 } else if let Some(ref lifetime_str) =
1054 rewrite_bound_params(context, shape, &binder.generic_params)
1055 {
1056 result.push_str("unsafe<");
1057 result.push_str(lifetime_str);
1058 result.push_str("> ");
1059 }
1060
1061 let inner_ty_shape = if context.use_block_indent() {
1062 shape
1063 .offset_left(result.len())
1064 .max_width_error(shape.width, self.span())?
1065 } else {
1066 shape
1067 .visual_indent(result.len())
1068 .sub_width(result.len())
1069 .max_width_error(shape.width, self.span())?
1070 };
1071
1072 let rewrite = binder.inner_ty.rewrite_result(context, inner_ty_shape)?;
1073 result.push_str(&rewrite);
1074 Ok(result)
1075 }
1076 }
1077 }
1078}
1079
1080impl Rewrite for ast::TyPat {
1081 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1082 self.rewrite_result(context, shape).ok()
1083 }
1084
1085 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1086 match self.kind {
1087 ast::TyPatKind::Range(ref lhs, ref rhs, ref end_kind) => {
1088 rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span)
1089 }
1090 ast::TyPatKind::Or(ref variants) => {
1091 let mut first = true;
1092 let mut s = String::new();
1093 for variant in variants {
1094 if first {
1095 first = false
1096 } else {
1097 s.push_str(" | ");
1098 }
1099 s.push_str(&variant.rewrite_result(context, shape)?);
1100 }
1101 Ok(s)
1102 }
1103 ast::TyPatKind::Err(_) => Err(RewriteError::Unknown),
1104 }
1105 }
1106}
1107
1108fn rewrite_fn_ptr(
1109 fn_ptr: &ast::FnPtrTy,
1110 span: Span,
1111 context: &RewriteContext<'_>,
1112 shape: Shape,
1113) -> RewriteResult {
1114 debug!("rewrite_bare_fn {:#?}", shape);
1115
1116 let mut result = String::with_capacity(128);
1117
1118 if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &fn_ptr.generic_params) {
1119 result.push_str("for<");
1120 result.push_str(lifetime_str);
1124 result.push_str("> ");
1125 }
1126
1127 result.push_str(crate::utils::format_safety(fn_ptr.safety));
1128
1129 result.push_str(&format_extern(
1130 fn_ptr.ext,
1131 context.config.force_explicit_abi(),
1132 ));
1133
1134 result.push_str("fn");
1135
1136 let func_ty_shape = if context.use_block_indent() {
1137 shape
1138 .offset_left(result.len())
1139 .max_width_error(shape.width, span)?
1140 } else {
1141 shape
1142 .visual_indent(result.len())
1143 .sub_width(result.len())
1144 .max_width_error(shape.width, span)?
1145 };
1146
1147 let rewrite = format_function_type(
1148 fn_ptr.decl.inputs.iter(),
1149 &fn_ptr.decl.output,
1150 fn_ptr.decl.c_variadic(),
1151 span,
1152 context,
1153 func_ty_shape,
1154 )?;
1155
1156 result.push_str(&rewrite);
1157
1158 Ok(result)
1159}
1160
1161fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
1162 let is_trait = |b: &ast::GenericBound| match b {
1163 ast::GenericBound::Outlives(..) => false,
1164 ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => true,
1165 };
1166 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
1167 let last_trait_index = generic_bounds.iter().rposition(is_trait);
1168 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
1169 match (last_trait_index, first_lifetime_index) {
1170 (Some(last_trait_index), Some(first_lifetime_index)) => {
1171 last_trait_index < first_lifetime_index
1172 }
1173 _ => true,
1174 }
1175}
1176
1177fn join_bounds(
1178 context: &RewriteContext<'_>,
1179 shape: Shape,
1180 items: &[ast::GenericBound],
1181 need_indent: bool,
1182) -> RewriteResult {
1183 join_bounds_inner(context, shape, items, need_indent, false)
1184}
1185
1186fn join_bounds_inner(
1187 context: &RewriteContext<'_>,
1188 shape: Shape,
1189 items: &[ast::GenericBound],
1190 need_indent: bool,
1191 force_newline: bool,
1192) -> RewriteResult {
1193 debug_assert!(!items.is_empty());
1194
1195 let generic_bounds_in_order = is_generic_bounds_in_order(items);
1196 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
1197 ast::GenericBound::Outlives(..) => true,
1198 ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => last_line_extendable(s),
1200 };
1201
1202 let is_item_with_multi_items_array = |item: &ast::GenericBound| match item {
1205 ast::GenericBound::Trait(ref poly_trait_ref, ..) => {
1206 let segments = &poly_trait_ref.trait_ref.path.segments;
1207 if segments.len() > 1 {
1208 true
1209 } else {
1210 if let Some(args_in) = &segments[0].args {
1211 matches!(
1212 args_in.deref(),
1213 ast::GenericArgs::AngleBracketed(bracket_args)
1214 if bracket_args.args.len() > 1
1215 )
1216 } else {
1217 false
1218 }
1219 }
1220 }
1221 ast::GenericBound::Use(args, _) => args.len() > 1,
1222 _ => false,
1223 };
1224
1225 let result = items.iter().enumerate().try_fold(
1226 (String::new(), None, false),
1227 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
1228 let trailing_span = if i < items.len() - 1 {
1229 let hi = context
1230 .snippet_provider
1231 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
1232
1233 Some(mk_sp(item.span().hi(), hi))
1234 } else {
1235 None
1236 };
1237 let (leading_span, has_leading_comment) = if i > 0 {
1238 let lo = context
1239 .snippet_provider
1240 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
1241
1242 let span = mk_sp(lo, item.span().lo());
1243
1244 let has_comments = contains_comment(context.snippet(span));
1245
1246 (Some(mk_sp(lo, item.span().lo())), has_comments)
1247 } else {
1248 (None, false)
1249 };
1250 let prev_has_trailing_comment = match prev_trailing_span {
1251 Some(ts) => contains_comment(context.snippet(ts)),
1252 _ => false,
1253 };
1254
1255 let shape = if need_indent && force_newline {
1256 shape
1257 .block_indent(context.config.tab_spaces())
1258 .with_max_width(context.config)
1259 } else {
1260 shape
1261 };
1262 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
1263 shape
1264 .indent
1265 .to_string_with_newline(context.config)
1266 .to_string()
1267 } else {
1268 String::from(" ")
1269 };
1270
1271 let joiner = match context.config.type_punctuation_density() {
1272 TypeDensity::Compressed => String::from("+"),
1273 TypeDensity::Wide => whitespace + "+ ",
1274 };
1275 let joiner = if has_leading_comment {
1276 joiner.trim_end()
1277 } else {
1278 &joiner
1279 };
1280 let joiner = if prev_has_trailing_comment {
1281 joiner.trim_start()
1282 } else {
1283 joiner
1284 };
1285
1286 let (extendable, trailing_str) = if i == 0 {
1287 let bound_str = item.rewrite_result(context, shape)?;
1288 (is_bound_extendable(&bound_str, item), bound_str)
1289 } else {
1290 let bound_str = &item.rewrite_result(context, shape)?;
1291 match leading_span {
1292 Some(ls) if has_leading_comment => (
1293 is_bound_extendable(bound_str, item),
1294 combine_strs_with_missing_comments(
1295 context, joiner, bound_str, ls, shape, true,
1296 )?,
1297 ),
1298 _ => (
1299 is_bound_extendable(bound_str, item),
1300 String::from(joiner) + bound_str,
1301 ),
1302 }
1303 };
1304 match prev_trailing_span {
1305 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1306 context,
1307 &strs,
1308 &trailing_str,
1309 ts,
1310 shape,
1311 true,
1312 )
1313 .map(|v| (v, trailing_span, extendable)),
1314 _ => Ok((strs + &trailing_str, trailing_span, extendable)),
1315 }
1316 },
1317 )?;
1318
1319 let retry_with_force_newline = match context.config.style_edition() {
1325 style_edition @ _ if style_edition <= StyleEdition::Edition2021 => {
1326 !force_newline
1327 && items.len() > 1
1328 && (result.0.contains('\n') || result.0.len() > shape.width)
1329 }
1330 _ if force_newline => false,
1331 _ if (!result.0.contains('\n') && result.0.len() <= shape.width) => false,
1332 _ if items.len() > 1 => true,
1333 _ => is_item_with_multi_items_array(&items[0]),
1334 };
1335
1336 if retry_with_force_newline {
1337 join_bounds_inner(context, shape, items, need_indent, true)
1338 } else {
1339 Ok(result.0)
1340 }
1341}
1342
1343pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
1344 ty.as_ref().and_then(|t| match &t.kind {
1345 ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1346 _ => None,
1347 })
1348}
1349
1350pub(crate) fn can_be_overflowed_type(
1351 context: &RewriteContext<'_>,
1352 ty: &ast::Ty,
1353 len: usize,
1354) -> bool {
1355 match ty.kind {
1356 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1357 ast::TyKind::Ref(_, ref mutty)
1358 | ast::TyKind::PinnedRef(_, ref mutty)
1359 | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len),
1360 _ => false,
1361 }
1362}
1363
1364pub(crate) fn rewrite_bound_params(
1366 context: &RewriteContext<'_>,
1367 shape: Shape,
1368 generic_params: &[ast::GenericParam],
1369) -> Option<String> {
1370 let result = generic_params
1371 .iter()
1372 .map(|param| param.rewrite(context, shape))
1373 .collect::<Option<Vec<_>>>()?
1374 .join(", ");
1375 if result.is_empty() {
1376 None
1377 } else {
1378 Some(result)
1379 }
1380}