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 kw_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 kw_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::DynStar => {
839 let shape = shape
840 .offset_left(5)
841 .max_width_error(shape.width, self.span())?;
842 (shape, "dyn* ")
843 }
844 ast::TraitObjectSyntax::None => (shape, ""),
845 };
846 let mut res = bounds.rewrite_result(context, shape)?;
847 if context.inside_macro()
849 && bounds.len() == 1
850 && context.snippet(self.span).ends_with('+')
851 && !res.ends_with('+')
852 {
853 res.push('+');
854 }
855 Ok(format!("{prefix}{res}"))
856 }
857 ast::TyKind::Ptr(ref mt) => {
858 let prefix = match mt.mutbl {
859 Mutability::Mut => "*mut ",
860 Mutability::Not => "*const ",
861 };
862
863 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
864 }
865 ast::TyKind::Ref(ref lifetime, ref mt)
866 | ast::TyKind::PinnedRef(ref lifetime, ref mt) => {
867 let mut_str = format_mutability(mt.mutbl);
868 let mut_len = mut_str.len();
869 let mut result = String::with_capacity(128);
870 result.push('&');
871 let ref_hi = context.snippet_provider.span_after(self.span(), "&");
872 let mut cmnt_lo = ref_hi;
873
874 if let Some(ref lifetime) = *lifetime {
875 let lt_budget = shape
876 .width
877 .checked_sub(2 + mut_len)
878 .max_width_error(shape.width, self.span())?;
879 let lt_str = lifetime.rewrite_result(
880 context,
881 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
882 )?;
883 let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
884 if contains_comment(context.snippet(before_lt_span)) {
885 result = combine_strs_with_missing_comments(
886 context,
887 &result,
888 <_str,
889 before_lt_span,
890 shape,
891 true,
892 )?;
893 } else {
894 result.push_str(<_str);
895 }
896 result.push(' ');
897 cmnt_lo = lifetime.ident.span.hi();
898 }
899
900 if let ast::TyKind::PinnedRef(..) = self.kind {
901 result.push_str("pin ");
902 if ast::Mutability::Not == mt.mutbl {
903 result.push_str("const ");
904 }
905 }
906
907 if ast::Mutability::Mut == mt.mutbl {
908 let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
909 let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
910 if contains_comment(context.snippet(before_mut_span)) {
911 result = combine_strs_with_missing_comments(
912 context,
913 result.trim_end(),
914 mut_str,
915 before_mut_span,
916 shape,
917 true,
918 )?;
919 } else {
920 result.push_str(mut_str);
921 }
922 cmnt_lo = mut_hi;
923 }
924
925 let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
926 if contains_comment(context.snippet(before_ty_span)) {
927 result = combine_strs_with_missing_comments(
928 context,
929 result.trim_end(),
930 &mt.ty.rewrite_result(context, shape)?,
931 before_ty_span,
932 shape,
933 true,
934 )?;
935 } else {
936 let used_width = last_line_width(&result);
937 let budget = shape
938 .width
939 .checked_sub(used_width)
940 .max_width_error(shape.width, self.span())?;
941 let ty_str = mt.ty.rewrite_result(
942 context,
943 Shape::legacy(budget, shape.indent + used_width),
944 )?;
945 result.push_str(&ty_str);
946 }
947
948 Ok(result)
949 }
950 ast::TyKind::Paren(ref ty) => {
953 if context.config.style_edition() <= StyleEdition::Edition2021
954 || context.config.indent_style() == IndentStyle::Visual
955 {
956 let budget = shape
957 .width
958 .checked_sub(2)
959 .max_width_error(shape.width, self.span())?;
960 return ty
961 .rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
962 .map(|ty_str| format!("({})", ty_str));
963 }
964
965 if let Some(sh) = shape.sub_width(2) {
967 if let Ok(ref s) = ty.rewrite_result(context, sh) {
968 if !s.contains('\n') {
969 return Ok(format!("({s})"));
970 }
971 }
972 }
973
974 let indent_str = shape.indent.to_string_with_newline(context.config);
975 let shape = shape
976 .block_indent(context.config.tab_spaces())
977 .with_max_width(context.config);
978 let rw = ty.rewrite_result(context, shape)?;
979 Ok(format!(
980 "({}{}{})",
981 shape.to_string_with_newline(context.config),
982 rw,
983 indent_str
984 ))
985 }
986 ast::TyKind::Slice(ref ty) => {
987 let budget = shape
988 .width
989 .checked_sub(4)
990 .max_width_error(shape.width, self.span())?;
991 ty.rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
992 .map(|ty_str| format!("[{}]", ty_str))
993 }
994 ast::TyKind::Tup(ref items) => {
995 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
996 }
997 ast::TyKind::Path(ref q_self, ref path) => {
998 rewrite_path(context, PathContext::Type, q_self, path, shape)
999 }
1000 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
1001 &**ty,
1002 &*repeats.value,
1003 PairParts::new("[", "; ", "]"),
1004 context,
1005 shape,
1006 SeparatorPlace::Back,
1007 ),
1008 ast::TyKind::Infer => {
1009 if shape.width >= 1 {
1010 Ok("_".to_owned())
1011 } else {
1012 Err(RewriteError::ExceedsMaxWidth {
1013 configured_width: shape.width,
1014 span: self.span(),
1015 })
1016 }
1017 }
1018 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
1019 ast::TyKind::Never => Ok(String::from("!")),
1020 ast::TyKind::MacCall(ref mac) => {
1021 rewrite_macro(mac, context, shape, MacroPosition::Expression)
1022 }
1023 ast::TyKind::ImplicitSelf => Ok(String::from("")),
1024 ast::TyKind::ImplTrait(_, ref it) => {
1025 if it.is_empty() {
1027 return Ok("impl".to_owned());
1028 }
1029 let rw = if context.config.style_edition() <= StyleEdition::Edition2021 {
1030 it.rewrite_result(context, shape)
1031 } else {
1032 join_bounds(context, shape, it, false)
1033 };
1034 rw.map(|it_str| {
1035 let space = if it_str.is_empty() { "" } else { " " };
1036 format!("impl{}{}", space, it_str)
1037 })
1038 }
1039 ast::TyKind::CVarArgs => Ok("...".to_owned()),
1040 ast::TyKind::Dummy | ast::TyKind::Err(_) => Ok(context.snippet(self.span).to_owned()),
1041 ast::TyKind::Typeof(ref anon_const) => rewrite_call(
1042 context,
1043 "typeof",
1044 &[anon_const.value.clone()],
1045 self.span,
1046 shape,
1047 ),
1048 ast::TyKind::Pat(ref ty, ref pat) => {
1049 let ty = ty.rewrite_result(context, shape)?;
1050 let pat = pat.rewrite_result(context, shape)?;
1051 Ok(format!("{ty} is {pat}"))
1052 }
1053 ast::TyKind::UnsafeBinder(ref binder) => {
1054 let mut result = String::new();
1055 if binder.generic_params.is_empty() {
1056 result.push_str("unsafe<> ")
1059 } else if let Some(ref lifetime_str) =
1060 rewrite_bound_params(context, shape, &binder.generic_params)
1061 {
1062 result.push_str("unsafe<");
1063 result.push_str(lifetime_str);
1064 result.push_str("> ");
1065 }
1066
1067 let inner_ty_shape = if context.use_block_indent() {
1068 shape
1069 .offset_left(result.len())
1070 .max_width_error(shape.width, self.span())?
1071 } else {
1072 shape
1073 .visual_indent(result.len())
1074 .sub_width(result.len())
1075 .max_width_error(shape.width, self.span())?
1076 };
1077
1078 let rewrite = binder.inner_ty.rewrite_result(context, inner_ty_shape)?;
1079 result.push_str(&rewrite);
1080 Ok(result)
1081 }
1082 }
1083 }
1084}
1085
1086impl Rewrite for ast::TyPat {
1087 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1088 self.rewrite_result(context, shape).ok()
1089 }
1090
1091 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1092 match self.kind {
1093 ast::TyPatKind::Range(ref lhs, ref rhs, ref end_kind) => {
1094 rewrite_range_pat(context, shape, lhs, rhs, end_kind, self.span)
1095 }
1096 ast::TyPatKind::Or(ref variants) => {
1097 let mut first = true;
1098 let mut s = String::new();
1099 for variant in variants {
1100 if first {
1101 first = false
1102 } else {
1103 s.push_str(" | ");
1104 }
1105 s.push_str(&variant.rewrite_result(context, shape)?);
1106 }
1107 Ok(s)
1108 }
1109 ast::TyPatKind::Err(_) => Err(RewriteError::Unknown),
1110 }
1111 }
1112}
1113
1114fn rewrite_bare_fn(
1115 bare_fn: &ast::BareFnTy,
1116 span: Span,
1117 context: &RewriteContext<'_>,
1118 shape: Shape,
1119) -> RewriteResult {
1120 debug!("rewrite_bare_fn {:#?}", shape);
1121
1122 let mut result = String::with_capacity(128);
1123
1124 if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &bare_fn.generic_params) {
1125 result.push_str("for<");
1126 result.push_str(lifetime_str);
1130 result.push_str("> ");
1131 }
1132
1133 result.push_str(crate::utils::format_safety(bare_fn.safety));
1134
1135 result.push_str(&format_extern(
1136 bare_fn.ext,
1137 context.config.force_explicit_abi(),
1138 ));
1139
1140 result.push_str("fn");
1141
1142 let func_ty_shape = if context.use_block_indent() {
1143 shape
1144 .offset_left(result.len())
1145 .max_width_error(shape.width, span)?
1146 } else {
1147 shape
1148 .visual_indent(result.len())
1149 .sub_width(result.len())
1150 .max_width_error(shape.width, span)?
1151 };
1152
1153 let rewrite = format_function_type(
1154 bare_fn.decl.inputs.iter(),
1155 &bare_fn.decl.output,
1156 bare_fn.decl.c_variadic(),
1157 span,
1158 context,
1159 func_ty_shape,
1160 )?;
1161
1162 result.push_str(&rewrite);
1163
1164 Ok(result)
1165}
1166
1167fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
1168 let is_trait = |b: &ast::GenericBound| match b {
1169 ast::GenericBound::Outlives(..) => false,
1170 ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => true,
1171 };
1172 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
1173 let last_trait_index = generic_bounds.iter().rposition(is_trait);
1174 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
1175 match (last_trait_index, first_lifetime_index) {
1176 (Some(last_trait_index), Some(first_lifetime_index)) => {
1177 last_trait_index < first_lifetime_index
1178 }
1179 _ => true,
1180 }
1181}
1182
1183fn join_bounds(
1184 context: &RewriteContext<'_>,
1185 shape: Shape,
1186 items: &[ast::GenericBound],
1187 need_indent: bool,
1188) -> RewriteResult {
1189 join_bounds_inner(context, shape, items, need_indent, false)
1190}
1191
1192fn join_bounds_inner(
1193 context: &RewriteContext<'_>,
1194 shape: Shape,
1195 items: &[ast::GenericBound],
1196 need_indent: bool,
1197 force_newline: bool,
1198) -> RewriteResult {
1199 debug_assert!(!items.is_empty());
1200
1201 let generic_bounds_in_order = is_generic_bounds_in_order(items);
1202 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
1203 ast::GenericBound::Outlives(..) => true,
1204 ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => last_line_extendable(s),
1206 };
1207
1208 let is_item_with_multi_items_array = |item: &ast::GenericBound| match item {
1211 ast::GenericBound::Trait(ref poly_trait_ref, ..) => {
1212 let segments = &poly_trait_ref.trait_ref.path.segments;
1213 if segments.len() > 1 {
1214 true
1215 } else {
1216 if let Some(args_in) = &segments[0].args {
1217 matches!(
1218 args_in.deref(),
1219 ast::GenericArgs::AngleBracketed(bracket_args)
1220 if bracket_args.args.len() > 1
1221 )
1222 } else {
1223 false
1224 }
1225 }
1226 }
1227 ast::GenericBound::Use(args, _) => args.len() > 1,
1228 _ => false,
1229 };
1230
1231 let result = items.iter().enumerate().try_fold(
1232 (String::new(), None, false),
1233 |(strs, prev_trailing_span, prev_extendable), (i, item)| {
1234 let trailing_span = if i < items.len() - 1 {
1235 let hi = context
1236 .snippet_provider
1237 .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
1238
1239 Some(mk_sp(item.span().hi(), hi))
1240 } else {
1241 None
1242 };
1243 let (leading_span, has_leading_comment) = if i > 0 {
1244 let lo = context
1245 .snippet_provider
1246 .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
1247
1248 let span = mk_sp(lo, item.span().lo());
1249
1250 let has_comments = contains_comment(context.snippet(span));
1251
1252 (Some(mk_sp(lo, item.span().lo())), has_comments)
1253 } else {
1254 (None, false)
1255 };
1256 let prev_has_trailing_comment = match prev_trailing_span {
1257 Some(ts) => contains_comment(context.snippet(ts)),
1258 _ => false,
1259 };
1260
1261 let shape = if need_indent && force_newline {
1262 shape
1263 .block_indent(context.config.tab_spaces())
1264 .with_max_width(context.config)
1265 } else {
1266 shape
1267 };
1268 let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
1269 shape
1270 .indent
1271 .to_string_with_newline(context.config)
1272 .to_string()
1273 } else {
1274 String::from(" ")
1275 };
1276
1277 let joiner = match context.config.type_punctuation_density() {
1278 TypeDensity::Compressed => String::from("+"),
1279 TypeDensity::Wide => whitespace + "+ ",
1280 };
1281 let joiner = if has_leading_comment {
1282 joiner.trim_end()
1283 } else {
1284 &joiner
1285 };
1286 let joiner = if prev_has_trailing_comment {
1287 joiner.trim_start()
1288 } else {
1289 joiner
1290 };
1291
1292 let (extendable, trailing_str) = if i == 0 {
1293 let bound_str = item.rewrite_result(context, shape)?;
1294 (is_bound_extendable(&bound_str, item), bound_str)
1295 } else {
1296 let bound_str = &item.rewrite_result(context, shape)?;
1297 match leading_span {
1298 Some(ls) if has_leading_comment => (
1299 is_bound_extendable(bound_str, item),
1300 combine_strs_with_missing_comments(
1301 context, joiner, bound_str, ls, shape, true,
1302 )?,
1303 ),
1304 _ => (
1305 is_bound_extendable(bound_str, item),
1306 String::from(joiner) + bound_str,
1307 ),
1308 }
1309 };
1310 match prev_trailing_span {
1311 Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1312 context,
1313 &strs,
1314 &trailing_str,
1315 ts,
1316 shape,
1317 true,
1318 )
1319 .map(|v| (v, trailing_span, extendable)),
1320 _ => Ok((strs + &trailing_str, trailing_span, extendable)),
1321 }
1322 },
1323 )?;
1324
1325 let retry_with_force_newline = match context.config.style_edition() {
1331 style_edition @ _ if style_edition <= StyleEdition::Edition2021 => {
1332 !force_newline
1333 && items.len() > 1
1334 && (result.0.contains('\n') || result.0.len() > shape.width)
1335 }
1336 _ if force_newline => false,
1337 _ if (!result.0.contains('\n') && result.0.len() <= shape.width) => false,
1338 _ if items.len() > 1 => true,
1339 _ => is_item_with_multi_items_array(&items[0]),
1340 };
1341
1342 if retry_with_force_newline {
1343 join_bounds_inner(context, shape, items, need_indent, true)
1344 } else {
1345 Ok(result.0)
1346 }
1347}
1348
1349pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
1350 ty.as_ref().and_then(|t| match &t.kind {
1351 ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1352 _ => None,
1353 })
1354}
1355
1356pub(crate) fn can_be_overflowed_type(
1357 context: &RewriteContext<'_>,
1358 ty: &ast::Ty,
1359 len: usize,
1360) -> bool {
1361 match ty.kind {
1362 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1363 ast::TyKind::Ref(_, ref mutty)
1364 | ast::TyKind::PinnedRef(_, ref mutty)
1365 | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len),
1366 _ => false,
1367 }
1368}
1369
1370pub(crate) fn rewrite_bound_params(
1372 context: &RewriteContext<'_>,
1373 shape: Shape,
1374 generic_params: &[ast::GenericParam],
1375) -> Option<String> {
1376 let result = generic_params
1377 .iter()
1378 .map(|param| param.rewrite(context, shape))
1379 .collect::<Option<Vec<_>>>()?
1380 .join(", ");
1381 if result.is_empty() {
1382 None
1383 } else {
1384 Some(result)
1385 }
1386}