Skip to main content

rustfmt_nightly/
types.rs

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