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