rustfmt_nightly/
types.rs

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
38// Does not wrap on simple segments.
39pub(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    // 32 covers almost all path lengths measured when compiling core, and there isn't a big
49    // downside from allocating slightly more than necessary.
50    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            // 3 = ">::".len()
71            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        // Indicates a global path, shouldn't be rendered.
116        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
259// Formats a path segment. There are some hacks involved to correctly determine
260// the segment's associated span since it's not part of the AST.
261//
262// The span_lo is assumed to be greater than the end of any previous segment's
263// parameters and lesser or equal than the start of current segment.
264//
265// span_hi is assumed equal to the end of the entire path.
266//
267// When the segment contains a positive number of parameters, we update span_lo
268// so that invariants described above will hold for the next segment.
269fn 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                // HACK: squeeze out the span between the identifier and the parameters.
293                // The hack is required so that we don't remove the separator inside macro calls.
294                // This does not work in the presence of comment, hoping that people are
295                // sane about where to put their comment.
296                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                // Update position of last bracket.
308                *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        // 4 = " -> "
337        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        // 2 for ()
355        let budget = shape
356            .width
357            .checked_sub(2)
358            .max_width_error(shape.width, span)?;
359        // 1 for (
360        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
444// If the return type is multi-lined, then force to use multiple lines for
445// arguments as well.
446fn 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            // 2 is for the case of ',\n'
455            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        // FIXME: dead spans?
468        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        // FIXME: If there are more than one attributes, this will force multiline.
682        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                &param,
749                mk_sp(last_attr.span.hi(), param_start),
750                shape,
751                !last_attr.is_doc_comment(),
752            )?;
753        } else {
754            // When rewriting generic params, an extra newline should be put
755            // if the attributes end with a doc comment
756            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(&param);
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            // 6 is "for<> ".len()
778            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                // we have to consider 'dyn' keyword is used or not!!!
831                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                // We may have falsely removed a trailing `+` inside macro call.
848                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                            &lt_str,
889                            before_lt_span,
890                            shape,
891                            true,
892                        )?;
893                    } else {
894                        result.push_str(&lt_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            // FIXME: we drop any comments here, even though it's a silly place to put
951            // comments.
952            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                // 2 = ()
966                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, None, context, shape, MacroPosition::Expression)
1022            }
1023            ast::TyKind::ImplicitSelf => Ok(String::from("")),
1024            ast::TyKind::ImplTrait(_, ref it) => {
1025                // Empty trait is not a parser error.
1026                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                    // We always want to write `unsafe<>` since `unsafe<> Ty`
1057                    // and `Ty` are distinct types.
1058                    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::Err(_) => Err(RewriteError::Unknown),
1097        }
1098    }
1099}
1100
1101fn rewrite_bare_fn(
1102    bare_fn: &ast::BareFnTy,
1103    span: Span,
1104    context: &RewriteContext<'_>,
1105    shape: Shape,
1106) -> RewriteResult {
1107    debug!("rewrite_bare_fn {:#?}", shape);
1108
1109    let mut result = String::with_capacity(128);
1110
1111    if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &bare_fn.generic_params) {
1112        result.push_str("for<");
1113        // 6 = "for<> ".len(), 4 = "for<".
1114        // This doesn't work out so nicely for multiline situation with lots of
1115        // rightward drift. If that is a problem, we could use the list stuff.
1116        result.push_str(lifetime_str);
1117        result.push_str("> ");
1118    }
1119
1120    result.push_str(crate::utils::format_safety(bare_fn.safety));
1121
1122    result.push_str(&format_extern(
1123        bare_fn.ext,
1124        context.config.force_explicit_abi(),
1125    ));
1126
1127    result.push_str("fn");
1128
1129    let func_ty_shape = if context.use_block_indent() {
1130        shape
1131            .offset_left(result.len())
1132            .max_width_error(shape.width, span)?
1133    } else {
1134        shape
1135            .visual_indent(result.len())
1136            .sub_width(result.len())
1137            .max_width_error(shape.width, span)?
1138    };
1139
1140    let rewrite = format_function_type(
1141        bare_fn.decl.inputs.iter(),
1142        &bare_fn.decl.output,
1143        bare_fn.decl.c_variadic(),
1144        span,
1145        context,
1146        func_ty_shape,
1147    )?;
1148
1149    result.push_str(&rewrite);
1150
1151    Ok(result)
1152}
1153
1154fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
1155    let is_trait = |b: &ast::GenericBound| match b {
1156        ast::GenericBound::Outlives(..) => false,
1157        ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => true,
1158    };
1159    let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
1160    let last_trait_index = generic_bounds.iter().rposition(is_trait);
1161    let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
1162    match (last_trait_index, first_lifetime_index) {
1163        (Some(last_trait_index), Some(first_lifetime_index)) => {
1164            last_trait_index < first_lifetime_index
1165        }
1166        _ => true,
1167    }
1168}
1169
1170fn join_bounds(
1171    context: &RewriteContext<'_>,
1172    shape: Shape,
1173    items: &[ast::GenericBound],
1174    need_indent: bool,
1175) -> RewriteResult {
1176    join_bounds_inner(context, shape, items, need_indent, false)
1177}
1178
1179fn join_bounds_inner(
1180    context: &RewriteContext<'_>,
1181    shape: Shape,
1182    items: &[ast::GenericBound],
1183    need_indent: bool,
1184    force_newline: bool,
1185) -> RewriteResult {
1186    debug_assert!(!items.is_empty());
1187
1188    let generic_bounds_in_order = is_generic_bounds_in_order(items);
1189    let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
1190        ast::GenericBound::Outlives(..) => true,
1191        // We treat `use<>` like a trait bound here.
1192        ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => last_line_extendable(s),
1193    };
1194
1195    // Whether a GenericBound item is a PathSegment segment that includes internal array
1196    // that contains more than one item
1197    let is_item_with_multi_items_array = |item: &ast::GenericBound| match item {
1198        ast::GenericBound::Trait(ref poly_trait_ref, ..) => {
1199            let segments = &poly_trait_ref.trait_ref.path.segments;
1200            if segments.len() > 1 {
1201                true
1202            } else {
1203                if let Some(args_in) = &segments[0].args {
1204                    matches!(
1205                        args_in.deref(),
1206                        ast::GenericArgs::AngleBracketed(bracket_args)
1207                            if bracket_args.args.len() > 1
1208                    )
1209                } else {
1210                    false
1211                }
1212            }
1213        }
1214        ast::GenericBound::Use(args, _) => args.len() > 1,
1215        _ => false,
1216    };
1217
1218    let result = items.iter().enumerate().try_fold(
1219        (String::new(), None, false),
1220        |(strs, prev_trailing_span, prev_extendable), (i, item)| {
1221            let trailing_span = if i < items.len() - 1 {
1222                let hi = context
1223                    .snippet_provider
1224                    .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
1225
1226                Some(mk_sp(item.span().hi(), hi))
1227            } else {
1228                None
1229            };
1230            let (leading_span, has_leading_comment) = if i > 0 {
1231                let lo = context
1232                    .snippet_provider
1233                    .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
1234
1235                let span = mk_sp(lo, item.span().lo());
1236
1237                let has_comments = contains_comment(context.snippet(span));
1238
1239                (Some(mk_sp(lo, item.span().lo())), has_comments)
1240            } else {
1241                (None, false)
1242            };
1243            let prev_has_trailing_comment = match prev_trailing_span {
1244                Some(ts) => contains_comment(context.snippet(ts)),
1245                _ => false,
1246            };
1247
1248            let shape = if need_indent && force_newline {
1249                shape
1250                    .block_indent(context.config.tab_spaces())
1251                    .with_max_width(context.config)
1252            } else {
1253                shape
1254            };
1255            let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
1256                shape
1257                    .indent
1258                    .to_string_with_newline(context.config)
1259                    .to_string()
1260            } else {
1261                String::from(" ")
1262            };
1263
1264            let joiner = match context.config.type_punctuation_density() {
1265                TypeDensity::Compressed => String::from("+"),
1266                TypeDensity::Wide => whitespace + "+ ",
1267            };
1268            let joiner = if has_leading_comment {
1269                joiner.trim_end()
1270            } else {
1271                &joiner
1272            };
1273            let joiner = if prev_has_trailing_comment {
1274                joiner.trim_start()
1275            } else {
1276                joiner
1277            };
1278
1279            let (extendable, trailing_str) = if i == 0 {
1280                let bound_str = item.rewrite_result(context, shape)?;
1281                (is_bound_extendable(&bound_str, item), bound_str)
1282            } else {
1283                let bound_str = &item.rewrite_result(context, shape)?;
1284                match leading_span {
1285                    Some(ls) if has_leading_comment => (
1286                        is_bound_extendable(bound_str, item),
1287                        combine_strs_with_missing_comments(
1288                            context, joiner, bound_str, ls, shape, true,
1289                        )?,
1290                    ),
1291                    _ => (
1292                        is_bound_extendable(bound_str, item),
1293                        String::from(joiner) + bound_str,
1294                    ),
1295                }
1296            };
1297            match prev_trailing_span {
1298                Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1299                    context,
1300                    &strs,
1301                    &trailing_str,
1302                    ts,
1303                    shape,
1304                    true,
1305                )
1306                .map(|v| (v, trailing_span, extendable)),
1307                _ => Ok((strs + &trailing_str, trailing_span, extendable)),
1308            }
1309        },
1310    )?;
1311
1312    // Whether to retry with a forced newline:
1313    //   Only if result is not already multiline and did not exceed line width,
1314    //   and either there is more than one item;
1315    //       or the single item is of type `Trait`,
1316    //          and any of the internal arrays contains more than one item;
1317    let retry_with_force_newline = match context.config.style_edition() {
1318        style_edition @ _ if style_edition <= StyleEdition::Edition2021 => {
1319            !force_newline
1320                && items.len() > 1
1321                && (result.0.contains('\n') || result.0.len() > shape.width)
1322        }
1323        _ if force_newline => false,
1324        _ if (!result.0.contains('\n') && result.0.len() <= shape.width) => false,
1325        _ if items.len() > 1 => true,
1326        _ => is_item_with_multi_items_array(&items[0]),
1327    };
1328
1329    if retry_with_force_newline {
1330        join_bounds_inner(context, shape, items, need_indent, true)
1331    } else {
1332        Ok(result.0)
1333    }
1334}
1335
1336pub(crate) fn opaque_ty(ty: &Option<ptr::P<ast::Ty>>) -> Option<&ast::GenericBounds> {
1337    ty.as_ref().and_then(|t| match &t.kind {
1338        ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1339        _ => None,
1340    })
1341}
1342
1343pub(crate) fn can_be_overflowed_type(
1344    context: &RewriteContext<'_>,
1345    ty: &ast::Ty,
1346    len: usize,
1347) -> bool {
1348    match ty.kind {
1349        ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1350        ast::TyKind::Ref(_, ref mutty)
1351        | ast::TyKind::PinnedRef(_, ref mutty)
1352        | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len),
1353        _ => false,
1354    }
1355}
1356
1357/// Returns `None` if there is no `GenericParam` in the list
1358pub(crate) fn rewrite_bound_params(
1359    context: &RewriteContext<'_>,
1360    shape: Shape,
1361    generic_params: &[ast::GenericParam],
1362) -> Option<String> {
1363    let result = generic_params
1364        .iter()
1365        .map(|param| param.rewrite(context, shape))
1366        .collect::<Option<Vec<_>>>()?
1367        .join(", ");
1368    if result.is_empty() {
1369        None
1370    } else {
1371        Some(result)
1372    }
1373}