rustfmt_nightly/
types.rs

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