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()
420        || last_line_width(&args, context.config.tab_spaces()) + first_line_width(&output)
421            <= shape.width
422    {
423        Ok(format!("{args}{output}"))
424    } else {
425        Ok(format!(
426            "{}\n{}{}",
427            args,
428            list_shape.indent.to_string(context.config),
429            output.trim_start()
430        ))
431    }
432}
433
434fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
435    colon_spaces(context.config)
436}
437
438// If the return type is multi-lined, then force to use multiple lines for
439// arguments as well.
440fn get_tactics(item_vec: &[ListItem], output: &str, shape: Shape) -> DefinitiveListTactic {
441    if output.contains('\n') {
442        DefinitiveListTactic::Vertical
443    } else {
444        definitive_tactic(
445            item_vec,
446            ListTactic::HorizontalVertical,
447            Separator::Comma,
448            // 2 is for the case of ',\n'
449            shape.width.saturating_sub(2 + output.len()),
450        )
451    }
452}
453
454impl Rewrite for ast::WherePredicate {
455    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
456        self.rewrite_result(context, shape).ok()
457    }
458
459    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
460        let attrs_str = self.attrs.rewrite_result(context, shape)?;
461        // FIXME: dead spans?
462        let pred_str = &match self.kind {
463            ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
464                ref bound_generic_params,
465                ref bounded_ty,
466                ref bounds,
467                ..
468            }) => {
469                let type_str = bounded_ty.rewrite_result(context, shape)?;
470                let colon = type_bound_colon(context).trim_end();
471                let lhs = if let Some(binder_str) =
472                    rewrite_bound_params(context, shape, bound_generic_params)
473                {
474                    format!("for<{binder_str}> {type_str}{colon}")
475                } else {
476                    format!("{type_str}{colon}")
477                };
478
479                rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)?
480            }
481            ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
482                ref lifetime,
483                ref bounds,
484            }) => rewrite_bounded_lifetime(lifetime, bounds, self.span, context, shape)?,
485        };
486
487        let mut result = String::with_capacity(attrs_str.len() + pred_str.len() + 1);
488        result.push_str(&attrs_str);
489        let pred_start = self.span.lo();
490        let line_len = last_line_width(&attrs_str, context.config.tab_spaces())
491            + 1
492            + first_line_width(&pred_str);
493        if let Some(last_attr) = self.attrs.last().filter(|last_attr| {
494            contains_comment(context.snippet(mk_sp(last_attr.span.hi(), pred_start)))
495        }) {
496            result = combine_strs_with_missing_comments(
497                context,
498                &result,
499                &pred_str,
500                mk_sp(last_attr.span.hi(), pred_start),
501                Shape {
502                    width: shape.width.min(context.config.inline_attribute_width()),
503                    ..shape
504                },
505                !last_attr.is_doc_comment(),
506            )?;
507        } else {
508            if !self.attrs.is_empty() {
509                if context.config.inline_attribute_width() < line_len
510                    || self.attrs.len() > 1
511                    || self.attrs.last().is_some_and(|a| a.is_doc_comment())
512                {
513                    result.push_str(&shape.indent.to_string_with_newline(context.config));
514                } else {
515                    result.push(' ');
516                }
517            }
518            result.push_str(&pred_str);
519        }
520
521        Ok(result)
522    }
523}
524
525impl Rewrite for ast::GenericArg {
526    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
527        self.rewrite_result(context, shape).ok()
528    }
529
530    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
531        match *self {
532            ast::GenericArg::Lifetime(ref lt) => lt.rewrite_result(context, shape),
533            ast::GenericArg::Type(ref ty) => ty.rewrite_result(context, shape),
534            ast::GenericArg::Const(ref const_) => const_.rewrite_result(context, shape),
535        }
536    }
537}
538
539fn rewrite_generic_args(
540    gen_args: &ast::GenericArgs,
541    context: &RewriteContext<'_>,
542    shape: Shape,
543    span: Span,
544) -> RewriteResult {
545    match gen_args {
546        ast::GenericArgs::AngleBracketed(ref data) => {
547            if data.args.is_empty() {
548                Ok("".to_owned())
549            } else {
550                let args = data
551                    .args
552                    .iter()
553                    .map(|x| match x {
554                        ast::AngleBracketedArg::Arg(generic_arg) => {
555                            SegmentParam::from_generic_arg(generic_arg)
556                        }
557                        ast::AngleBracketedArg::Constraint(constraint) => {
558                            SegmentParam::Binding(constraint)
559                        }
560                    })
561                    .collect::<Vec<_>>();
562
563                overflow::rewrite_with_angle_brackets(context, "", args.iter(), shape, span)
564            }
565        }
566        ast::GenericArgs::Parenthesized(ref data) => {
567            format_function_type(&data.inputs, &data.output, false, data.span, context, shape)
568        }
569        ast::GenericArgs::ParenthesizedElided(..) => Ok("(..)".to_owned()),
570    }
571}
572
573fn rewrite_bounded_lifetime(
574    lt: &ast::Lifetime,
575    bounds: &[ast::GenericBound],
576    span: Span,
577    context: &RewriteContext<'_>,
578    shape: Shape,
579) -> RewriteResult {
580    let result = lt.rewrite_result(context, shape)?;
581
582    if bounds.is_empty() {
583        Ok(result)
584    } else {
585        let colon = type_bound_colon(context);
586        let overhead = last_line_width(&result, context.config.tab_spaces()) + colon.len();
587        let shape = shape.sub_width(overhead, span)?;
588        let result = format!(
589            "{}{}{}",
590            result,
591            colon,
592            join_bounds(context, shape, bounds, true)?
593        );
594        Ok(result)
595    }
596}
597
598impl Rewrite for ast::AnonConst {
599    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
600        self.rewrite_result(context, shape).ok()
601    }
602
603    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
604        format_expr(&self.value, ExprType::SubExpression, context, shape)
605    }
606}
607
608impl Rewrite for ast::Lifetime {
609    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
610        self.rewrite_result(context, shape).ok()
611    }
612
613    fn rewrite_result(&self, context: &RewriteContext<'_>, _: Shape) -> RewriteResult {
614        Ok(context.snippet(self.ident.span).to_owned())
615    }
616}
617
618impl Rewrite for ast::GenericBound {
619    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
620        self.rewrite_result(context, shape).ok()
621    }
622
623    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
624        match *self {
625            ast::GenericBound::Trait(ref poly_trait_ref) => {
626                let snippet = context.snippet(self.span());
627                let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
628                poly_trait_ref
629                    .rewrite_result(context, shape)
630                    .map(|s| if has_paren { format!("({})", s) } else { s })
631            }
632            ast::GenericBound::Use(ref args, span) => {
633                overflow::rewrite_with_angle_brackets(context, "use", args.iter(), shape, span)
634            }
635            ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite_result(context, shape),
636        }
637    }
638}
639
640impl Rewrite for ast::GenericBounds {
641    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
642        self.rewrite_result(context, shape).ok()
643    }
644
645    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
646        if self.is_empty() {
647            return Ok(String::new());
648        }
649
650        join_bounds(context, shape, self, true)
651    }
652}
653
654impl Rewrite for ast::GenericParam {
655    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
656        self.rewrite_result(context, shape).ok()
657    }
658
659    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
660        // FIXME: If there are more than one attributes, this will force multiline.
661        let mut result = self
662            .attrs
663            .rewrite_result(context, shape)
664            .unwrap_or(String::new());
665        let has_attrs = !result.is_empty();
666
667        let mut param = String::with_capacity(128);
668
669        let param_start = if let ast::GenericParamKind::Const {
670            ref ty,
671            span,
672            default,
673        } = &self.kind
674        {
675            param.push_str("const ");
676            param.push_str(rewrite_ident(context, self.ident));
677            param.push_str(": ");
678            param.push_str(&ty.rewrite_result(context, shape)?);
679            if let Some(default) = default {
680                let eq_str = match context.config.type_punctuation_density() {
681                    TypeDensity::Compressed => "=",
682                    TypeDensity::Wide => " = ",
683                };
684                param.push_str(eq_str);
685                let budget = shape
686                    .width
687                    .checked_sub(param.len())
688                    .max_width_error(shape.width, self.span())?;
689                let rewrite =
690                    default.rewrite_result(context, Shape::legacy(budget, shape.indent))?;
691                param.push_str(&rewrite);
692            }
693            span.lo()
694        } else {
695            param.push_str(rewrite_ident(context, self.ident));
696            self.ident.span.lo()
697        };
698
699        if !self.bounds.is_empty() {
700            param.push_str(type_bound_colon(context));
701            param.push_str(&self.bounds.rewrite_result(context, shape)?)
702        }
703        if let ast::GenericParamKind::Type {
704            default: Some(ref def),
705        } = self.kind
706        {
707            let eq_str = match context.config.type_punctuation_density() {
708                TypeDensity::Compressed => "=",
709                TypeDensity::Wide => " = ",
710            };
711            param.push_str(eq_str);
712            let budget = shape
713                .width
714                .checked_sub(param.len())
715                .max_width_error(shape.width, self.span())?;
716            let rewrite =
717                def.rewrite_result(context, Shape::legacy(budget, shape.indent + param.len()))?;
718            param.push_str(&rewrite);
719        }
720
721        if let Some(last_attr) = self.attrs.last().filter(|last_attr| {
722            contains_comment(context.snippet(mk_sp(last_attr.span.hi(), param_start)))
723        }) {
724            result = combine_strs_with_missing_comments(
725                context,
726                &result,
727                &param,
728                mk_sp(last_attr.span.hi(), param_start),
729                shape,
730                !last_attr.is_doc_comment(),
731            )?;
732        } else {
733            // When rewriting generic params, an extra newline should be put
734            // if the attributes end with a doc comment
735            if let Some(true) = self.attrs.last().map(|a| a.is_doc_comment()) {
736                result.push_str(&shape.indent.to_string_with_newline(context.config));
737            } else if has_attrs {
738                result.push(' ');
739            }
740            result.push_str(&param);
741        }
742
743        Ok(result)
744    }
745}
746
747impl Rewrite for ast::PolyTraitRef {
748    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
749        self.rewrite_result(context, shape).ok()
750    }
751
752    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
753        let (binder, shape) = if let Some(lifetime_str) =
754            rewrite_bound_params(context, shape, &self.bound_generic_params)
755        {
756            // 6 is "for<> ".len()
757            let extra_offset = lifetime_str.len() + 6;
758            let shape = shape.offset_left(extra_offset, self.span)?;
759            (format!("for<{lifetime_str}> "), shape)
760        } else {
761            (String::new(), shape)
762        };
763
764        let ast::TraitBoundModifiers {
765            constness,
766            asyncness,
767            polarity,
768        } = self.modifiers;
769        let mut constness = constness.as_str().to_string();
770        if !constness.is_empty() {
771            constness.push(' ');
772        }
773        let mut asyncness = asyncness.as_str().to_string();
774        if !asyncness.is_empty() {
775            asyncness.push(' ');
776        }
777        let polarity = polarity.as_str();
778        let shape = shape.offset_left(constness.len() + polarity.len(), self.span)?;
779
780        let path_str = self.trait_ref.rewrite_result(context, shape)?;
781        Ok(format!(
782            "{binder}{constness}{asyncness}{polarity}{path_str}"
783        ))
784    }
785}
786
787impl Rewrite for ast::TraitRef {
788    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
789        self.rewrite_result(context, shape).ok()
790    }
791
792    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
793        rewrite_path(context, PathContext::Type, &None, &self.path, shape)
794    }
795}
796
797impl Rewrite for ast::Ty {
798    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
799        self.rewrite_result(context, shape).ok()
800    }
801
802    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
803        match self.kind {
804            ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
805                // we have to consider 'dyn' keyword is used or not!!!
806                let (shape, prefix) = match tobj_syntax {
807                    ast::TraitObjectSyntax::Dyn => {
808                        let shape = shape.offset_left(4, self.span())?;
809                        (shape, "dyn ")
810                    }
811                    ast::TraitObjectSyntax::None => (shape, ""),
812                };
813                let mut res = bounds.rewrite_result(context, shape)?;
814                // We may have falsely removed a trailing `+` inside macro call.
815                if context.inside_macro()
816                    && bounds.len() == 1
817                    && context.snippet(self.span).ends_with('+')
818                    && !res.ends_with('+')
819                {
820                    res.push('+');
821                }
822                Ok(format!("{prefix}{res}"))
823            }
824            ast::TyKind::Ptr(ref mt) => {
825                let prefix = match mt.mutbl {
826                    Mutability::Mut => "*mut ",
827                    Mutability::Not => "*const ",
828                };
829
830                rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
831            }
832            ast::TyKind::Ref(ref lifetime, ref mt)
833            | ast::TyKind::PinnedRef(ref lifetime, ref mt) => {
834                let mut_str = format_mutability(mt.mutbl);
835                let mut_len = mut_str.len();
836                let mut result = String::with_capacity(128);
837                result.push('&');
838                let ref_hi = context.snippet_provider.span_after(self.span(), "&");
839                let mut cmnt_lo = ref_hi;
840
841                if let Some(ref lifetime) = *lifetime {
842                    let lt_budget = shape
843                        .width
844                        .checked_sub(2 + mut_len)
845                        .max_width_error(shape.width, self.span())?;
846                    let lt_str = lifetime.rewrite_result(
847                        context,
848                        Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
849                    )?;
850                    let before_lt_span = mk_sp(cmnt_lo, lifetime.ident.span.lo());
851                    if contains_comment(context.snippet(before_lt_span)) {
852                        result = combine_strs_with_missing_comments(
853                            context,
854                            &result,
855                            &lt_str,
856                            before_lt_span,
857                            shape,
858                            true,
859                        )?;
860                    } else {
861                        result.push_str(&lt_str);
862                    }
863                    result.push(' ');
864                    cmnt_lo = lifetime.ident.span.hi();
865                }
866
867                if let ast::TyKind::PinnedRef(..) = self.kind {
868                    result.push_str("pin ");
869                    if ast::Mutability::Not == mt.mutbl {
870                        result.push_str("const ");
871                    }
872                }
873
874                if ast::Mutability::Mut == mt.mutbl {
875                    let mut_hi = context.snippet_provider.span_after(self.span(), "mut");
876                    let before_mut_span = mk_sp(cmnt_lo, mut_hi - BytePos::from_usize(3));
877                    if contains_comment(context.snippet(before_mut_span)) {
878                        result = combine_strs_with_missing_comments(
879                            context,
880                            result.trim_end(),
881                            mut_str,
882                            before_mut_span,
883                            shape,
884                            true,
885                        )?;
886                    } else {
887                        result.push_str(mut_str);
888                    }
889                    cmnt_lo = mut_hi;
890                }
891
892                let before_ty_span = mk_sp(cmnt_lo, mt.ty.span.lo());
893                if contains_comment(context.snippet(before_ty_span)) {
894                    result = combine_strs_with_missing_comments(
895                        context,
896                        result.trim_end(),
897                        &mt.ty.rewrite_result(context, shape)?,
898                        before_ty_span,
899                        shape,
900                        true,
901                    )?;
902                } else {
903                    let used_width = last_line_width(&result, context.config.tab_spaces());
904                    let budget = shape
905                        .width
906                        .checked_sub(used_width)
907                        .max_width_error(shape.width, self.span())?;
908                    let ty_str = mt.ty.rewrite_result(
909                        context,
910                        Shape::legacy(budget, shape.indent + used_width),
911                    )?;
912                    result.push_str(&ty_str);
913                }
914
915                Ok(result)
916            }
917            // FIXME: we drop any comments here, even though it's a silly place to put
918            // comments.
919            ast::TyKind::Paren(ref ty) => {
920                if context.config.style_edition() <= StyleEdition::Edition2021
921                    || context.config.indent_style() == IndentStyle::Visual
922                {
923                    let budget = shape
924                        .width
925                        .checked_sub(2)
926                        .max_width_error(shape.width, self.span())?;
927                    return ty
928                        .rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
929                        .map(|ty_str| format!("({})", ty_str));
930                }
931
932                // 2 = ()
933                if let Some(sh) = shape.sub_width_opt(2) {
934                    if let Ok(ref s) = ty.rewrite_result(context, sh) {
935                        if !s.contains('\n') {
936                            return Ok(format!("({s})"));
937                        }
938                    }
939                }
940
941                let indent_str = shape.indent.to_string_with_newline(context.config);
942                let shape = shape
943                    .block_indent(context.config.tab_spaces())
944                    .with_max_width(context.config);
945                let rw = ty.rewrite_result(context, shape)?;
946                Ok(format!(
947                    "({}{}{})",
948                    shape.to_string_with_newline(context.config),
949                    rw,
950                    indent_str
951                ))
952            }
953            ast::TyKind::Slice(ref ty) => {
954                let budget = shape
955                    .width
956                    .checked_sub(4)
957                    .max_width_error(shape.width, self.span())?;
958                ty.rewrite_result(context, Shape::legacy(budget, shape.indent + 1))
959                    .map(|ty_str| format!("[{}]", ty_str))
960            }
961            ast::TyKind::Tup(ref items) => {
962                rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
963            }
964            ast::TyKind::Path(ref q_self, ref path) => {
965                rewrite_path(context, PathContext::Type, q_self, path, shape)
966            }
967            ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
968                &**ty,
969                &*repeats.value,
970                PairParts::new("[", "; ", "]"),
971                context,
972                shape,
973                SeparatorPlace::Back,
974            ),
975            ast::TyKind::Infer => {
976                if shape.width >= 1 {
977                    Ok("_".to_owned())
978                } else {
979                    Err(RewriteError::ExceedsMaxWidth {
980                        configured_width: shape.width,
981                        span: self.span(),
982                    })
983                }
984            }
985            ast::TyKind::FnPtr(ref fn_ptr) => rewrite_fn_ptr(fn_ptr, self.span, context, shape),
986            ast::TyKind::Never => Ok(String::from("!")),
987            ast::TyKind::MacCall(ref mac) => {
988                rewrite_macro(mac, context, shape, MacroPosition::Expression)
989            }
990            ast::TyKind::ImplicitSelf => Ok(String::from("")),
991            ast::TyKind::ImplTrait(_, ref it) => {
992                // Empty trait is not a parser error.
993                if it.is_empty() {
994                    return Ok("impl".to_owned());
995                }
996                let rw = if context.config.style_edition() <= StyleEdition::Edition2021 {
997                    it.rewrite_result(context, shape)
998                } else if context.config.style_edition() == StyleEdition::Edition2024 {
999                    join_bounds(context, shape, it, false)
1000                } else {
1001                    let offset = "impl ".len();
1002                    let shape = shape.offset_left(offset, self.span())?;
1003                    join_bounds(context, shape, it, false)
1004                };
1005
1006                rw.map(|it_str| {
1007                    let space = if it_str.is_empty() { "" } else { " " };
1008                    format!("impl{}{}", space, it_str)
1009                })
1010            }
1011            ast::TyKind::CVarArgs => Ok("...".to_owned()),
1012            ast::TyKind::FieldOf(ref ty, ref variant, ref field) => {
1013                let ty = ty.rewrite_result(context, shape)?;
1014                if let Some(variant) = variant {
1015                    Ok(format!("builtin # field_of({ty}, {variant}.{field})"))
1016                } else {
1017                    Ok(format!("builtin # field_of({ty}, {field})"))
1018                }
1019            }
1020            ast::TyKind::UnsafeBinder(ref binder) => {
1021                let mut result = String::new();
1022                if binder.generic_params.is_empty() {
1023                    // We always want to write `unsafe<>` since `unsafe<> Ty`
1024                    // and `Ty` are distinct types.
1025                    result.push_str("unsafe<> ")
1026                } else if let Some(ref lifetime_str) =
1027                    rewrite_bound_params(context, shape, &binder.generic_params)
1028                {
1029                    result.push_str("unsafe<");
1030                    result.push_str(lifetime_str);
1031                    result.push_str("> ");
1032                }
1033
1034                let inner_ty_shape = if context.use_block_indent() {
1035                    shape.offset_left(result.len(), self.span())?
1036                } else {
1037                    shape
1038                        .visual_indent(result.len())
1039                        .sub_width(result.len(), self.span())?
1040                };
1041
1042                let rewrite = binder.inner_ty.rewrite_result(context, inner_ty_shape)?;
1043                result.push_str(&rewrite);
1044                Ok(result)
1045            }
1046            ast::TyKind::Pat(..) | ast::TyKind::View(..) | ast::TyKind::GcaMacro(..) => {
1047                // These don't normally occur in the AST because macros aren't expanded. However,
1048                // rustfmt tries to parse macro arguments when formatting macros, so it's not
1049                // totally impossible for rustfmt to come across these nodes when formatting a file.
1050                // Also, rustfmt might get passed the output from `-Zunpretty=expanded`.
1051                Err(RewriteError::Unknown)
1052            }
1053            ast::TyKind::Dummy | ast::TyKind::Err(_) => Ok(context.snippet(self.span).to_owned()),
1054        }
1055    }
1056}
1057
1058impl Rewrite for ast::TyPat {
1059    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1060        self.rewrite_result(context, shape).ok()
1061    }
1062
1063    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1064        match self.kind {
1065            ast::TyPatKind::Range(ref lhs, ref rhs, ref end_kind) => rewrite_range(
1066                context,
1067                shape,
1068                lhs.as_deref().map(|x| x.value.as_ref()),
1069                rhs.as_deref().map(|x| x.value.as_ref()),
1070                format_range_end(end_kind.node),
1071            ),
1072            ast::TyPatKind::Or(ref variants) => {
1073                let mut first = true;
1074                let mut s = String::new();
1075                for variant in variants {
1076                    if first {
1077                        first = false
1078                    } else {
1079                        s.push_str(" | ");
1080                    }
1081                    s.push_str(&variant.rewrite_result(context, shape)?);
1082                }
1083                Ok(s)
1084            }
1085            ast::TyPatKind::NotNull | ast::TyPatKind::Err(_) => Err(RewriteError::Unknown),
1086        }
1087    }
1088}
1089
1090fn rewrite_fn_ptr(
1091    fn_ptr: &ast::FnPtrTy,
1092    span: Span,
1093    context: &RewriteContext<'_>,
1094    shape: Shape,
1095) -> RewriteResult {
1096    debug!("rewrite_bare_fn {:#?}", shape);
1097
1098    let mut result = String::with_capacity(128);
1099
1100    if let Some(ref lifetime_str) = rewrite_bound_params(context, shape, &fn_ptr.generic_params) {
1101        result.push_str("for<");
1102        // 6 = "for<> ".len(), 4 = "for<".
1103        // This doesn't work out so nicely for multiline situation with lots of
1104        // rightward drift. If that is a problem, we could use the list stuff.
1105        result.push_str(lifetime_str);
1106        result.push_str("> ");
1107    }
1108
1109    result.push_str(crate::utils::format_safety(fn_ptr.safety));
1110
1111    result.push_str(&format_extern(
1112        fn_ptr.ext,
1113        context.config.force_explicit_abi(),
1114    ));
1115
1116    result.push_str("fn");
1117
1118    let func_ty_shape = if context.use_block_indent() {
1119        shape.offset_left(result.len(), span)?
1120    } else {
1121        shape
1122            .visual_indent(result.len())
1123            .sub_width(result.len(), span)?
1124    };
1125
1126    let rewrite = format_function_type(
1127        &fn_ptr.decl.inputs,
1128        &fn_ptr.decl.output,
1129        fn_ptr.decl.c_variadic(),
1130        fn_ptr.decl_span,
1131        context,
1132        func_ty_shape,
1133    )?;
1134
1135    result.push_str(&rewrite);
1136
1137    Ok(result)
1138}
1139
1140fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
1141    let is_trait = |b: &ast::GenericBound| match b {
1142        ast::GenericBound::Outlives(..) => false,
1143        ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => true,
1144    };
1145    let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
1146    let last_trait_index = generic_bounds.iter().rposition(is_trait);
1147    let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
1148    match (last_trait_index, first_lifetime_index) {
1149        (Some(last_trait_index), Some(first_lifetime_index)) => {
1150            last_trait_index < first_lifetime_index
1151        }
1152        _ => true,
1153    }
1154}
1155
1156fn join_bounds(
1157    context: &RewriteContext<'_>,
1158    shape: Shape,
1159    items: &[ast::GenericBound],
1160    need_indent: bool,
1161) -> RewriteResult {
1162    join_bounds_inner(context, shape, items, need_indent, false)
1163}
1164
1165fn join_bounds_inner(
1166    context: &RewriteContext<'_>,
1167    shape: Shape,
1168    items: &[ast::GenericBound],
1169    need_indent: bool,
1170    force_newline: bool,
1171) -> RewriteResult {
1172    debug_assert!(!items.is_empty());
1173
1174    let generic_bounds_in_order = is_generic_bounds_in_order(items);
1175    let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
1176        ast::GenericBound::Outlives(..) => true,
1177        // We treat `use<>` like a trait bound here.
1178        ast::GenericBound::Trait(..) | ast::GenericBound::Use(..) => last_line_extendable(s),
1179    };
1180
1181    // Whether a GenericBound item is a PathSegment segment that includes internal array
1182    // that contains more than one item
1183    let is_item_with_multi_items_array = |item: &ast::GenericBound| match item {
1184        ast::GenericBound::Trait(ref poly_trait_ref, ..) => {
1185            let segments = &poly_trait_ref.trait_ref.path.segments;
1186            if segments.len() > 1 {
1187                true
1188            } else {
1189                if let Some(args_in) = &segments[0].args {
1190                    matches!(
1191                        args_in.deref(),
1192                        ast::GenericArgs::AngleBracketed(bracket_args)
1193                            if bracket_args.args.len() > 1
1194                    )
1195                } else {
1196                    false
1197                }
1198            }
1199        }
1200        ast::GenericBound::Use(args, _) => args.len() > 1,
1201        _ => false,
1202    };
1203
1204    let result = items.iter().enumerate().try_fold(
1205        (String::new(), None, false),
1206        |(strs, prev_trailing_span, prev_extendable), (i, item)| {
1207            let trailing_span = if i < items.len() - 1 {
1208                let hi = context
1209                    .snippet_provider
1210                    .span_before(mk_sp(items[i + 1].span().lo(), item.span().hi()), "+");
1211
1212                Some(mk_sp(item.span().hi(), hi))
1213            } else {
1214                None
1215            };
1216            let (leading_span, has_leading_comment) = if i > 0 {
1217                let lo = context
1218                    .snippet_provider
1219                    .span_after(mk_sp(items[i - 1].span().hi(), item.span().lo()), "+");
1220
1221                let span = mk_sp(lo, item.span().lo());
1222
1223                let has_comments = contains_comment(context.snippet(span));
1224
1225                (Some(mk_sp(lo, item.span().lo())), has_comments)
1226            } else {
1227                (None, false)
1228            };
1229            let prev_has_trailing_comment = match prev_trailing_span {
1230                Some(ts) => contains_comment(context.snippet(ts)),
1231                _ => false,
1232            };
1233
1234            let shape = if need_indent && force_newline {
1235                shape
1236                    .block_indent(context.config.tab_spaces())
1237                    .with_max_width(context.config)
1238            } else {
1239                shape
1240            };
1241            let whitespace = if force_newline && (!prev_extendable || !generic_bounds_in_order) {
1242                shape
1243                    .indent
1244                    .to_string_with_newline(context.config)
1245                    .to_string()
1246            } else {
1247                String::from(" ")
1248            };
1249
1250            let joiner = match context.config.type_punctuation_density() {
1251                TypeDensity::Compressed => String::from("+"),
1252                TypeDensity::Wide => whitespace + "+ ",
1253            };
1254            let joiner = if has_leading_comment {
1255                joiner.trim_end()
1256            } else {
1257                &joiner
1258            };
1259            let joiner = if prev_has_trailing_comment {
1260                joiner.trim_start()
1261            } else {
1262                joiner
1263            };
1264
1265            let (extendable, trailing_str) = if i == 0 {
1266                let bound_str = item.rewrite_result(context, shape)?;
1267                (is_bound_extendable(&bound_str, item), bound_str)
1268            } else {
1269                let bound_str = &item.rewrite_result(context, shape)?;
1270                match leading_span {
1271                    Some(ls) if has_leading_comment => (
1272                        is_bound_extendable(bound_str, item),
1273                        combine_strs_with_missing_comments(
1274                            context, joiner, bound_str, ls, shape, true,
1275                        )?,
1276                    ),
1277                    _ => (
1278                        is_bound_extendable(bound_str, item),
1279                        String::from(joiner) + bound_str,
1280                    ),
1281                }
1282            };
1283            match prev_trailing_span {
1284                Some(ts) if prev_has_trailing_comment => combine_strs_with_missing_comments(
1285                    context,
1286                    &strs,
1287                    &trailing_str,
1288                    ts,
1289                    shape,
1290                    true,
1291                )
1292                .map(|v| (v, trailing_span, extendable)),
1293                _ => Ok((strs + &trailing_str, trailing_span, extendable)),
1294            }
1295        },
1296    )?;
1297
1298    // Whether to retry with a forced newline:
1299    //   Only if result is not already multiline and did not exceed line width,
1300    //   and either there is more than one item;
1301    //       or the single item is of type `Trait`,
1302    //          and any of the internal arrays contains more than one item;
1303    let retry_with_force_newline = match context.config.style_edition() {
1304        style_edition @ _ if style_edition <= StyleEdition::Edition2021 => {
1305            !force_newline
1306                && items.len() > 1
1307                && (result.0.contains('\n') || result.0.len() > shape.width)
1308        }
1309        _ if force_newline => false,
1310        _ if (!result.0.contains('\n') && result.0.len() <= shape.width) => false,
1311        _ if items.len() > 1 => true,
1312        _ => is_item_with_multi_items_array(&items[0]),
1313    };
1314
1315    if retry_with_force_newline {
1316        join_bounds_inner(context, shape, items, need_indent, true)
1317    } else {
1318        Ok(result.0)
1319    }
1320}
1321
1322pub(crate) fn opaque_ty(ty: &Option<Box<ast::Ty>>) -> Option<&ast::GenericBounds> {
1323    ty.as_ref().and_then(|t| match &t.kind {
1324        ast::TyKind::ImplTrait(_, bounds) => Some(bounds),
1325        _ => None,
1326    })
1327}
1328
1329pub(crate) fn can_be_overflowed_type(
1330    context: &RewriteContext<'_>,
1331    ty: &ast::Ty,
1332    len: usize,
1333) -> bool {
1334    match ty.kind {
1335        ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
1336        ast::TyKind::Ref(_, ref mutty)
1337        | ast::TyKind::PinnedRef(_, ref mutty)
1338        | ast::TyKind::Ptr(ref mutty) => can_be_overflowed_type(context, &*mutty.ty, len),
1339        _ => false,
1340    }
1341}
1342
1343/// Returns `None` if there is no `GenericParam` in the list
1344pub(crate) fn rewrite_bound_params(
1345    context: &RewriteContext<'_>,
1346    shape: Shape,
1347    generic_params: &[ast::GenericParam],
1348) -> Option<String> {
1349    let result = generic_params
1350        .iter()
1351        .map(|param| param.rewrite(context, shape))
1352        .collect::<Option<Vec<_>>>()?
1353        .join(", ");
1354    if result.is_empty() {
1355        None
1356    } else {
1357        Some(result)
1358    }
1359}