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