Skip to main content

rustfmt_nightly/
items.rs

1// Formatting top-level items - functions, structs, enums, traits, impls.
2
3use std::borrow::Cow;
4use std::cmp::{Ordering, max, min};
5
6use regex::Regex;
7use rustc_ast::ast;
8use rustc_ast::visit;
9use rustc_span::{BytePos, DUMMY_SP, Ident, Span, symbol};
10use tracing::debug;
11
12use crate::attr::filter_inline_attrs;
13use crate::comment::{
14    FindUncommented, combine_strs_with_missing_comments, contains_comment, is_last_comment_block,
15    recover_comment_removed, recover_missing_comment_in_span, rewrite_missing_comment,
16};
17use crate::config::lists::*;
18use crate::config::{BraceStyle, Config, IndentStyle, StyleEdition};
19use crate::expr::{
20    RhsAssignKind, RhsTactics, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
21    rewrite_assign_rhs_with, rewrite_assign_rhs_with_comments, rewrite_else_kw_with_comments,
22    rewrite_let_else_block,
23};
24use crate::lists::{ListFormatting, Separator, definitive_tactic, itemize_list, write_list};
25use crate::macros::{MacroPosition, rewrite_macro};
26use crate::overflow;
27use crate::rewrite::{
28    ExceedsMaxWidthError, Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult,
29};
30use crate::shape::{Indent, Shape};
31use crate::source_map::{LineRangeUtils, SpanUtils};
32use crate::spanned::Spanned;
33use crate::stmt::Stmt;
34use crate::types::opaque_ty;
35use crate::utils::*;
36use crate::vertical::rewrite_with_alignment;
37use crate::visitor::FmtVisitor;
38
39const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
40    kind: ast::VisibilityKind::Inherited,
41    span: DUMMY_SP,
42};
43
44fn type_annotation_separator(config: &Config) -> &str {
45    colon_spaces(config)
46}
47
48// Statements of the form
49// let pat: ty = init; or let pat: ty = init else { .. };
50impl Rewrite for ast::Local {
51    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
52        self.rewrite_result(context, shape).ok()
53    }
54
55    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
56        debug!(
57            "Local::rewrite {:?} {} {:?}",
58            self, shape.width, shape.indent
59        );
60
61        skip_out_of_file_lines_range_err!(context, self.span);
62
63        if contains_skip(&self.attrs) {
64            return Err(RewriteError::SkipFormatting);
65        }
66
67        let super_ = self.super_.is_some();
68        // FIXME: deletes any comments in between super and let
69        let let_ = if super_ { "super let " } else { "let " };
70        let attrs_str = self.attrs.rewrite_result(context, shape)?;
71        let mut result = if attrs_str.is_empty() {
72            let_.to_owned()
73        } else {
74            combine_strs_with_missing_comments(
75                context,
76                &attrs_str,
77                let_,
78                mk_sp(
79                    self.attrs.last().map(|a| a.span.hi()).unwrap(),
80                    self.span.lo(),
81                ),
82                shape,
83                false,
84            )?
85        };
86        let let_kw_offset = result.len() - let_.len();
87
88        let pat_shape = shape.offset_left(let_.len(), self.span())?;
89        // 1 = ;
90        let pat_shape = pat_shape.sub_width(1, self.span())?;
91        let pat_str = self.pat.rewrite_result(context, pat_shape)?;
92
93        result.push_str(&pat_str);
94
95        // String that is placed within the assignment pattern and expression.
96        let infix = {
97            let mut infix = String::with_capacity(32);
98
99            if let Some(ref ty) = self.ty {
100                let separator = type_annotation_separator(context.config);
101                let ty_shape = if pat_str.contains('\n') {
102                    shape.with_max_width(context.config)
103                } else {
104                    shape
105                }
106                .offset_left(last_line_width(&result) + separator.len(), self.span())?
107                // 2 = ` =`
108                .sub_width(2, self.span())?;
109
110                let rewrite = ty.rewrite_result(context, ty_shape)?;
111
112                infix.push_str(separator);
113                infix.push_str(&rewrite);
114            }
115
116            if self.kind.init().is_some() {
117                infix.push_str(" =");
118            }
119
120            infix
121        };
122
123        result.push_str(&infix);
124
125        if let Some((init, else_block)) = self.kind.init_else_opt() {
126            // 1 = trailing semicolon;
127            let nested_shape = shape.sub_width(1, self.span())?;
128
129            result = rewrite_assign_rhs(
130                context,
131                result,
132                init,
133                &RhsAssignKind::Expr(&init.kind, init.span),
134                nested_shape,
135            )?;
136
137            if let Some(block) = else_block {
138                let else_kw_span = init.span.between(block.span);
139                // Strip attributes and comments to check if newline is needed before the else
140                // keyword from the initializer part. (#5901)
141                let style_edition = context.config.style_edition();
142                let init_str = if style_edition >= StyleEdition::Edition2024 {
143                    &result[let_kw_offset..]
144                } else {
145                    result.as_str()
146                };
147                let force_newline_else = pat_str.contains('\n')
148                    || !same_line_else_kw_and_brace(init_str, context, else_kw_span, nested_shape);
149                let else_kw = rewrite_else_kw_with_comments(
150                    force_newline_else,
151                    true,
152                    context,
153                    else_kw_span,
154                    shape,
155                );
156                result.push_str(&else_kw);
157
158                // At this point we've written `let {pat} = {expr} else' into the buffer, and we
159                // want to calculate up front if there's room to write the divergent block on the
160                // same line. The available space varies based on indentation so we clamp the width
161                // on the smaller of `shape.width` and `single_line_let_else_max_width`.
162                let max_width =
163                    std::cmp::min(shape.width, context.config.single_line_let_else_max_width());
164
165                // If available_space hits zero we know for sure this will be a multi-lined block
166                let style_edition = context.config.style_edition();
167                let assign_str_with_else_kw = if style_edition >= StyleEdition::Edition2024 {
168                    &result[let_kw_offset..]
169                } else {
170                    result.as_str()
171                };
172                let available_space = max_width.saturating_sub(assign_str_with_else_kw.len());
173
174                let allow_single_line = !force_newline_else
175                    && available_space > 0
176                    && allow_single_line_let_else_block(assign_str_with_else_kw, block);
177
178                let mut rw_else_block =
179                    rewrite_let_else_block(block, allow_single_line, context, shape)?;
180
181                let single_line_else = !rw_else_block.contains('\n');
182                // +1 for the trailing `;`
183                let else_block_exceeds_width = rw_else_block.len() + 1 > available_space;
184
185                if allow_single_line && single_line_else && else_block_exceeds_width {
186                    // writing this on one line would exceed the available width
187                    // so rewrite the else block over multiple lines.
188                    rw_else_block = rewrite_let_else_block(block, false, context, shape)?;
189                }
190
191                result.push_str(&rw_else_block);
192            };
193        }
194
195        result.push(';');
196        Ok(result)
197    }
198}
199
200/// When the initializer expression is multi-lined, then the else keyword and opening brace of the
201/// block ( i.e. "else {") should be put on the same line as the end of the initializer expression
202/// if all the following are true:
203///
204/// 1. The initializer expression ends with one or more closing parentheses, square brackets,
205///    or braces
206/// 2. There is nothing else on that line
207/// 3. That line is not indented beyond the indent on the first line of the let keyword
208fn same_line_else_kw_and_brace(
209    init_str: &str,
210    context: &RewriteContext<'_>,
211    else_kw_span: Span,
212    init_shape: Shape,
213) -> bool {
214    if !init_str.contains('\n') {
215        // initializer expression is single lined. The "else {" can only be placed on the same line
216        // as the initializer expression if there is enough room for it.
217        // 7 = ` else {`
218        return init_shape.width.saturating_sub(init_str.len()) >= 7;
219    }
220
221    // 1. The initializer expression ends with one or more `)`, `]`, `}`.
222    if !init_str.ends_with([')', ']', '}']) {
223        return false;
224    }
225
226    // 2. There is nothing else on that line
227    // For example, there are no comments
228    let else_kw_snippet = context.snippet(else_kw_span).trim();
229    if else_kw_snippet != "else" {
230        return false;
231    }
232
233    // 3. The last line of the initializer expression is not indented beyond the `let` keyword
234    let indent = init_shape.indent.to_string(context.config);
235    init_str
236        .lines()
237        .last()
238        .expect("initializer expression is multi-lined")
239        .strip_prefix(indent.as_ref())
240        .map_or(false, |l| !l.starts_with(char::is_whitespace))
241}
242
243fn allow_single_line_let_else_block(result: &str, block: &ast::Block) -> bool {
244    if result.contains('\n') {
245        return false;
246    }
247
248    if block.stmts.len() <= 1 {
249        return true;
250    }
251
252    false
253}
254
255// FIXME convert to using rewrite style rather than visitor
256// FIXME format modules in this style
257#[allow(dead_code)]
258#[derive(Debug)]
259struct Item<'a> {
260    safety: ast::Safety,
261    abi: Cow<'static, str>,
262    vis: Option<&'a ast::Visibility>,
263    body: Vec<BodyElement<'a>>,
264    span: Span,
265}
266
267impl<'a> Item<'a> {
268    fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
269        Item {
270            safety: fm.safety,
271            abi: format_extern(
272                ast::Extern::from_abi(fm.abi, DUMMY_SP),
273                config.force_explicit_abi(),
274            ),
275            vis: None,
276            body: fm
277                .items
278                .iter()
279                .map(|i| BodyElement::ForeignItem(i))
280                .collect(),
281            span,
282        }
283    }
284}
285
286#[derive(Debug)]
287enum BodyElement<'a> {
288    // Stmt(&'a ast::Stmt),
289    // Field(&'a ast::ExprField),
290    // Variant(&'a ast::Variant),
291    // Item(&'a ast::Item),
292    ForeignItem(&'a ast::ForeignItem),
293}
294
295/// Represents a fn's signature.
296pub(crate) struct FnSig<'a> {
297    decl: &'a ast::FnDecl,
298    generics: &'a ast::Generics,
299    ext: ast::Extern,
300    coroutine_marker: &'a Option<ast::CoroutineMarker>,
301    constness: ast::Const,
302    defaultness: ast::Defaultness,
303    safety: ast::Safety,
304    visibility: &'a ast::Visibility,
305}
306
307impl<'a> FnSig<'a> {
308    pub(crate) fn from_method_sig(
309        method_sig: &'a ast::FnSig,
310        generics: &'a ast::Generics,
311        visibility: &'a ast::Visibility,
312        defaultness: ast::Defaultness,
313    ) -> FnSig<'a> {
314        FnSig {
315            safety: method_sig.header.safety,
316            coroutine_marker: &method_sig.header.coroutine_marker,
317            constness: method_sig.header.constness,
318            defaultness,
319            ext: method_sig.header.ext,
320            decl: &*method_sig.decl,
321            generics,
322            visibility,
323        }
324    }
325
326    pub(crate) fn from_fn_kind(
327        fn_kind: &'a visit::FnKind<'_>,
328        decl: &'a ast::FnDecl,
329        defaultness: ast::Defaultness,
330    ) -> FnSig<'a> {
331        match *fn_kind {
332            visit::FnKind::Fn(visit::FnCtxt::Assoc(..), vis, ast::Fn { sig, generics, .. }) => {
333                FnSig::from_method_sig(sig, generics, vis, defaultness)
334            }
335            visit::FnKind::Fn(_, vis, ast::Fn { sig, generics, .. }) => FnSig {
336                decl,
337                generics,
338                ext: sig.header.ext,
339                constness: sig.header.constness,
340                coroutine_marker: &sig.header.coroutine_marker,
341                defaultness,
342                safety: sig.header.safety,
343                visibility: vis,
344            },
345            _ => unreachable!(),
346        }
347    }
348
349    fn to_str(&self, context: &RewriteContext<'_>) -> String {
350        let mut result = String::with_capacity(128);
351        // Vis defaultness constness unsafety abi.
352        result.push_str(&*format_visibility(context, self.visibility));
353        result.push_str(format_defaultness(self.defaultness));
354        result.push_str(format_constness(self.constness));
355        self.coroutine_marker
356            .map(|coroutine_marker| result.push_str(format_coro(coroutine_marker)));
357        result.push_str(format_safety(self.safety));
358        result.push_str(&format_extern(
359            self.ext,
360            context.config.force_explicit_abi(),
361        ));
362        result
363    }
364}
365
366impl<'a> FmtVisitor<'a> {
367    fn format_item(&mut self, item: &Item<'_>) {
368        self.buffer.push_str(format_safety(item.safety));
369        self.buffer.push_str(&item.abi);
370
371        let snippet = self.snippet(item.span);
372        let brace_pos = snippet.find_uncommented("{").unwrap();
373
374        self.push_str("{");
375        if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
376            // FIXME: this skips comments between the extern keyword and the opening
377            // brace.
378            self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
379            self.block_indent = self.block_indent.block_indent(self.config);
380
381            if !item.body.is_empty() {
382                for item in &item.body {
383                    self.format_body_element(item);
384                }
385            }
386
387            self.format_missing_no_indent(item.span.hi() - BytePos(1));
388            self.block_indent = self.block_indent.block_unindent(self.config);
389            let indent_str = self.block_indent.to_string(self.config);
390            self.push_str(&indent_str);
391        }
392
393        self.push_str("}");
394        self.last_pos = item.span.hi();
395    }
396
397    fn format_body_element(&mut self, element: &BodyElement<'_>) {
398        match *element {
399            BodyElement::ForeignItem(item) => self.format_foreign_item(item),
400        }
401    }
402
403    pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
404        let item = Item::from_foreign_mod(fm, span, self.config);
405        self.format_item(&item);
406    }
407
408    fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
409        let rewrite = item.rewrite(&self.get_context(), self.shape());
410        let hi = item.span.hi();
411        let span = if item.attrs.is_empty() {
412            item.span
413        } else {
414            mk_sp(item.attrs[0].span.lo(), hi)
415        };
416        self.push_rewrite(span, rewrite);
417        self.last_pos = hi;
418    }
419
420    pub(crate) fn rewrite_fn_before_block(
421        &mut self,
422        indent: Indent,
423        ident: symbol::Ident,
424        fn_sig: &FnSig<'_>,
425        span: Span,
426    ) -> Option<(String, FnBraceStyle)> {
427        let context = self.get_context();
428
429        let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
430        let (result, _, force_newline_brace) =
431            rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style).ok()?;
432
433        // 2 = ` {`
434        if self.config.brace_style() == BraceStyle::AlwaysNextLine
435            || force_newline_brace
436            || last_line_width(&result) + 2 > self.shape().width
437        {
438            fn_brace_style = FnBraceStyle::NextLine
439        }
440
441        Some((result, fn_brace_style))
442    }
443
444    pub(crate) fn rewrite_required_fn(
445        &mut self,
446        indent: Indent,
447        ident: symbol::Ident,
448        sig: &ast::FnSig,
449        vis: &ast::Visibility,
450        generics: &ast::Generics,
451        defaultness: ast::Defaultness,
452        span: Span,
453    ) -> RewriteResult {
454        // Drop semicolon or it will be interpreted as comment.
455        let span = mk_sp(span.lo(), span.hi() - BytePos(1));
456        let context = self.get_context();
457
458        let (mut result, ends_with_comment, _) = rewrite_fn_base(
459            &context,
460            indent,
461            ident,
462            &FnSig::from_method_sig(sig, generics, vis, defaultness),
463            span,
464            FnBraceStyle::None,
465        )?;
466
467        // If `result` ends with a comment, then remember to add a newline
468        if ends_with_comment {
469            result.push_str(&indent.to_string_with_newline(context.config));
470        }
471
472        // Re-attach semicolon
473        result.push(';');
474
475        Ok(result)
476    }
477
478    pub(crate) fn single_line_fn(
479        &self,
480        fn_str: &str,
481        block: &ast::Block,
482        inner_attrs: Option<&[ast::Attribute]>,
483    ) -> Option<String> {
484        if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
485            return None;
486        }
487
488        let context = self.get_context();
489
490        if self.config.empty_item_single_line()
491            && is_empty_block(&context, block, None)
492            && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
493            && !last_line_contains_single_line_comment(fn_str)
494        {
495            return Some(format!("{fn_str} {{}}"));
496        }
497
498        if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
499            return None;
500        }
501
502        let res = Stmt::from_ast_node(block.stmts.first()?, true)
503            .rewrite(&self.get_context(), self.shape())?;
504
505        let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
506        if !res.contains('\n') && width <= self.config.max_width() {
507            Some(format!("{fn_str} {{ {res} }}"))
508        } else {
509            None
510        }
511    }
512
513    pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
514        let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
515        self.push_rewrite(static_parts.span, rewrite);
516    }
517
518    pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
519        let is_tuple = match struct_parts.def {
520            ast::VariantData::Tuple(..) => true,
521            _ => false,
522        };
523        let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
524            .map(|s| if is_tuple { s + ";" } else { s });
525        self.push_rewrite(struct_parts.span, rewrite);
526    }
527
528    pub(crate) fn visit_enum(
529        &mut self,
530        ident: symbol::Ident,
531        vis: &ast::Visibility,
532        enum_def: &ast::EnumDef,
533        generics: &ast::Generics,
534        span: Span,
535    ) {
536        let enum_header =
537            format_header(&self.get_context(), "enum ", ident, vis, self.block_indent);
538        self.push_str(&enum_header);
539
540        let enum_snippet = self.snippet(span);
541        let brace_pos = enum_snippet.find_uncommented("{").unwrap();
542        let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
543        let generics_str = format_generics(
544            &self.get_context(),
545            generics,
546            self.config.brace_style(),
547            if enum_def.variants.is_empty() {
548                BracePos::ForceSameLine
549            } else {
550                BracePos::Auto
551            },
552            self.block_indent,
553            // make a span that starts right after `enum Foo`
554            mk_sp(ident.span.hi(), body_start),
555            last_line_width(&enum_header),
556        )
557        .unwrap();
558        self.push_str(&generics_str);
559
560        self.last_pos = body_start;
561
562        match self.format_variant_list(enum_def, body_start, span.hi()) {
563            Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
564            rw => {
565                self.push_rewrite(mk_sp(body_start, span.hi()), rw);
566                self.block_indent = self.block_indent.block_unindent(self.config);
567            }
568        }
569    }
570
571    // Format the body of an enum definition
572    fn format_variant_list(
573        &mut self,
574        enum_def: &ast::EnumDef,
575        body_lo: BytePos,
576        body_hi: BytePos,
577    ) -> Option<String> {
578        if enum_def.variants.is_empty() {
579            let mut buffer = String::with_capacity(128);
580            // 1 = "}"
581            let span = mk_sp(body_lo, body_hi - BytePos(1));
582            format_empty_struct_or_tuple(
583                &self.get_context(),
584                span,
585                self.block_indent,
586                &mut buffer,
587                "",
588                "}",
589            );
590            return Some(buffer);
591        }
592        let mut result = String::with_capacity(1024);
593        let original_offset = self.block_indent;
594        self.block_indent = self.block_indent.block_indent(self.config);
595
596        // If enum variants have discriminants, try to vertically align those,
597        // provided the discrims are not shifted too much  to the right
598        let align_threshold: usize = self.config.enum_discrim_align_threshold();
599        let discr_ident_lens: Vec<usize> = enum_def
600            .variants
601            .iter()
602            .filter(|var| var.disr_expr.is_some())
603            .map(|var| rewrite_ident(&self.get_context(), var.ident).len())
604            .collect();
605        // cut the list at the point of longest discrim shorter than the threshold
606        // All of the discrims under the threshold will get padded, and all above - left as is.
607        let pad_discrim_ident_to = *discr_ident_lens
608            .iter()
609            .filter(|&l| *l <= align_threshold)
610            .max()
611            .unwrap_or(&0);
612
613        let itemize_list_with = |one_line_width: usize| {
614            itemize_list(
615                self.snippet_provider,
616                enum_def.variants.iter(),
617                "}",
618                ",",
619                |f| {
620                    if !f.attrs.is_empty() {
621                        f.attrs[0].span.lo()
622                    } else {
623                        f.span.lo()
624                    }
625                },
626                |f| f.span.hi(),
627                |f| {
628                    self.format_variant(f, one_line_width, pad_discrim_ident_to)
629                        .unknown_error()
630                },
631                body_lo,
632                body_hi,
633                false,
634            )
635            .collect()
636        };
637        let mut items: Vec<_> = itemize_list_with(self.config.struct_variant_width());
638
639        // If one of the variants use multiple lines, use multi-lined formatting for all variants.
640        let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
641        let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
642        if has_multiline_variant && has_single_line_variant {
643            items = itemize_list_with(0);
644        }
645
646        let shape = self.shape().sub_width_opt(2)?;
647        let fmt = ListFormatting::new(shape, self.config)
648            .trailing_separator(self.config.trailing_comma())
649            .preserve_newline(true);
650
651        let list = write_list(&items, &fmt).ok()?;
652        result.push_str(&list);
653        result.push_str(&original_offset.to_string_with_newline(self.config));
654        result.push('}');
655        Some(result)
656    }
657
658    // Variant of an enum.
659    fn format_variant(
660        &self,
661        field: &ast::Variant,
662        one_line_width: usize,
663        pad_discrim_ident_to: usize,
664    ) -> Option<String> {
665        if contains_skip(&field.attrs) {
666            let lo = field.attrs[0].span.lo();
667            let span = mk_sp(lo, field.span.hi());
668            return Some(self.snippet(span).to_owned());
669        }
670
671        let context = self.get_context();
672        let shape = self.shape();
673        let attrs_str = if context.config.style_edition() >= StyleEdition::Edition2024 {
674            field.attrs.rewrite(&context, shape)?
675        } else {
676            // StyleEdition::Edition20{15|18|21} formatting that was off by 1. See issue #5801
677            field.attrs.rewrite(&context, shape.sub_width_opt(1)?)?
678        };
679        // sub_width(1) to take the trailing comma into account
680        let shape = shape.sub_width_opt(1)?;
681
682        let lo = field
683            .attrs
684            .last()
685            .map_or(field.span.lo(), |attr| attr.span.hi());
686        let span = mk_sp(lo, field.span.lo());
687
688        let variant_body = match field.data {
689            ast::VariantData::Tuple(..) | ast::VariantData::Struct { .. } => format_struct(
690                &context,
691                &StructParts::from_variant(field, &context),
692                self.block_indent,
693                Some(one_line_width),
694            )?,
695            ast::VariantData::Unit(..) => rewrite_ident(&context, field.ident).to_owned(),
696        };
697
698        let variant_body = if let Some(ref expr) = field.disr_expr {
699            let lhs = format!("{variant_body:pad_discrim_ident_to$} =");
700            let ex = &*expr.value;
701            rewrite_assign_rhs_with(
702                &context,
703                lhs,
704                ex,
705                shape,
706                &RhsAssignKind::Expr(&ex.kind, ex.span),
707                RhsTactics::AllowOverflow,
708            )
709            .ok()?
710        } else {
711            variant_body
712        };
713
714        combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
715            .ok()
716    }
717
718    fn visit_impl_items(&mut self, items: &[Box<ast::AssocItem>]) {
719        if self.get_context().config.reorder_impl_items() {
720            type TyOpt = Option<Box<ast::Ty>>;
721            use crate::ast::AssocItemKind::*;
722            let is_type = |ty: &TyOpt| opaque_ty(ty).is_none();
723            let is_opaque = |ty: &TyOpt| opaque_ty(ty).is_some();
724            let both_type = |l: &TyOpt, r: &TyOpt| is_type(l) && is_type(r);
725            let both_opaque = |l: &TyOpt, r: &TyOpt| is_opaque(l) && is_opaque(r);
726            let need_empty_line = |a: &ast::AssocItemKind, b: &ast::AssocItemKind| match (a, b) {
727                (Type(lty), Type(rty))
728                    if both_type(&lty.ty, &rty.ty) || both_opaque(&lty.ty, &rty.ty) =>
729                {
730                    false
731                }
732                (Const(..), Const(..)) => false,
733                _ => true,
734            };
735
736            // Create visitor for each items, then reorder them.
737            let mut buffer = vec![];
738            for item in items {
739                self.visit_impl_item(item);
740                buffer.push((self.buffer.clone(), item.clone()));
741                self.buffer.clear();
742            }
743
744            buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
745                (Type(lty), Type(rty))
746                    if both_type(&lty.ty, &rty.ty) || both_opaque(&lty.ty, &rty.ty) =>
747                {
748                    lty.ident.as_str().cmp(rty.ident.as_str())
749                }
750                (Const(ca), Const(cb)) => ca.ident.as_str().cmp(cb.ident.as_str()),
751                (MacCall(..), MacCall(..)) => Ordering::Equal,
752                (Fn(..), Fn(..)) | (Delegation(..), Delegation(..)) => {
753                    a.span.lo().cmp(&b.span.lo())
754                }
755                (Type(ty), _) if is_type(&ty.ty) => Ordering::Less,
756                (_, Type(ty)) if is_type(&ty.ty) => Ordering::Greater,
757                (Type(..), _) => Ordering::Less,
758                (_, Type(..)) => Ordering::Greater,
759                (Const(..), _) => Ordering::Less,
760                (_, Const(..)) => Ordering::Greater,
761                (MacCall(..), _) => Ordering::Less,
762                (_, MacCall(..)) => Ordering::Greater,
763                (Delegation(..), _) | (DelegationMac(..), _) => Ordering::Less,
764                (_, Delegation(..)) | (_, DelegationMac(..)) => Ordering::Greater,
765            });
766            let mut prev_kind = None;
767            for (buf, item) in buffer {
768                // Make sure that there are at least a single empty line between
769                // different impl items.
770                if prev_kind
771                    .as_ref()
772                    .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind))
773                {
774                    self.push_str("\n");
775                }
776                let indent_str = self.block_indent.to_string_with_newline(self.config);
777                self.push_str(&indent_str);
778                self.push_str(buf.trim());
779                prev_kind = Some(item.kind.clone());
780            }
781        } else {
782            for item in items {
783                self.visit_impl_item(item);
784            }
785        }
786    }
787}
788
789pub(crate) fn format_impl(
790    context: &RewriteContext<'_>,
791    item: &ast::Item,
792    iimpl: &ast::Impl,
793    offset: Indent,
794) -> RewriteResult {
795    let ast::Impl {
796        generics,
797        self_ty,
798        items,
799        ..
800    } = iimpl;
801    let mut result = String::with_capacity(128);
802    let ref_and_type = format_impl_ref_and_type(context, item, iimpl, offset)?;
803    let sep = offset.to_string_with_newline(context.config);
804    result.push_str(&ref_and_type);
805
806    let where_budget = if result.contains('\n') {
807        context.config.max_width()
808    } else {
809        context.budget(last_line_width(&result))
810    };
811
812    let mut option = WhereClauseOption::snuggled(&ref_and_type);
813    let snippet = context.snippet(item.span);
814    let open_pos = snippet.find_uncommented("{").unknown_error()? + 1;
815    if !contains_comment(&snippet[open_pos..])
816        && items.is_empty()
817        && generics.where_clause.predicates.len() == 1
818        && !result.contains('\n')
819    {
820        option.suppress_comma();
821        option.snuggle();
822        option.allow_single_line();
823    }
824
825    let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
826    let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
827    let where_clause_str = rewrite_where_clause(
828        context,
829        &generics.where_clause,
830        context.config.brace_style(),
831        Shape::legacy(where_budget, offset.block_only()),
832        false,
833        "{",
834        where_span_end,
835        self_ty.span.hi(),
836        option,
837    )?;
838
839    // If there is no where-clause, we may have missing comments between the trait name and
840    // the opening brace.
841    if generics.where_clause.predicates.is_empty() {
842        if let Some(hi) = where_span_end {
843            match recover_missing_comment_in_span(
844                mk_sp(self_ty.span.hi(), hi),
845                Shape::indented(offset, context.config),
846                context,
847                last_line_width(&result),
848            ) {
849                Ok(ref missing_comment) if !missing_comment.is_empty() => {
850                    result.push_str(missing_comment);
851                }
852                _ => (),
853            }
854        }
855    }
856
857    if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
858        result.push_str(&where_clause_str);
859        if where_clause_str.contains('\n') {
860            // If there is only one where-clause predicate
861            // and the where-clause spans multiple lines,
862            // then recover the suppressed comma in single line where-clause formatting
863            if generics.where_clause.predicates.len() == 1 {
864                result.push(',');
865            }
866        }
867        if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
868            result.push_str(&format!("{sep}{{{sep}}}"));
869        } else {
870            result.push_str(" {}");
871        }
872        return Ok(result);
873    }
874
875    result.push_str(&where_clause_str);
876
877    let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
878    match context.config.brace_style() {
879        _ if need_newline => result.push_str(&sep),
880        BraceStyle::AlwaysNextLine => result.push_str(&sep),
881        BraceStyle::PreferSameLine => result.push(' '),
882        BraceStyle::SameLineWhere => {
883            if !where_clause_str.is_empty() {
884                result.push_str(&sep);
885            } else {
886                result.push(' ');
887            }
888        }
889    }
890
891    result.push('{');
892    // this is an impl body snippet(impl SampleImpl { /* here */ })
893    let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
894    let snippet = context.snippet(mk_sp(lo, item.span.hi()));
895    let open_pos = snippet.find_uncommented("{").unknown_error()? + 1;
896
897    if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
898        let mut visitor = FmtVisitor::from_context(context);
899        let item_indent = offset.block_only().block_indent(context.config);
900        visitor.block_indent = item_indent;
901        visitor.last_pos = lo + BytePos(open_pos as u32);
902
903        visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
904        visitor.visit_impl_items(items);
905
906        visitor.format_missing(item.span.hi() - BytePos(1));
907
908        let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
909        let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
910
911        result.push_str(&inner_indent_str);
912        result.push_str(visitor.buffer.trim());
913        result.push_str(&outer_indent_str);
914    } else if need_newline || !context.config.empty_item_single_line() {
915        result.push_str(&sep);
916    }
917
918    result.push('}');
919
920    Ok(result)
921}
922
923fn is_impl_single_line(
924    context: &RewriteContext<'_>,
925    items: &[Box<ast::AssocItem>],
926    result: &str,
927    where_clause_str: &str,
928    item: &ast::Item,
929) -> Result<bool, RewriteError> {
930    let snippet = context.snippet(item.span);
931    let open_pos = snippet.find_uncommented("{").unknown_error()? + 1;
932
933    Ok(context.config.empty_item_single_line()
934        && items.is_empty()
935        && !result.contains('\n')
936        && result.len() + where_clause_str.len() <= context.config.max_width()
937        && !contains_comment(&snippet[open_pos..]))
938}
939
940fn format_impl_ref_and_type(
941    context: &RewriteContext<'_>,
942    item: &ast::Item,
943    iimpl: &ast::Impl,
944    offset: Indent,
945) -> RewriteResult {
946    let ast::Impl {
947        generics,
948        of_trait,
949        self_ty,
950        items: _,
951        constness,
952    } = iimpl;
953    let mut result = String::with_capacity(128);
954
955    result.push_str(&format_visibility(context, &item.vis));
956
957    if let Some(of_trait) = of_trait.as_deref() {
958        result.push_str(format_defaultness(of_trait.defaultness));
959        result.push_str(format_constness(*constness));
960        result.push_str(format_safety(of_trait.safety));
961    } else {
962        result.push_str(format_constness(*constness));
963    }
964
965    let shape = if context.config.style_edition() >= StyleEdition::Edition2024 {
966        Shape::indented(offset + last_line_width(&result), context.config)
967    } else {
968        generics_shape_from_config(
969            context.config,
970            Shape::indented(offset + last_line_width(&result), context.config),
971            0,
972            item.span,
973        )?
974    };
975    let generics_str = rewrite_generics(context, "impl", generics, shape)?;
976    result.push_str(&generics_str);
977
978    let trait_ref_overhead;
979    if let Some(of_trait) = of_trait.as_deref() {
980        let polarity_str = match of_trait.polarity {
981            ast::ImplPolarity::Negative(_) => "!",
982            ast::ImplPolarity::Positive => "",
983        };
984        let result_len = last_line_width(&result);
985        result.push_str(&rewrite_trait_ref(
986            context,
987            &of_trait.trait_ref,
988            offset,
989            polarity_str,
990            result_len,
991        )?);
992        trait_ref_overhead = " for".len();
993    } else {
994        trait_ref_overhead = 0;
995    }
996
997    // Try to put the self type in a single line.
998    let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
999        // If there is no where-clause adapt budget for type formatting to take space and curly
1000        // brace into account.
1001        match context.config.brace_style() {
1002            BraceStyle::AlwaysNextLine => 0,
1003            _ => 2,
1004        }
1005    } else {
1006        0
1007    };
1008    let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
1009    // 1 = space before the type.
1010    let budget = context.budget(used_space + 1);
1011    if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
1012        if !self_ty_str.contains('\n') {
1013            if of_trait.is_some() {
1014                result.push_str(" for ");
1015            } else {
1016                result.push(' ');
1017            }
1018            result.push_str(&self_ty_str);
1019            return Ok(result);
1020        }
1021    }
1022
1023    // Couldn't fit the self type on a single line, put it on a new line.
1024    result.push('\n');
1025    // Add indentation of one additional tab.
1026    let new_line_offset = offset.block_indent(context.config);
1027    result.push_str(&new_line_offset.to_string(context.config));
1028    if of_trait.is_some() {
1029        result.push_str("for ");
1030    }
1031    let budget = context.budget(last_line_width(&result));
1032    let type_offset = match context.config.indent_style() {
1033        IndentStyle::Visual => new_line_offset + trait_ref_overhead,
1034        IndentStyle::Block => new_line_offset,
1035    };
1036    result.push_str(&*self_ty.rewrite_result(context, Shape::legacy(budget, type_offset))?);
1037    Ok(result)
1038}
1039
1040fn rewrite_trait_ref(
1041    context: &RewriteContext<'_>,
1042    trait_ref: &ast::TraitRef,
1043    offset: Indent,
1044    polarity_str: &str,
1045    result_len: usize,
1046) -> RewriteResult {
1047    // 1 = space between generics and trait_ref
1048    let used_space = 1 + polarity_str.len() + result_len;
1049    let shape = Shape::indented(offset + used_space, context.config);
1050    if let Ok(trait_ref_str) = trait_ref.rewrite_result(context, shape) {
1051        if !trait_ref_str.contains('\n') {
1052            return Ok(format!(" {polarity_str}{trait_ref_str}"));
1053        }
1054    }
1055    // We could not make enough space for trait_ref, so put it on new line.
1056    let offset = offset.block_indent(context.config);
1057    let shape = Shape::indented(offset, context.config);
1058    let trait_ref_str = trait_ref.rewrite_result(context, shape)?;
1059    Ok(format!(
1060        "{}{}{}",
1061        offset.to_string_with_newline(context.config),
1062        polarity_str,
1063        trait_ref_str
1064    ))
1065}
1066
1067pub(crate) struct StructParts<'a> {
1068    prefix: &'a str,
1069    ident: symbol::Ident,
1070    vis: &'a ast::Visibility,
1071    def: &'a ast::VariantData,
1072    generics: Option<&'a ast::Generics>,
1073    span: Span,
1074}
1075
1076impl<'a> StructParts<'a> {
1077    fn format_header(&self, context: &RewriteContext<'_>, offset: Indent) -> String {
1078        format_header(context, self.prefix, self.ident, self.vis, offset)
1079    }
1080
1081    fn from_variant(variant: &'a ast::Variant, context: &RewriteContext<'_>) -> Self {
1082        StructParts {
1083            prefix: "",
1084            ident: variant.ident,
1085            vis: &DEFAULT_VISIBILITY,
1086            def: &variant.data,
1087            generics: None,
1088            span: enum_variant_span(variant, context),
1089        }
1090    }
1091
1092    pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1093        let (prefix, def, ident, generics) = match item.kind {
1094            ast::ItemKind::Struct(ident, ref generics, ref def) => {
1095                ("struct ", def, ident, generics)
1096            }
1097            ast::ItemKind::Union(ident, ref generics, ref def) => ("union ", def, ident, generics),
1098            _ => unreachable!(),
1099        };
1100        StructParts {
1101            prefix,
1102            ident,
1103            vis: &item.vis,
1104            def,
1105            generics: Some(generics),
1106            span: item.span,
1107        }
1108    }
1109}
1110
1111fn enum_variant_span(variant: &ast::Variant, context: &RewriteContext<'_>) -> Span {
1112    use ast::VariantData::*;
1113    if let Some(ref anon_const) = variant.disr_expr {
1114        let span_before_consts = variant.span.until(anon_const.value.span);
1115        let hi = match &variant.data {
1116            Struct { .. } => context
1117                .snippet_provider
1118                .span_after_last(span_before_consts, "}"),
1119            Tuple(..) => context
1120                .snippet_provider
1121                .span_after_last(span_before_consts, ")"),
1122            Unit(..) => variant.ident.span.hi(),
1123        };
1124        mk_sp(span_before_consts.lo(), hi)
1125    } else {
1126        variant.span
1127    }
1128}
1129
1130fn format_struct(
1131    context: &RewriteContext<'_>,
1132    struct_parts: &StructParts<'_>,
1133    offset: Indent,
1134    one_line_width: Option<usize>,
1135) -> Option<String> {
1136    match struct_parts.def {
1137        ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
1138        ast::VariantData::Tuple(fields, _) => {
1139            format_tuple_struct(context, struct_parts, fields, offset)
1140        }
1141        ast::VariantData::Struct { fields, .. } => {
1142            format_struct_struct(context, struct_parts, fields, offset, one_line_width)
1143        }
1144    }
1145}
1146
1147pub(crate) fn format_trait(
1148    context: &RewriteContext<'_>,
1149    item: &ast::Item,
1150    trait_: &ast::Trait,
1151    offset: Indent,
1152) -> RewriteResult {
1153    let ast::Trait {
1154        ref impl_restriction,
1155        constness,
1156        is_auto,
1157        safety,
1158        ident,
1159        ref generics,
1160        ref bounds,
1161        ref items,
1162    } = *trait_;
1163
1164    let mut result = String::with_capacity(128);
1165    let header = format!(
1166        "{}{}{}{}{}trait ",
1167        format_visibility(context, &item.vis),
1168        format_impl_restriction(context, impl_restriction),
1169        format_constness(constness),
1170        format_safety(safety),
1171        format_auto(is_auto),
1172    );
1173    result.push_str(&header);
1174
1175    let body_lo = context.snippet_provider.span_after(item.span, "{");
1176
1177    let shape = Shape::indented(offset, context.config).offset_left(result.len(), item.span)?;
1178    let generics_str = rewrite_generics(context, rewrite_ident(context, ident), generics, shape)?;
1179    result.push_str(&generics_str);
1180
1181    // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
1182    if !bounds.is_empty() {
1183        // Retrieve *unnormalized* ident (See #6069)
1184        let source_ident = context.snippet(ident.span);
1185        let ident_hi = context.snippet_provider.span_after(item.span, source_ident);
1186        let bound_hi = bounds.last().unwrap().span().hi();
1187        let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1188        if contains_comment(snippet) {
1189            return Err(RewriteError::Unknown);
1190        }
1191
1192        result = rewrite_assign_rhs_with(
1193            context,
1194            result + ":",
1195            bounds,
1196            shape,
1197            &RhsAssignKind::Bounds,
1198            RhsTactics::ForceNextLineWithoutIndent,
1199        )?;
1200    }
1201
1202    // Rewrite where-clause.
1203    if !generics.where_clause.predicates.is_empty() {
1204        let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1205
1206        let where_budget = context.budget(last_line_width(&result));
1207        let pos_before_where = if bounds.is_empty() {
1208            generics.where_clause.span.lo()
1209        } else {
1210            bounds[bounds.len() - 1].span().hi()
1211        };
1212        let option = WhereClauseOption::snuggled(&generics_str);
1213        let where_clause_str = rewrite_where_clause(
1214            context,
1215            &generics.where_clause,
1216            context.config.brace_style(),
1217            Shape::legacy(where_budget, offset.block_only()),
1218            where_on_new_line,
1219            "{",
1220            None,
1221            pos_before_where,
1222            option,
1223        )?;
1224
1225        // If the where-clause cannot fit on the same line,
1226        // put the where-clause on a new line
1227        if !where_clause_str.contains('\n')
1228            && last_line_width(&result) + where_clause_str.len() + offset.width()
1229                > context.config.comment_width()
1230        {
1231            let width = offset.block_indent + context.config.tab_spaces() - 1;
1232            let where_indent = Indent::new(0, width);
1233            result.push_str(&where_indent.to_string_with_newline(context.config));
1234        }
1235        result.push_str(&where_clause_str);
1236    } else {
1237        let item_snippet = context.snippet(item.span);
1238        if let Some(lo) = item_snippet.find('/') {
1239            // 1 = `{`
1240            let comment_hi = if generics.params.len() > 0 {
1241                generics.span.lo() - BytePos(1)
1242            } else {
1243                body_lo - BytePos(1)
1244            };
1245            let comment_lo = item.span.lo() + BytePos(lo as u32);
1246            if comment_lo < comment_hi {
1247                match recover_missing_comment_in_span(
1248                    mk_sp(comment_lo, comment_hi),
1249                    Shape::indented(offset, context.config),
1250                    context,
1251                    last_line_width(&result),
1252                ) {
1253                    Ok(ref missing_comment) if !missing_comment.is_empty() => {
1254                        result.push_str(missing_comment);
1255                    }
1256                    _ => (),
1257                }
1258            }
1259        }
1260    }
1261
1262    let block_span = mk_sp(generics.where_clause.span.hi(), item.span.hi());
1263    let snippet = context.snippet(block_span);
1264    let open_pos = snippet.find_uncommented("{").unknown_error()? + 1;
1265
1266    match context.config.brace_style() {
1267        _ if last_line_contains_single_line_comment(&result)
1268            || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1269        {
1270            result.push_str(&offset.to_string_with_newline(context.config));
1271        }
1272        _ if context.config.empty_item_single_line()
1273            && items.is_empty()
1274            && !result.contains('\n')
1275            && !contains_comment(&snippet[open_pos..]) =>
1276        {
1277            result.push_str(" {}");
1278            return Ok(result);
1279        }
1280        BraceStyle::AlwaysNextLine => {
1281            result.push_str(&offset.to_string_with_newline(context.config));
1282        }
1283        BraceStyle::PreferSameLine => result.push(' '),
1284        BraceStyle::SameLineWhere => {
1285            if result.contains('\n')
1286                || (!generics.where_clause.predicates.is_empty() && !items.is_empty())
1287            {
1288                result.push_str(&offset.to_string_with_newline(context.config));
1289            } else {
1290                result.push(' ');
1291            }
1292        }
1293    }
1294    result.push('{');
1295
1296    let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1297
1298    if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
1299        let mut visitor = FmtVisitor::from_context(context);
1300        visitor.block_indent = offset.block_only().block_indent(context.config);
1301        visitor.last_pos = block_span.lo() + BytePos(open_pos as u32);
1302
1303        for item in items {
1304            visitor.visit_trait_item(item);
1305        }
1306
1307        visitor.format_missing(item.span.hi() - BytePos(1));
1308
1309        let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1310
1311        result.push_str(&inner_indent_str);
1312        result.push_str(visitor.buffer.trim());
1313        result.push_str(&outer_indent_str);
1314    } else if result.contains('\n') {
1315        result.push_str(&outer_indent_str);
1316    }
1317
1318    result.push('}');
1319    Ok(result)
1320}
1321
1322pub(crate) struct TraitAliasBounds<'a> {
1323    generic_bounds: &'a ast::GenericBounds,
1324    generics: &'a ast::Generics,
1325}
1326
1327impl<'a> Rewrite for TraitAliasBounds<'a> {
1328    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1329        self.rewrite_result(context, shape).ok()
1330    }
1331
1332    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1333        let generic_bounds_str = self.generic_bounds.rewrite_result(context, shape)?;
1334
1335        let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1336        option.allow_single_line();
1337
1338        let where_str = rewrite_where_clause(
1339            context,
1340            &self.generics.where_clause,
1341            context.config.brace_style(),
1342            shape,
1343            false,
1344            ";",
1345            None,
1346            self.generics.where_clause.span.lo(),
1347            option,
1348        )?;
1349
1350        let fits_single_line = !generic_bounds_str.contains('\n')
1351            && !where_str.contains('\n')
1352            && generic_bounds_str.len() + where_str.len() < shape.width;
1353        let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1354            Cow::from("")
1355        } else if fits_single_line {
1356            Cow::from(" ")
1357        } else {
1358            shape.indent.to_string_with_newline(context.config)
1359        };
1360
1361        Ok(format!("{generic_bounds_str}{space}{where_str}"))
1362    }
1363}
1364
1365pub(crate) fn format_trait_alias(
1366    context: &RewriteContext<'_>,
1367    ta: &ast::TraitAlias,
1368    vis: &ast::Visibility,
1369    span: Span,
1370    shape: Shape,
1371) -> RewriteResult {
1372    let alias = rewrite_ident(context, ta.ident);
1373    // 6 = "trait ", 2 = " ="
1374    let g_shape = shape.offset_left(6, span)?.sub_width(2, span)?;
1375    let generics_str = rewrite_generics(context, alias, &ta.generics, g_shape)?;
1376    let vis_str = format_visibility(context, vis);
1377    let constness = format_constness(ta.constness);
1378    let lhs = format!("{vis_str}{constness}trait {generics_str} =");
1379    // 1 = ";"
1380    let trait_alias_bounds = TraitAliasBounds {
1381        generic_bounds: &ta.bounds,
1382        generics: &ta.generics,
1383    };
1384    let result = rewrite_assign_rhs(
1385        context,
1386        lhs,
1387        &trait_alias_bounds,
1388        &RhsAssignKind::Bounds,
1389        shape.sub_width(1, ta.generics.span)?,
1390    )?;
1391    Ok(result + ";")
1392}
1393
1394fn format_unit_struct(
1395    context: &RewriteContext<'_>,
1396    p: &StructParts<'_>,
1397    offset: Indent,
1398) -> Option<String> {
1399    let header_str = format_header(context, p.prefix, p.ident, p.vis, offset);
1400    let generics_str = if let Some(generics) = p.generics {
1401        let hi = context.snippet_provider.span_before_last(p.span, ";");
1402        format_generics(
1403            context,
1404            generics,
1405            context.config.brace_style(),
1406            BracePos::None,
1407            offset,
1408            // make a span that starts right after `struct Foo`
1409            mk_sp(p.ident.span.hi(), hi),
1410            last_line_width(&header_str),
1411        )?
1412    } else {
1413        String::new()
1414    };
1415    Some(format!("{header_str}{generics_str};"))
1416}
1417
1418pub(crate) fn format_struct_struct(
1419    context: &RewriteContext<'_>,
1420    struct_parts: &StructParts<'_>,
1421    fields: &[ast::FieldDef],
1422    offset: Indent,
1423    one_line_width: Option<usize>,
1424) -> Option<String> {
1425    let mut result = String::with_capacity(1024);
1426    let span = struct_parts.span;
1427
1428    let header_str = struct_parts.format_header(context, offset);
1429    result.push_str(&header_str);
1430
1431    let header_hi = struct_parts.ident.span.hi();
1432    let body_lo = if let Some(generics) = struct_parts.generics {
1433        // Adjust the span to start at the end of the generic arguments before searching for the '{'
1434        let span = span.with_lo(generics.where_clause.span.hi());
1435        context.snippet_provider.span_after(span, "{")
1436    } else {
1437        context.snippet_provider.span_after(span, "{")
1438    };
1439
1440    let generics_str = match struct_parts.generics {
1441        Some(g) => format_generics(
1442            context,
1443            g,
1444            context.config.brace_style(),
1445            if fields.is_empty() {
1446                BracePos::ForceSameLine
1447            } else {
1448                BracePos::Auto
1449            },
1450            offset,
1451            // make a span that starts right after `struct Foo`
1452            mk_sp(header_hi, body_lo),
1453            last_line_width(&result),
1454        )?,
1455        None => {
1456            // 3 = ` {}`, 2 = ` {`.
1457            let overhead = if fields.is_empty() { 3 } else { 2 };
1458            if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1459                || context.config.max_width() < overhead + result.len()
1460            {
1461                format!("\n{}{{", offset.block_only().to_string(context.config))
1462            } else {
1463                " {".to_owned()
1464            }
1465        }
1466    };
1467    // 1 = `}`
1468    let overhead = if fields.is_empty() { 1 } else { 0 };
1469    let total_width = result.len() + generics_str.len() + overhead;
1470    if !generics_str.is_empty()
1471        && !generics_str.contains('\n')
1472        && total_width > context.config.max_width()
1473    {
1474        result.push('\n');
1475        result.push_str(&offset.to_string(context.config));
1476        result.push_str(generics_str.trim_start());
1477    } else {
1478        result.push_str(&generics_str);
1479    }
1480
1481    if fields.is_empty() {
1482        let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1483        format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1484        return Some(result);
1485    }
1486
1487    // 3 = ` ` and ` }`
1488    let one_line_budget = context.budget(result.len() + 3 + offset.width());
1489    let one_line_budget =
1490        one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1491
1492    let items_str = rewrite_with_alignment(
1493        fields,
1494        context,
1495        Shape::indented(offset.block_indent(context.config), context.config).sub_width_opt(1)?,
1496        mk_sp(body_lo, span.hi()),
1497        one_line_budget,
1498    )?;
1499
1500    if !items_str.contains('\n')
1501        && !result.contains('\n')
1502        && items_str.len() <= one_line_budget
1503        && !last_line_contains_single_line_comment(&items_str)
1504    {
1505        Some(format!("{result} {items_str} }}"))
1506    } else {
1507        Some(format!(
1508            "{}\n{}{}\n{}}}",
1509            result,
1510            offset
1511                .block_indent(context.config)
1512                .to_string(context.config),
1513            items_str,
1514            offset.to_string(context.config)
1515        ))
1516    }
1517}
1518
1519fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1520    match vis.kind {
1521        ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1522        _ => default_span.lo(),
1523    }
1524}
1525
1526// Format tuple or struct without any fields. We need to make sure that the comments
1527// inside the delimiters are preserved.
1528pub(crate) fn format_empty_struct_or_tuple(
1529    context: &RewriteContext<'_>,
1530    span: Span,
1531    offset: Indent,
1532    result: &mut String,
1533    opener: &str,
1534    closer: &str,
1535) {
1536    // 3 = " {}" or "();"
1537    let used_width = last_line_used_width(result, offset.width()) + 3;
1538    if used_width > context.config.max_width() {
1539        result.push_str(&offset.to_string_with_newline(context.config))
1540    }
1541    result.push_str(opener);
1542
1543    // indented shape for proper indenting of multi-line comments
1544    let shape = Shape::indented(offset.block_indent(context.config), context.config);
1545    match rewrite_missing_comment(span, shape, context) {
1546        Ok(ref s) if s.is_empty() => (),
1547        Ok(ref s) => {
1548            let is_multi_line = !is_single_line(s);
1549            if is_multi_line || first_line_contains_single_line_comment(s) {
1550                let nested_indent_str = offset
1551                    .block_indent(context.config)
1552                    .to_string_with_newline(context.config);
1553                result.push_str(&nested_indent_str);
1554            }
1555            result.push_str(s);
1556            if is_multi_line || last_line_contains_single_line_comment(s) {
1557                result.push_str(&offset.to_string_with_newline(context.config));
1558            }
1559        }
1560        Err(_) => result.push_str(context.snippet(span)),
1561    }
1562    result.push_str(closer);
1563}
1564
1565fn format_tuple_struct(
1566    context: &RewriteContext<'_>,
1567    struct_parts: &StructParts<'_>,
1568    fields: &[ast::FieldDef],
1569    offset: Indent,
1570) -> Option<String> {
1571    let mut result = String::with_capacity(1024);
1572    let span = struct_parts.span;
1573
1574    let header_str = struct_parts.format_header(context, offset);
1575    result.push_str(&header_str);
1576
1577    let body_lo = if fields.is_empty() {
1578        let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1579        context
1580            .snippet_provider
1581            .span_after(mk_sp(lo, span.hi()), "(")
1582    } else {
1583        fields[0].span.lo()
1584    };
1585    let body_hi = if fields.is_empty() {
1586        context
1587            .snippet_provider
1588            .span_after(mk_sp(body_lo, span.hi()), ")")
1589    } else {
1590        // This is a dirty hack to work around a missing `)` from the span of the last field.
1591        let last_arg_span = fields[fields.len() - 1].span;
1592        context
1593            .snippet_provider
1594            .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1595            .unwrap_or_else(|| last_arg_span.hi())
1596    };
1597
1598    let where_clause_str = match struct_parts.generics {
1599        Some(generics) => {
1600            let budget = context.budget(last_line_width(&header_str));
1601            let shape = Shape::legacy(budget, offset);
1602            let generics_str = rewrite_generics(context, "", generics, shape).ok()?;
1603            result.push_str(&generics_str);
1604
1605            let where_budget = context.budget(last_line_width(&result));
1606            let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1607            rewrite_where_clause(
1608                context,
1609                &generics.where_clause,
1610                context.config.brace_style(),
1611                Shape::legacy(where_budget, offset.block_only()),
1612                false,
1613                ";",
1614                None,
1615                body_hi,
1616                option,
1617            )
1618            .ok()?
1619        }
1620        None => "".to_owned(),
1621    };
1622
1623    if fields.is_empty() {
1624        let body_hi = context
1625            .snippet_provider
1626            .span_before(mk_sp(body_lo, span.hi()), ")");
1627        let inner_span = mk_sp(body_lo, body_hi);
1628        format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1629    } else {
1630        let lo = if let Some(generics) = struct_parts.generics {
1631            generics.span.hi()
1632        } else {
1633            struct_parts.ident.span.hi()
1634        };
1635        let shape = Shape::indented(offset, context.config).sub_width_opt(1)?;
1636        result = overflow::rewrite_with_parens(
1637            context,
1638            &result,
1639            fields.iter(),
1640            shape,
1641            mk_sp(lo, span.hi()),
1642            context.config.fn_call_width(),
1643            None,
1644        )
1645        .ok()?;
1646    }
1647
1648    if !where_clause_str.is_empty()
1649        && !where_clause_str.contains('\n')
1650        && (result.contains('\n')
1651            || offset.block_indent + result.len() + where_clause_str.len() + 1
1652                > context.config.max_width())
1653    {
1654        // We need to put the where-clause on a new line, but we didn't
1655        // know that earlier, so the where-clause will not be indented properly.
1656        result.push('\n');
1657        result.push_str(
1658            &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1659        );
1660    }
1661    result.push_str(&where_clause_str);
1662
1663    Some(result)
1664}
1665
1666#[derive(Clone, Copy)]
1667pub(crate) enum ItemVisitorKind {
1668    Item,
1669    AssocTraitItem,
1670    AssocImplItem,
1671    ForeignItem,
1672}
1673
1674struct TyAliasRewriteInfo<'c, 'g>(
1675    &'c RewriteContext<'c>,
1676    Indent,
1677    &'g ast::Generics,
1678    &'g ast::WhereClause,
1679    symbol::Ident,
1680    Span,
1681);
1682
1683pub(crate) fn rewrite_type_alias<'a>(
1684    ty_alias_kind: &ast::TyAlias,
1685    vis: &ast::Visibility,
1686    context: &RewriteContext<'a>,
1687    indent: Indent,
1688    visitor_kind: ItemVisitorKind,
1689    span: Span,
1690) -> RewriteResult {
1691    use ItemVisitorKind::*;
1692
1693    let ast::TyAlias {
1694        defaultness,
1695        ident,
1696        ref generics,
1697        ref bounds,
1698        ref ty,
1699        ref after_where_clause,
1700    } = *ty_alias_kind;
1701    let ty_opt = ty.as_ref();
1702    let rhs_hi = ty
1703        .as_ref()
1704        .map_or(generics.where_clause.span.hi(), |ty| ty.span.hi());
1705    let rw_info = &TyAliasRewriteInfo(context, indent, generics, after_where_clause, ident, span);
1706    let op_ty = opaque_ty(ty);
1707    // Type Aliases are formatted slightly differently depending on the context
1708    // in which they appear, whether they are opaque, and whether they are associated.
1709    // https://rustc-dev-guide.rust-lang.org/opaque-types-type-alias-impl-trait.html
1710    // https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/items.md#type-aliases
1711    match (visitor_kind, &op_ty) {
1712        (Item | AssocTraitItem | ForeignItem, Some(op_bounds)) => {
1713            let op = OpaqueType { bounds: op_bounds };
1714            rewrite_ty(rw_info, Some(bounds), Some(&op), rhs_hi, vis, defaultness)
1715        }
1716        (Item | AssocTraitItem | ForeignItem, None) => {
1717            rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis, defaultness)
1718        }
1719        (AssocImplItem, _) => {
1720            if let Some(op_bounds) = op_ty {
1721                let op = OpaqueType { bounds: op_bounds };
1722                rewrite_ty(
1723                    rw_info,
1724                    Some(bounds),
1725                    Some(&op),
1726                    rhs_hi,
1727                    &DEFAULT_VISIBILITY,
1728                    defaultness,
1729                )
1730            } else {
1731                rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis, defaultness)
1732            }
1733        }
1734    }
1735}
1736
1737fn rewrite_ty<R: Rewrite>(
1738    rw_info: &TyAliasRewriteInfo<'_, '_>,
1739    generic_bounds_opt: Option<&ast::GenericBounds>,
1740    rhs: Option<&R>,
1741    // the span of the end of the RHS (or the end of the generics, if there is no RHS)
1742    rhs_hi: BytePos,
1743    vis: &ast::Visibility,
1744    defaultness: ast::Defaultness,
1745) -> RewriteResult {
1746    let mut result = String::with_capacity(128);
1747    let TyAliasRewriteInfo(context, indent, generics, after_where_clause, ident, span) = *rw_info;
1748    result.push_str(&format!(
1749        "{}{}type ",
1750        format_visibility(context, vis),
1751        format_defaultness(defaultness)
1752    ));
1753    let ident_str = rewrite_ident(context, ident);
1754
1755    if generics.params.is_empty() {
1756        result.push_str(ident_str)
1757    } else {
1758        // 2 = `= `
1759        let g_shape = Shape::indented(indent, context.config);
1760        let g_shape = g_shape
1761            .offset_left(result.len(), span)?
1762            .sub_width(2, span)?;
1763        let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1764        result.push_str(&generics_str);
1765    }
1766
1767    if let Some(bounds) = generic_bounds_opt {
1768        if !bounds.is_empty() {
1769            // 2 = `: `
1770            let shape = Shape::indented(indent, context.config);
1771            let shape = shape.offset_left(result.len() + 2, span)?;
1772            let type_bounds = bounds
1773                .rewrite_result(context, shape)
1774                .map(|s| format!(": {}", s))?;
1775            result.push_str(&type_bounds);
1776        }
1777    }
1778
1779    let where_budget = context.budget(last_line_width(&result));
1780    let mut option = WhereClauseOption::snuggled(&result);
1781    if rhs.is_none() {
1782        option.suppress_comma();
1783    }
1784    let before_where_clause_str = rewrite_where_clause(
1785        context,
1786        &generics.where_clause,
1787        context.config.brace_style(),
1788        Shape::legacy(where_budget, indent),
1789        false,
1790        "=",
1791        None,
1792        generics.span.hi(),
1793        option,
1794    )?;
1795    result.push_str(&before_where_clause_str);
1796
1797    let mut result = if let Some(ty) = rhs {
1798        // If there are any where clauses, add a newline before the assignment.
1799        // If there is a before where clause, do not indent, but if there is
1800        // only an after where clause, additionally indent the type.
1801        if !generics.where_clause.predicates.is_empty() {
1802            result.push_str(&indent.to_string_with_newline(context.config));
1803        } else if !after_where_clause.predicates.is_empty() {
1804            result.push_str(
1805                &indent
1806                    .block_indent(context.config)
1807                    .to_string_with_newline(context.config),
1808            );
1809        } else {
1810            result.push(' ');
1811        }
1812
1813        let comment_span = context
1814            .snippet_provider
1815            .opt_span_before(span, "=")
1816            .map(|op_lo| mk_sp(generics.where_clause.span.hi(), op_lo));
1817
1818        let lhs = match comment_span {
1819            Some(comment_span)
1820                if contains_comment(
1821                    context
1822                        .snippet_provider
1823                        .span_to_snippet(comment_span)
1824                        .unknown_error()?,
1825                ) =>
1826            {
1827                let comment_shape = if !generics.where_clause.predicates.is_empty() {
1828                    Shape::indented(indent, context.config)
1829                } else {
1830                    let shape = Shape::indented(indent, context.config);
1831                    shape.block_left(context.config.tab_spaces(), span)?
1832                };
1833
1834                combine_strs_with_missing_comments(
1835                    context,
1836                    result.trim_end(),
1837                    "=",
1838                    comment_span,
1839                    comment_shape,
1840                    true,
1841                )?
1842            }
1843            _ => format!("{result}="),
1844        };
1845
1846        // 1 = `;` unless there's a trailing where clause
1847        let shape = Shape::indented(indent, context.config);
1848        let shape = if after_where_clause.predicates.is_empty() {
1849            Shape::indented(indent, context.config).sub_width(1, span)?
1850        } else {
1851            shape
1852        };
1853        rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape)?
1854    } else {
1855        result
1856    };
1857
1858    if !after_where_clause.predicates.is_empty() {
1859        let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1860        let after_where_clause_str = rewrite_where_clause(
1861            context,
1862            &after_where_clause,
1863            context.config.brace_style(),
1864            Shape::indented(indent, context.config),
1865            false,
1866            ";",
1867            None,
1868            rhs_hi,
1869            option,
1870        )?;
1871        result.push_str(&after_where_clause_str);
1872    }
1873
1874    result += ";";
1875    Ok(result)
1876}
1877
1878fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1879    (
1880        if config.space_before_colon() { " " } else { "" },
1881        if config.space_after_colon() { " " } else { "" },
1882    )
1883}
1884
1885pub(crate) fn rewrite_struct_field_prefix(
1886    context: &RewriteContext<'_>,
1887    field: &ast::FieldDef,
1888) -> RewriteResult {
1889    let vis = format_visibility(context, &field.vis);
1890    let mut_restriction = format_mut_restriction(context, field.mut_restriction());
1891    let safety = format_safety(field.safety());
1892    let type_annotation_spacing = type_annotation_spacing(context.config);
1893    Ok(match field.ident {
1894        Some(name) => format!(
1895            "{vis}{mut_restriction}{safety}{}{}:",
1896            rewrite_ident(context, name),
1897            type_annotation_spacing.0
1898        ),
1899        None => format!("{vis}{mut_restriction}{safety}"),
1900    })
1901}
1902
1903impl Rewrite for ast::FieldDef {
1904    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1905        self.rewrite_result(context, shape).ok()
1906    }
1907
1908    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1909        rewrite_struct_field(context, self, shape, 0)
1910    }
1911}
1912
1913pub(crate) fn rewrite_struct_field(
1914    context: &RewriteContext<'_>,
1915    field: &ast::FieldDef,
1916    shape: Shape,
1917    lhs_max_width: usize,
1918) -> RewriteResult {
1919    // FIXME(default_field_values): Implement formatting.
1920    if field.default_value().is_some() {
1921        return Err(RewriteError::Unknown);
1922    }
1923
1924    if contains_skip(&field.attrs) {
1925        return Ok(context.snippet(field.span()).to_owned());
1926    }
1927
1928    let type_annotation_spacing = type_annotation_spacing(context.config);
1929    let prefix = rewrite_struct_field_prefix(context, field)?;
1930
1931    let attrs_str = field.attrs.rewrite_result(context, shape)?;
1932    let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1933    let missing_span = if field.attrs.is_empty() {
1934        mk_sp(field.span.lo(), field.span.lo())
1935    } else {
1936        mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1937    };
1938    let mut spacing = String::from(if field.ident.is_some() {
1939        type_annotation_spacing.1
1940    } else {
1941        ""
1942    });
1943    // Try to put everything on a single line.
1944    let attr_prefix = combine_strs_with_missing_comments(
1945        context,
1946        &attrs_str,
1947        &prefix,
1948        missing_span,
1949        shape,
1950        attrs_extendable,
1951    )?;
1952    let overhead = trimmed_last_line_width(&attr_prefix);
1953    let lhs_offset = lhs_max_width.saturating_sub(overhead);
1954    for _ in 0..lhs_offset {
1955        spacing.push(' ');
1956    }
1957    // In this extreme case we will be missing a space between an attribute and a field.
1958    if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1959        spacing.push(' ');
1960    }
1961
1962    let orig_ty = shape
1963        .offset_left_opt(overhead + spacing.len())
1964        .and_then(|ty_shape| field.ty.rewrite_result(context, ty_shape).ok());
1965
1966    if let Some(ref ty) = orig_ty {
1967        if !ty.contains('\n') && !contains_comment(context.snippet(missing_span)) {
1968            return Ok(attr_prefix + &spacing + ty);
1969        }
1970    }
1971
1972    let is_prefix_empty = prefix.is_empty();
1973    // We must use multiline. We are going to put attributes and a field on different lines.
1974    let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, &RhsAssignKind::Ty, shape)?;
1975    // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1976    let field_str = if is_prefix_empty {
1977        field_str.trim_start()
1978    } else {
1979        &field_str
1980    };
1981    combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1982}
1983
1984pub(crate) struct StaticParts<'a> {
1985    prefix: &'a str,
1986    safety: ast::Safety,
1987    vis: &'a ast::Visibility,
1988    ident: symbol::Ident,
1989    generics: Option<&'a ast::Generics>,
1990    ty: &'a ast::Ty,
1991    mutability: ast::Mutability,
1992    expr_opt: Option<&'a ast::Expr>,
1993    defaultness: Option<ast::Defaultness>,
1994    span: Span,
1995}
1996
1997impl<'a> StaticParts<'a> {
1998    pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1999        let (defaultness, prefix, safety, ident, ty, mutability, expr_opt, generics) =
2000            match &item.kind {
2001                ast::ItemKind::Static(s) => (
2002                    None,
2003                    "static",
2004                    s.safety,
2005                    s.ident,
2006                    &s.ty,
2007                    s.mutability,
2008                    s.expr.as_deref(),
2009                    None,
2010                ),
2011                ast::ItemKind::Const(c) => (
2012                    Some(c.defaultness),
2013                    if c.kind == ast::ConstItemKind::TypeConst {
2014                        "type const"
2015                    } else {
2016                        "const"
2017                    },
2018                    ast::Safety::Default,
2019                    c.ident,
2020                    &c.ty,
2021                    ast::Mutability::Not,
2022                    c.body.as_deref(),
2023                    Some(&c.generics),
2024                ),
2025                _ => unreachable!(),
2026            };
2027        StaticParts {
2028            prefix,
2029            safety,
2030            vis: &item.vis,
2031            ident,
2032            generics,
2033            ty,
2034            mutability,
2035            expr_opt,
2036            defaultness,
2037            span: item.span,
2038        }
2039    }
2040
2041    pub(crate) fn from_trait_item(ti: &'a ast::AssocItem, ident: Ident) -> Self {
2042        let (defaultness, ty, expr_opt, generics, prefix) = match &ti.kind {
2043            ast::AssocItemKind::Const(c) => {
2044                let prefix = if c.kind == ast::ConstItemKind::TypeConst {
2045                    "type const"
2046                } else {
2047                    "const"
2048                };
2049                (
2050                    c.defaultness,
2051                    &c.ty,
2052                    c.body.as_deref(),
2053                    Some(&c.generics),
2054                    prefix,
2055                )
2056            }
2057            _ => unreachable!(),
2058        };
2059        StaticParts {
2060            prefix,
2061            safety: ast::Safety::Default,
2062            vis: &ti.vis,
2063            ident,
2064            generics,
2065            ty,
2066            mutability: ast::Mutability::Not,
2067            expr_opt,
2068            defaultness: Some(defaultness),
2069            span: ti.span,
2070        }
2071    }
2072
2073    pub(crate) fn from_impl_item(ii: &'a ast::AssocItem, ident: Ident) -> Self {
2074        let (defaultness, ty, expr_opt, generics, prefix) = match &ii.kind {
2075            ast::AssocItemKind::Const(c) => {
2076                let prefix = if c.kind == ast::ConstItemKind::TypeConst {
2077                    "type const"
2078                } else {
2079                    "const"
2080                };
2081                (
2082                    c.defaultness,
2083                    &c.ty,
2084                    c.body.as_deref(),
2085                    Some(&c.generics),
2086                    prefix,
2087                )
2088            }
2089            _ => unreachable!(),
2090        };
2091        StaticParts {
2092            prefix,
2093            safety: ast::Safety::Default,
2094            vis: &ii.vis,
2095            ident,
2096            generics,
2097            ty,
2098            mutability: ast::Mutability::Not,
2099            expr_opt,
2100            defaultness: Some(defaultness),
2101            span: ii.span,
2102        }
2103    }
2104}
2105
2106fn rewrite_static(
2107    context: &RewriteContext<'_>,
2108    static_parts: &StaticParts<'_>,
2109    offset: Indent,
2110) -> Option<String> {
2111    // For now, if this static (or const) has a where clause, then bail.
2112    if static_parts
2113        .generics
2114        .is_some_and(|g| !g.where_clause.is_empty())
2115    {
2116        return None;
2117    }
2118    let generics = static_parts
2119        .generics
2120        .and_then(|g| {
2121            format_generics(
2122                context,
2123                &g,
2124                context.config.brace_style(),
2125                BracePos::None,
2126                offset,
2127                // make a span that starts right after `const x<n>`
2128                mk_sp(static_parts.ident.span.hi(), static_parts.ty.span.lo()),
2129                offset.block_indent,
2130            )
2131        })
2132        .map_or("".into(), |x| format!("{x}"));
2133    let colon = colon_spaces(context.config);
2134    let mut prefix = format!(
2135        "{}{}{}{} {}{}{}{}",
2136        format_visibility(context, static_parts.vis),
2137        static_parts.defaultness.map_or("", format_defaultness),
2138        format_safety(static_parts.safety),
2139        static_parts.prefix,
2140        format_mutability(static_parts.mutability),
2141        rewrite_ident(context, static_parts.ident),
2142        generics,
2143        colon
2144    );
2145
2146    // 2 = " =".len()
2147    let ty_shape = Shape::indented(offset.block_only(), context.config)
2148        .offset_left_opt(last_line_width(&prefix) + 2)?;
2149    let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
2150        Some(ty_str) => ty_str,
2151        None => {
2152            if prefix.ends_with(' ') {
2153                prefix.pop();
2154            }
2155            let nested_indent = offset.block_indent(context.config);
2156            let nested_shape = Shape::indented(nested_indent, context.config);
2157            let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
2158            format!(
2159                "{}{}",
2160                nested_indent.to_string_with_newline(context.config),
2161                ty_str
2162            )
2163        }
2164    };
2165
2166    if let Some(expr) = static_parts.expr_opt {
2167        let comments_lo = context.snippet_provider.span_after(static_parts.span, "=");
2168        let expr_lo = expr.span.lo();
2169        let comments_span = mk_sp(comments_lo, expr_lo);
2170
2171        let lhs = format!("{prefix}{ty_str} =");
2172
2173        // 1 = ;
2174        let remaining_width = context.budget(offset.block_indent + 1);
2175        rewrite_assign_rhs_with_comments(
2176            context,
2177            &lhs,
2178            expr,
2179            Shape::legacy(remaining_width, offset.block_only()),
2180            &RhsAssignKind::Expr(&expr.kind, expr.span),
2181            RhsTactics::Default,
2182            comments_span,
2183            true,
2184        )
2185        .ok()
2186        .map(|res| recover_comment_removed(res, static_parts.span, context))
2187        .map(|s| if s.ends_with(';') { s } else { s + ";" })
2188    } else {
2189        Some(format!("{prefix}{ty_str};"))
2190    }
2191}
2192
2193// FIXME(calebcartwright) - This is a hack around a bug in the handling of TyKind::ImplTrait.
2194// This should be removed once that bug is resolved, with the type alias formatting using the
2195// defined Ty for the RHS directly.
2196// https://github.com/rust-lang/rustfmt/issues/4373
2197// https://github.com/rust-lang/rustfmt/issues/5027
2198struct OpaqueType<'a> {
2199    bounds: &'a ast::GenericBounds,
2200}
2201
2202impl<'a> Rewrite for OpaqueType<'a> {
2203    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2204        let shape = shape.offset_left_opt(5)?; // `impl `
2205        self.bounds
2206            .rewrite(context, shape)
2207            .map(|s| format!("impl {}", s))
2208    }
2209}
2210
2211impl Rewrite for ast::FnRetTy {
2212    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2213        self.rewrite_result(context, shape).ok()
2214    }
2215
2216    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2217        match *self {
2218            ast::FnRetTy::Default(_) => Ok(String::new()),
2219            ast::FnRetTy::Ty(ref ty) => {
2220                let arrow_width = "-> ".len();
2221                if context.config.style_edition() <= StyleEdition::Edition2021
2222                    || context.config.indent_style() == IndentStyle::Visual
2223                {
2224                    let inner_width = shape
2225                        .width
2226                        .checked_sub(arrow_width)
2227                        .max_width_error(shape.width, self.span())?;
2228                    return ty
2229                        .rewrite_result(
2230                            context,
2231                            Shape::legacy(inner_width, shape.indent + arrow_width),
2232                        )
2233                        .map(|r| format!("-> {}", r));
2234                }
2235
2236                let shape = shape.offset_left(arrow_width, self.span())?;
2237
2238                ty.rewrite_result(context, shape)
2239                    .map(|s| format!("-> {}", s))
2240            }
2241        }
2242    }
2243}
2244
2245fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
2246    match ty.kind {
2247        ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
2248        _ => false,
2249    }
2250}
2251
2252/// Recover any missing comments between the param and the type.
2253///
2254/// # Returns
2255///
2256/// A 2-len tuple with the comment before the colon in first position, and the comment after the
2257/// colon in second position.
2258fn get_missing_param_comments(
2259    context: &RewriteContext<'_>,
2260    pat_span: Span,
2261    ty_span: Span,
2262    shape: Shape,
2263) -> (String, String) {
2264    let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
2265
2266    let span_before_colon = {
2267        let missing_comment_span_hi = context
2268            .snippet_provider
2269            .span_before(missing_comment_span, ":");
2270        mk_sp(pat_span.hi(), missing_comment_span_hi)
2271    };
2272    let span_after_colon = {
2273        let missing_comment_span_lo = context
2274            .snippet_provider
2275            .span_after(missing_comment_span, ":");
2276        mk_sp(missing_comment_span_lo, ty_span.lo())
2277    };
2278
2279    let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
2280        .ok()
2281        .filter(|comment| !comment.is_empty())
2282        .map_or(String::new(), |comment| format!(" {}", comment));
2283    let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
2284        .ok()
2285        .filter(|comment| !comment.is_empty())
2286        .map_or(String::new(), |comment| format!("{} ", comment));
2287    (comment_before_colon, comment_after_colon)
2288}
2289
2290impl Rewrite for ast::Param {
2291    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2292        self.rewrite_result(context, shape).ok()
2293    }
2294
2295    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2296        let param_attrs_result = self
2297            .attrs
2298            .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2299        // N.B. Doc comments aren't typically valid syntax, but could appear
2300        // in the presence of certain macros - https://github.com/rust-lang/rustfmt/issues/4936
2301        let (span, has_multiple_attr_lines, has_doc_comments) = if !self.attrs.is_empty() {
2302            let num_attrs = self.attrs.len();
2303            (
2304                mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
2305                param_attrs_result.contains('\n'),
2306                self.attrs.iter().any(|a| a.is_doc_comment()),
2307            )
2308        } else {
2309            (mk_sp(self.span.lo(), self.span.lo()), false, false)
2310        };
2311
2312        if let Some(ref explicit_self) = self.to_self() {
2313            rewrite_explicit_self(
2314                context,
2315                explicit_self,
2316                &param_attrs_result,
2317                span,
2318                shape,
2319                has_multiple_attr_lines,
2320            )
2321        } else if is_named_param(self) {
2322            let param_name = &self
2323                .pat
2324                .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2325            let mut result = combine_strs_with_missing_comments(
2326                context,
2327                &param_attrs_result,
2328                param_name,
2329                span,
2330                shape,
2331                !has_multiple_attr_lines && !has_doc_comments,
2332            )?;
2333
2334            if !is_empty_infer(&*self.ty, self.pat.span) {
2335                let (before_comment, after_comment) =
2336                    get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
2337                result.push_str(&before_comment);
2338                result.push_str(colon_spaces(context.config));
2339                result.push_str(&after_comment);
2340                let overhead = last_line_width(&result);
2341                let max_width = shape
2342                    .width
2343                    .checked_sub(overhead)
2344                    .max_width_error(shape.width, self.span())?;
2345                if let Ok(ty_str) = self
2346                    .ty
2347                    .rewrite_result(context, Shape::legacy(max_width, shape.indent))
2348                {
2349                    result.push_str(&ty_str);
2350                } else {
2351                    let prev_str = if param_attrs_result.is_empty() {
2352                        param_attrs_result
2353                    } else {
2354                        param_attrs_result + &shape.to_string_with_newline(context.config)
2355                    };
2356
2357                    result = combine_strs_with_missing_comments(
2358                        context,
2359                        &prev_str,
2360                        param_name,
2361                        span,
2362                        shape,
2363                        !has_multiple_attr_lines,
2364                    )?;
2365                    result.push_str(&before_comment);
2366                    result.push_str(colon_spaces(context.config));
2367                    result.push_str(&after_comment);
2368                    let overhead = last_line_width(&result);
2369                    let max_width = shape
2370                        .width
2371                        .checked_sub(overhead)
2372                        .max_width_error(shape.width, self.span())?;
2373                    let ty_str = self
2374                        .ty
2375                        .rewrite_result(context, Shape::legacy(max_width, shape.indent))?;
2376                    result.push_str(&ty_str);
2377                }
2378            }
2379
2380            Ok(result)
2381        } else {
2382            combine_strs_with_missing_comments(
2383                context,
2384                &param_attrs_result,
2385                &self.ty.rewrite_result(context, shape)?,
2386                span,
2387                shape,
2388                !has_multiple_attr_lines && !has_doc_comments,
2389            )
2390        }
2391    }
2392}
2393
2394fn rewrite_opt_lifetime(
2395    context: &RewriteContext<'_>,
2396    lifetime: Option<ast::Lifetime>,
2397) -> RewriteResult {
2398    let Some(l) = lifetime else {
2399        return Ok(String::new());
2400    };
2401    let mut result = l.rewrite_result(
2402        context,
2403        Shape::legacy(context.config.max_width(), Indent::empty()),
2404    )?;
2405    result.push(' ');
2406    Ok(result)
2407}
2408
2409fn rewrite_explicit_self(
2410    context: &RewriteContext<'_>,
2411    explicit_self: &ast::ExplicitSelf,
2412    param_attrs: &str,
2413    span: Span,
2414    shape: Shape,
2415    has_multiple_attr_lines: bool,
2416) -> RewriteResult {
2417    let self_str = match explicit_self.node {
2418        ast::SelfKind::Region(lt, m) => {
2419            let mut_str = format_mutability(m);
2420            let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2421            format!("&{lifetime_str}{mut_str}self")
2422        }
2423        ast::SelfKind::Pinned(lt, m) => {
2424            let mut_str = m.ptr_str();
2425            let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2426            format!("&{lifetime_str}pin {mut_str} self")
2427        }
2428        ast::SelfKind::Explicit(ref ty, mutability) => {
2429            let type_str = ty.rewrite_result(
2430                context,
2431                Shape::legacy(context.config.max_width(), Indent::empty()),
2432            )?;
2433            format!("{}self: {}", format_mutability(mutability), type_str)
2434        }
2435        ast::SelfKind::Value(mutability) => format!("{}self", format_mutability(mutability)),
2436    };
2437    Ok(combine_strs_with_missing_comments(
2438        context,
2439        param_attrs,
2440        &self_str,
2441        span,
2442        shape,
2443        !has_multiple_attr_lines,
2444    )?)
2445}
2446
2447pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2448    if param.attrs.is_empty() {
2449        if is_named_param(param) {
2450            param.pat.span.lo()
2451        } else {
2452            param.ty.span.lo()
2453        }
2454    } else {
2455        param.attrs[0].span.lo()
2456    }
2457}
2458
2459pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2460    match param.ty.kind {
2461        ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2462        ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2463        _ => param.ty.span.hi(),
2464    }
2465}
2466
2467pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2468    !matches!(param.pat.kind, ast::PatKind::Missing)
2469}
2470
2471#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2472pub(crate) enum FnBraceStyle {
2473    SameLine,
2474    NextLine,
2475    None,
2476}
2477
2478// Return type is (result, force_new_line_for_brace)
2479fn rewrite_fn_base(
2480    context: &RewriteContext<'_>,
2481    indent: Indent,
2482    ident: symbol::Ident,
2483    fn_sig: &FnSig<'_>,
2484    span: Span,
2485    fn_brace_style: FnBraceStyle,
2486) -> Result<(String, bool, bool), RewriteError> {
2487    let mut force_new_line_for_brace = false;
2488
2489    let where_clause = &fn_sig.generics.where_clause;
2490
2491    let mut result = String::with_capacity(1024);
2492    result.push_str(&fn_sig.to_str(context));
2493
2494    // fn foo
2495    result.push_str("fn ");
2496
2497    // Generics.
2498    let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2499        // 4 = `() {`
2500        4
2501    } else {
2502        // 2 = `()`
2503        2
2504    };
2505    let used_width = last_line_used_width(&result, indent.width());
2506    let one_line_budget = context.budget(used_width + overhead);
2507    let shape = Shape {
2508        width: one_line_budget,
2509        indent,
2510        offset: used_width,
2511    };
2512    let fd = fn_sig.decl;
2513    let generics_str = rewrite_generics(
2514        context,
2515        rewrite_ident(context, ident),
2516        &fn_sig.generics,
2517        shape,
2518    )?;
2519    result.push_str(&generics_str);
2520
2521    let snuggle_angle_bracket = generics_str
2522        .lines()
2523        .last()
2524        .map_or(false, |l| l.trim_start().len() == 1);
2525
2526    // Note that the width and indent don't really matter, we'll re-layout the
2527    // return type later anyway.
2528    let ret_str = fd
2529        .output
2530        .rewrite_result(context, Shape::indented(indent, context.config))?;
2531
2532    let multi_line_ret_str = ret_str.contains('\n');
2533    let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2534
2535    // Params.
2536    let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2537        context,
2538        &result,
2539        indent,
2540        ret_str_len,
2541        fn_brace_style,
2542        multi_line_ret_str,
2543    );
2544
2545    debug!(
2546        "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2547        one_line_budget, multi_line_budget, param_indent
2548    );
2549
2550    result.push('(');
2551    // Check if vertical layout was forced.
2552    if one_line_budget == 0
2553        && !snuggle_angle_bracket
2554        && context.config.indent_style() == IndentStyle::Visual
2555    {
2556        result.push_str(&param_indent.to_string_with_newline(context.config));
2557    }
2558
2559    let params_end = if fd.inputs.is_empty() {
2560        context
2561            .snippet_provider
2562            .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), ")")
2563    } else {
2564        let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2565        context.snippet_provider.span_after(last_span, ")")
2566    };
2567    let params_span = mk_sp(
2568        context
2569            .snippet_provider
2570            .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), "("),
2571        params_end,
2572    );
2573    let param_str = rewrite_params(
2574        context,
2575        &fd.inputs,
2576        one_line_budget,
2577        multi_line_budget,
2578        indent,
2579        param_indent,
2580        params_span,
2581        fd.c_variadic(),
2582    )?;
2583
2584    let put_params_in_block = match context.config.indent_style() {
2585        IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2586        _ => false,
2587    } && !fd.inputs.is_empty();
2588
2589    let mut params_last_line_contains_comment = false;
2590    let mut no_params_and_over_max_width = false;
2591
2592    if put_params_in_block {
2593        param_indent = indent.block_indent(context.config);
2594        result.push_str(&param_indent.to_string_with_newline(context.config));
2595        result.push_str(&param_str);
2596        result.push_str(&indent.to_string_with_newline(context.config));
2597        result.push(')');
2598    } else {
2599        result.push_str(&param_str);
2600        let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2601        // Put the closing brace on the next line if it overflows the max width.
2602        // 1 = `)`
2603        let closing_paren_overflow_max_width =
2604            fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2605        // If the last line of params contains comment, we cannot put the closing paren
2606        // on the same line.
2607        params_last_line_contains_comment = param_str
2608            .lines()
2609            .last()
2610            .map_or(false, |last_line| last_line.contains("//"));
2611
2612        if context.config.style_edition() >= StyleEdition::Edition2024 {
2613            if params_last_line_contains_comment {
2614                result.push_str(&indent.to_string_with_newline(context.config));
2615                result.push(')');
2616                no_params_and_over_max_width = true;
2617            } else if closing_paren_overflow_max_width {
2618                result.push(')');
2619                result.push_str(&indent.to_string_with_newline(context.config));
2620                no_params_and_over_max_width = true;
2621            } else {
2622                result.push(')');
2623            }
2624        } else {
2625            if closing_paren_overflow_max_width || params_last_line_contains_comment {
2626                result.push_str(&indent.to_string_with_newline(context.config));
2627            }
2628            result.push(')');
2629        }
2630    }
2631
2632    // Return type.
2633    if let ast::FnRetTy::Ty(..) = fd.output {
2634        let ret_should_indent = match context.config.indent_style() {
2635            // If our params are block layout then we surely must have space.
2636            IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2637            _ if params_last_line_contains_comment => false,
2638            _ if result.contains('\n') || multi_line_ret_str => true,
2639            _ => {
2640                // If the return type would push over the max width, then put the return type on
2641                // a new line. With the +1 for the signature length an additional space between
2642                // the closing parenthesis of the param and the arrow '->' is considered.
2643                let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2644
2645                // If there is no where-clause, take into account the space after the return type
2646                // and the brace.
2647                if where_clause.predicates.is_empty() {
2648                    sig_length += 2;
2649                }
2650
2651                sig_length > context.config.max_width()
2652            }
2653        };
2654        let ret_shape = if ret_should_indent {
2655            if context.config.style_edition() <= StyleEdition::Edition2021
2656                || context.config.indent_style() == IndentStyle::Visual
2657            {
2658                let indent = if param_str.is_empty() {
2659                    // Aligning with nonexistent params looks silly.
2660                    force_new_line_for_brace = true;
2661                    indent + 4
2662                } else {
2663                    // FIXME: we might want to check that using the param indent
2664                    // doesn't blow our budget, and if it does, then fallback to
2665                    // the where-clause indent.
2666                    param_indent
2667                };
2668
2669                result.push_str(&indent.to_string_with_newline(context.config));
2670                Shape::indented(indent, context.config)
2671            } else {
2672                let mut ret_shape = Shape::indented(indent, context.config);
2673                if param_str.is_empty() {
2674                    // Aligning with nonexistent params looks silly.
2675                    force_new_line_for_brace = true;
2676                    ret_shape = if context.use_block_indent() {
2677                        ret_shape.offset_left_opt(4).unwrap_or(ret_shape)
2678                    } else {
2679                        ret_shape.indent = ret_shape.indent + 4;
2680                        ret_shape
2681                    };
2682                }
2683
2684                result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2685                ret_shape
2686            }
2687        } else {
2688            if context.config.style_edition() >= StyleEdition::Edition2024 {
2689                if !param_str.is_empty() || !no_params_and_over_max_width {
2690                    result.push(' ');
2691                }
2692            } else {
2693                result.push(' ');
2694            }
2695
2696            let ret_shape = Shape::indented(indent, context.config);
2697            ret_shape
2698                .offset_left_opt(last_line_width(&result))
2699                .unwrap_or(ret_shape)
2700        };
2701
2702        let exceeds_max_width = last_line_width(&result) + ret_str_len > context.config.max_width();
2703
2704        if multi_line_ret_str
2705            || ret_should_indent
2706            || (context.config.style_edition() >= StyleEdition::Edition2027 && exceeds_max_width)
2707        {
2708            // Now that we know the proper indent and width, we need to
2709            // re-layout the return type.
2710            let ret_str = fd.output.rewrite_result(context, ret_shape)?;
2711            result.push_str(&ret_str);
2712        } else {
2713            result.push_str(&ret_str);
2714        }
2715
2716        // Comment between return type and the end of the decl.
2717        let snippet_lo = fd.output.span().hi();
2718        if where_clause.predicates.is_empty() {
2719            let snippet_hi = span.hi();
2720            let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2721            // Try to preserve the layout of the original snippet.
2722            let original_starts_with_newline = snippet
2723                .find(|c| c != ' ')
2724                .map_or(false, |i| starts_with_newline(&snippet[i..]));
2725            let original_ends_with_newline = snippet
2726                .rfind(|c| c != ' ')
2727                .map_or(false, |i| snippet[i..].ends_with('\n'));
2728            let snippet = snippet.trim();
2729            if !snippet.is_empty() {
2730                result.push(if original_starts_with_newline {
2731                    '\n'
2732                } else {
2733                    ' '
2734                });
2735                result.push_str(snippet);
2736                if original_ends_with_newline {
2737                    force_new_line_for_brace = true;
2738                }
2739            }
2740        }
2741    }
2742
2743    let pos_before_where = match fd.output {
2744        ast::FnRetTy::Default(..) => params_span.hi(),
2745        ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
2746    };
2747
2748    let is_params_multi_lined = param_str.contains('\n');
2749
2750    let space = if put_params_in_block && ret_str.is_empty() {
2751        WhereClauseSpace::Space
2752    } else {
2753        WhereClauseSpace::Newline
2754    };
2755    let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2756    if is_params_multi_lined {
2757        option.veto_single_line();
2758    }
2759    let where_clause_str = rewrite_where_clause(
2760        context,
2761        &where_clause,
2762        context.config.brace_style(),
2763        Shape::indented(indent, context.config),
2764        true,
2765        "{",
2766        Some(span.hi()),
2767        pos_before_where,
2768        option,
2769    )?;
2770    // If there are neither where-clause nor return type, we may be missing comments between
2771    // params and `{`.
2772    if where_clause_str.is_empty() {
2773        if let ast::FnRetTy::Default(ret_span) = fd.output {
2774            match recover_missing_comment_in_span(
2775                // from after the closing paren to right before block or semicolon
2776                mk_sp(ret_span.lo(), span.hi()),
2777                shape,
2778                context,
2779                last_line_width(&result),
2780            ) {
2781                Ok(ref missing_comment) if !missing_comment.is_empty() => {
2782                    result.push_str(missing_comment);
2783                    force_new_line_for_brace = true;
2784                }
2785                _ => (),
2786            }
2787        }
2788    }
2789
2790    result.push_str(&where_clause_str);
2791
2792    let ends_with_comment = last_line_contains_single_line_comment(&result);
2793    force_new_line_for_brace |= ends_with_comment;
2794    force_new_line_for_brace |=
2795        is_params_multi_lined && context.config.where_single_line() && !where_clause_str.is_empty();
2796    Ok((result, ends_with_comment, force_new_line_for_brace))
2797}
2798
2799/// Kind of spaces to put before `where`.
2800#[derive(Copy, Clone)]
2801enum WhereClauseSpace {
2802    /// A single space.
2803    Space,
2804    /// A new line.
2805    Newline,
2806    /// Nothing.
2807    None,
2808}
2809
2810#[derive(Copy, Clone)]
2811struct WhereClauseOption {
2812    suppress_comma: bool, // Force no trailing comma
2813    snuggle: WhereClauseSpace,
2814    allow_single_line: bool, // Try single line where-clause instead of vertical layout
2815    veto_single_line: bool,  // Disallow a single-line where-clause.
2816}
2817
2818impl WhereClauseOption {
2819    fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2820        WhereClauseOption {
2821            suppress_comma,
2822            snuggle,
2823            allow_single_line: false,
2824            veto_single_line: false,
2825        }
2826    }
2827
2828    fn snuggled(current: &str) -> WhereClauseOption {
2829        WhereClauseOption {
2830            suppress_comma: false,
2831            snuggle: if last_line_width(current) == 1 {
2832                WhereClauseSpace::Space
2833            } else {
2834                WhereClauseSpace::Newline
2835            },
2836            allow_single_line: false,
2837            veto_single_line: false,
2838        }
2839    }
2840
2841    fn suppress_comma(&mut self) {
2842        self.suppress_comma = true
2843    }
2844
2845    fn allow_single_line(&mut self) {
2846        self.allow_single_line = true
2847    }
2848
2849    fn snuggle(&mut self) {
2850        self.snuggle = WhereClauseSpace::Space
2851    }
2852
2853    fn veto_single_line(&mut self) {
2854        self.veto_single_line = true;
2855    }
2856}
2857
2858fn rewrite_params(
2859    context: &RewriteContext<'_>,
2860    params: &[ast::Param],
2861    one_line_budget: usize,
2862    multi_line_budget: usize,
2863    indent: Indent,
2864    param_indent: Indent,
2865    span: Span,
2866    variadic: bool,
2867) -> RewriteResult {
2868    if params.is_empty() {
2869        let comment = context
2870            .snippet(mk_sp(
2871                span.lo(),
2872                // to remove ')'
2873                span.hi() - BytePos(1),
2874            ))
2875            .trim();
2876        return Ok(comment.to_owned());
2877    }
2878    let param_items: Vec<_> = itemize_list(
2879        context.snippet_provider,
2880        params.iter(),
2881        ")",
2882        ",",
2883        |param| span_lo_for_param(param),
2884        |param| param.ty.span.hi(),
2885        |param| {
2886            param
2887                .rewrite_result(context, Shape::legacy(multi_line_budget, param_indent))
2888                .or_else(|_| Ok(context.snippet(param.span()).to_owned()))
2889        },
2890        span.lo(),
2891        span.hi(),
2892        false,
2893    )
2894    .collect();
2895
2896    let tactic = definitive_tactic(
2897        &param_items,
2898        context
2899            .config
2900            .fn_params_layout()
2901            .to_list_tactic(context.config.style_edition(), param_items.len()),
2902        Separator::Comma,
2903        one_line_budget,
2904    );
2905    let budget = match tactic {
2906        DefinitiveListTactic::Horizontal => one_line_budget,
2907        _ => multi_line_budget,
2908    };
2909    let indent = match context.config.indent_style() {
2910        IndentStyle::Block => indent.block_indent(context.config),
2911        IndentStyle::Visual => param_indent,
2912    };
2913    let trailing_separator = if variadic {
2914        SeparatorTactic::Never
2915    } else {
2916        match context.config.indent_style() {
2917            IndentStyle::Block => context.config.trailing_comma(),
2918            IndentStyle::Visual => SeparatorTactic::Never,
2919        }
2920    };
2921    let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2922        .tactic(tactic)
2923        .trailing_separator(trailing_separator)
2924        .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2925        .preserve_newline(true);
2926    write_list(&param_items, &fmt)
2927}
2928
2929fn compute_budgets_for_params(
2930    context: &RewriteContext<'_>,
2931    result: &str,
2932    indent: Indent,
2933    ret_str_len: usize,
2934    fn_brace_style: FnBraceStyle,
2935    force_vertical_layout: bool,
2936) -> (usize, usize, Indent) {
2937    debug!(
2938        "compute_budgets_for_params {} {:?}, {}, {:?}",
2939        result.len(),
2940        indent,
2941        ret_str_len,
2942        fn_brace_style,
2943    );
2944    // Try keeping everything on the same line.
2945    if !result.contains('\n') && !force_vertical_layout {
2946        // 2 = `()`, 3 = `() `, space is before ret_string.
2947        let overhead = if ret_str_len == 0 { 2 } else { 3 };
2948        let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2949        match fn_brace_style {
2950            FnBraceStyle::None => used_space += 1,     // 1 = `;`
2951            FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2952            FnBraceStyle::NextLine => (),
2953        }
2954        let one_line_budget = context.budget(used_space);
2955
2956        if one_line_budget > 0 {
2957            // 4 = "() {".len()
2958            let (indent, multi_line_budget) = match context.config.indent_style() {
2959                IndentStyle::Block => {
2960                    let indent = indent.block_indent(context.config);
2961                    (indent, context.budget(indent.width() + 1))
2962                }
2963                IndentStyle::Visual => {
2964                    let indent = indent + result.len() + 1;
2965                    let multi_line_overhead = match fn_brace_style {
2966                        FnBraceStyle::SameLine => 4,
2967                        _ => 2,
2968                    } + indent.width();
2969                    (indent, context.budget(multi_line_overhead))
2970                }
2971            };
2972
2973            return (one_line_budget, multi_line_budget, indent);
2974        }
2975    }
2976
2977    // Didn't work. we must force vertical layout and put params on a newline.
2978    let new_indent = indent.block_indent(context.config);
2979    let used_space = match context.config.indent_style() {
2980        // 1 = `,`
2981        IndentStyle::Block => new_indent.width() + 1,
2982        // Account for `)` and possibly ` {`.
2983        IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2984    };
2985    (0, context.budget(used_space), new_indent)
2986}
2987
2988fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2989    let predicate_count = where_clause.predicates.len();
2990
2991    if config.where_single_line() && predicate_count == 1 {
2992        return FnBraceStyle::SameLine;
2993    }
2994    let brace_style = config.brace_style();
2995
2996    let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2997        || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2998    if use_next_line {
2999        FnBraceStyle::NextLine
3000    } else {
3001        FnBraceStyle::SameLine
3002    }
3003}
3004
3005fn rewrite_generics(
3006    context: &RewriteContext<'_>,
3007    ident: &str,
3008    generics: &ast::Generics,
3009    shape: Shape,
3010) -> RewriteResult {
3011    // FIXME: convert bounds to where-clauses where they get too big or if
3012    // there is a where-clause at all.
3013
3014    if generics.params.is_empty() {
3015        return Ok(ident.to_owned());
3016    }
3017
3018    let params = generics.params.iter();
3019    overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
3020}
3021
3022fn generics_shape_from_config(
3023    config: &Config,
3024    shape: Shape,
3025    offset: usize,
3026    span: Span,
3027) -> Result<Shape, ExceedsMaxWidthError> {
3028    match config.indent_style() {
3029        IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2, span),
3030        IndentStyle::Block => {
3031            // 1 = ","
3032            shape
3033                .block()
3034                .block_indent(config.tab_spaces())
3035                .with_max_width(config)
3036                .sub_width(1, span)
3037        }
3038    }
3039}
3040
3041fn rewrite_where_clause_rfc_style(
3042    context: &RewriteContext<'_>,
3043    predicates: &[ast::WherePredicate],
3044    where_span: Span,
3045    shape: Shape,
3046    terminator: &str,
3047    span_end: Option<BytePos>,
3048    span_end_before_where: BytePos,
3049    where_clause_option: WhereClauseOption,
3050) -> RewriteResult {
3051    let (where_keyword, allow_single_line) = rewrite_where_keyword(
3052        context,
3053        predicates,
3054        where_span,
3055        shape,
3056        span_end_before_where,
3057        where_clause_option,
3058    )?;
3059
3060    // 1 = `,`
3061    let clause_shape = shape
3062        .block()
3063        .with_max_width(context.config)
3064        .block_left(context.config.tab_spaces(), where_span)?
3065        .sub_width(1, where_span)?;
3066    let force_single_line = context.config.where_single_line()
3067        && predicates.len() == 1
3068        && !where_clause_option.veto_single_line;
3069
3070    let preds_str = rewrite_bounds_on_where_clause(
3071        context,
3072        predicates,
3073        clause_shape,
3074        terminator,
3075        span_end,
3076        where_clause_option,
3077        force_single_line,
3078    )?;
3079
3080    // 6 = `where `
3081    let clause_sep =
3082        if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
3083            || force_single_line
3084        {
3085            Cow::from(" ")
3086        } else {
3087            clause_shape.indent.to_string_with_newline(context.config)
3088        };
3089
3090    Ok(format!("{where_keyword}{clause_sep}{preds_str}"))
3091}
3092
3093/// Rewrite `where` and comment around it.
3094fn rewrite_where_keyword(
3095    context: &RewriteContext<'_>,
3096    predicates: &[ast::WherePredicate],
3097    where_span: Span,
3098    shape: Shape,
3099    span_end_before_where: BytePos,
3100    where_clause_option: WhereClauseOption,
3101) -> Result<(String, bool), RewriteError> {
3102    let block_shape = shape.block().with_max_width(context.config);
3103    // 1 = `,`
3104    let clause_shape = block_shape
3105        .block_left(context.config.tab_spaces(), where_span)?
3106        .sub_width(1, where_span)?;
3107
3108    let comment_separator = |comment: &str, shape: Shape| {
3109        if comment.is_empty() {
3110            Cow::from("")
3111        } else {
3112            shape.indent.to_string_with_newline(context.config)
3113        }
3114    };
3115
3116    let (span_before, span_after) =
3117        missing_span_before_after_where(span_end_before_where, predicates, where_span);
3118    let (comment_before, comment_after) =
3119        rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
3120
3121    let starting_newline = match where_clause_option.snuggle {
3122        WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
3123        WhereClauseSpace::None => Cow::from(""),
3124        _ => block_shape.indent.to_string_with_newline(context.config),
3125    };
3126
3127    let newline_before_where = comment_separator(&comment_before, shape);
3128    let newline_after_where = comment_separator(&comment_after, clause_shape);
3129    let result = format!(
3130        "{starting_newline}{comment_before}{newline_before_where}where\
3131{newline_after_where}{comment_after}"
3132    );
3133    let allow_single_line = where_clause_option.allow_single_line
3134        && comment_before.is_empty()
3135        && comment_after.is_empty();
3136
3137    Ok((result, allow_single_line))
3138}
3139
3140/// Rewrite bounds on a where clause.
3141fn rewrite_bounds_on_where_clause(
3142    context: &RewriteContext<'_>,
3143    predicates: &[ast::WherePredicate],
3144    shape: Shape,
3145    terminator: &str,
3146    span_end: Option<BytePos>,
3147    where_clause_option: WhereClauseOption,
3148    force_single_line: bool,
3149) -> RewriteResult {
3150    let span_start = predicates[0].span().lo();
3151    // If we don't have the start of the next span, then use the end of the
3152    // predicates, but that means we miss comments.
3153    let len = predicates.len();
3154    let end_of_preds = predicates[len - 1].span().hi();
3155    let span_end = span_end.unwrap_or(end_of_preds);
3156    let items = itemize_list(
3157        context.snippet_provider,
3158        predicates.iter(),
3159        terminator,
3160        ",",
3161        |pred| pred.span().lo(),
3162        |pred| pred.span().hi(),
3163        |pred| pred.rewrite_result(context, shape),
3164        span_start,
3165        span_end,
3166        false,
3167    );
3168    let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
3169        SeparatorTactic::Never
3170    } else {
3171        context.config.trailing_comma()
3172    };
3173
3174    // shape should be vertical only and only if we have `force_single_line` option enabled
3175    // and the number of items of the where-clause is equal to 1
3176    let shape_tactic = if force_single_line {
3177        DefinitiveListTactic::Horizontal
3178    } else {
3179        DefinitiveListTactic::Vertical
3180    };
3181
3182    let preserve_newline = context.config.style_edition() <= StyleEdition::Edition2021;
3183
3184    let fmt = ListFormatting::new(shape, context.config)
3185        .tactic(shape_tactic)
3186        .trailing_separator(comma_tactic)
3187        .preserve_newline(preserve_newline);
3188    write_list(&items.collect::<Vec<_>>(), &fmt)
3189}
3190
3191fn rewrite_where_clause(
3192    context: &RewriteContext<'_>,
3193    where_clause: &ast::WhereClause,
3194    brace_style: BraceStyle,
3195    shape: Shape,
3196    on_new_line: bool,
3197    terminator: &str,
3198    span_end: Option<BytePos>,
3199    span_end_before_where: BytePos,
3200    where_clause_option: WhereClauseOption,
3201) -> RewriteResult {
3202    let ast::WhereClause {
3203        ref predicates,
3204        span: where_span,
3205        has_where_token: _,
3206    } = *where_clause;
3207
3208    if predicates.is_empty() {
3209        return Ok(String::new());
3210    }
3211
3212    if context.config.indent_style() == IndentStyle::Block {
3213        return rewrite_where_clause_rfc_style(
3214            context,
3215            predicates,
3216            where_span,
3217            shape,
3218            terminator,
3219            span_end,
3220            span_end_before_where,
3221            where_clause_option,
3222        );
3223    }
3224
3225    let extra_indent = Indent::new(context.config.tab_spaces(), 0);
3226
3227    let offset = match context.config.indent_style() {
3228        IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
3229        // 6 = "where ".len()
3230        IndentStyle::Visual => shape.indent + extra_indent + 6,
3231    };
3232    // FIXME: if indent_style != Visual, then the budgets below might
3233    // be out by a char or two.
3234
3235    let budget = context.config.max_width() - offset.width();
3236    let span_start = predicates[0].span().lo();
3237    // If we don't have the start of the next span, then use the end of the
3238    // predicates, but that means we miss comments.
3239    let len = predicates.len();
3240    let end_of_preds = predicates[len - 1].span().hi();
3241    let span_end = span_end.unwrap_or(end_of_preds);
3242    let items = itemize_list(
3243        context.snippet_provider,
3244        predicates.iter(),
3245        terminator,
3246        ",",
3247        |pred| pred.span().lo(),
3248        |pred| pred.span().hi(),
3249        |pred| pred.rewrite_result(context, Shape::legacy(budget, offset)),
3250        span_start,
3251        span_end,
3252        false,
3253    );
3254    let item_vec = items.collect::<Vec<_>>();
3255    // FIXME: we don't need to collect here
3256    let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
3257
3258    let mut comma_tactic = context.config.trailing_comma();
3259    // Kind of a hack because we don't usually have trailing commas in where-clauses.
3260    if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
3261        comma_tactic = SeparatorTactic::Never;
3262    }
3263
3264    let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
3265        .tactic(tactic)
3266        .trailing_separator(comma_tactic)
3267        .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
3268        .preserve_newline(true);
3269    let preds_str = write_list(&item_vec, &fmt)?;
3270
3271    let end_length = if terminator == "{" {
3272        // If the brace is on the next line we don't need to count it otherwise it needs two
3273        // characters " {"
3274        match brace_style {
3275            BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
3276            BraceStyle::PreferSameLine => 2,
3277        }
3278    } else if terminator == "=" {
3279        2
3280    } else {
3281        terminator.len()
3282    };
3283    if on_new_line
3284        || preds_str.contains('\n')
3285        || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
3286    {
3287        Ok(format!(
3288            "\n{}where {}",
3289            (shape.indent + extra_indent).to_string(context.config),
3290            preds_str
3291        ))
3292    } else {
3293        Ok(format!(" where {preds_str}"))
3294    }
3295}
3296
3297fn missing_span_before_after_where(
3298    before_item_span_end: BytePos,
3299    predicates: &[ast::WherePredicate],
3300    where_span: Span,
3301) -> (Span, Span) {
3302    let missing_span_before = mk_sp(before_item_span_end, where_span.lo());
3303    // 5 = `where`
3304    let pos_after_where = where_span.lo() + BytePos(5);
3305    let missing_span_after = mk_sp(pos_after_where, predicates[0].span().lo());
3306    (missing_span_before, missing_span_after)
3307}
3308
3309fn rewrite_comments_before_after_where(
3310    context: &RewriteContext<'_>,
3311    span_before_where: Span,
3312    span_after_where: Span,
3313    shape: Shape,
3314) -> Result<(String, String), RewriteError> {
3315    let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
3316    let after_comment = rewrite_missing_comment(
3317        span_after_where,
3318        shape.block_indent(context.config.tab_spaces()),
3319        context,
3320    )?;
3321    Ok((before_comment, after_comment))
3322}
3323
3324fn format_header(
3325    context: &RewriteContext<'_>,
3326    item_name: &str,
3327    ident: symbol::Ident,
3328    vis: &ast::Visibility,
3329    offset: Indent,
3330) -> String {
3331    let mut result = String::with_capacity(128);
3332    let shape = Shape::indented(offset, context.config);
3333
3334    result.push_str(format_visibility(context, vis).trim());
3335
3336    // Check for a missing comment between the visibility and the item name.
3337    let after_vis = vis.span.hi();
3338    if let Some(before_item_name) = context
3339        .snippet_provider
3340        .opt_span_before(mk_sp(vis.span.lo(), ident.span.hi()), item_name.trim())
3341    {
3342        let missing_span = mk_sp(after_vis, before_item_name);
3343        if let Ok(result_with_comment) = combine_strs_with_missing_comments(
3344            context,
3345            &result,
3346            item_name,
3347            missing_span,
3348            shape,
3349            /* allow_extend */ true,
3350        ) {
3351            result = result_with_comment;
3352        }
3353    }
3354
3355    result.push_str(rewrite_ident(context, ident));
3356
3357    result
3358}
3359
3360#[derive(PartialEq, Eq, Clone, Copy)]
3361enum BracePos {
3362    None,
3363    Auto,
3364    ForceSameLine,
3365}
3366
3367fn format_generics(
3368    context: &RewriteContext<'_>,
3369    generics: &ast::Generics,
3370    brace_style: BraceStyle,
3371    brace_pos: BracePos,
3372    offset: Indent,
3373    span: Span,
3374    used_width: usize,
3375) -> Option<String> {
3376    let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
3377    let mut result = rewrite_generics(context, "", generics, shape).ok()?;
3378
3379    // If the generics are not parameterized then generics.span.hi() == 0,
3380    // so we use span.lo(), which is the position after `struct Foo`.
3381    let span_end_before_where = if !generics.params.is_empty() {
3382        generics.span.hi()
3383    } else {
3384        span.lo()
3385    };
3386    let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
3387        let budget = context.budget(last_line_used_width(&result, offset.width()));
3388        let mut option = WhereClauseOption::snuggled(&result);
3389        if brace_pos == BracePos::None {
3390            option.suppress_comma = true;
3391        }
3392        let where_clause_str = rewrite_where_clause(
3393            context,
3394            &generics.where_clause,
3395            brace_style,
3396            Shape::legacy(budget, offset.block_only()),
3397            true,
3398            "{",
3399            Some(span.hi()),
3400            span_end_before_where,
3401            option,
3402        )
3403        .ok()?;
3404        result.push_str(&where_clause_str);
3405        (
3406            brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
3407            // missed comments are taken care of in #rewrite_where_clause
3408            None,
3409        )
3410    } else {
3411        (
3412            brace_pos == BracePos::ForceSameLine
3413                || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
3414                    || brace_style != BraceStyle::AlwaysNextLine)
3415                || trimmed_last_line_width(&result) == 1,
3416            rewrite_missing_comment(
3417                mk_sp(
3418                    span_end_before_where,
3419                    if brace_pos == BracePos::None {
3420                        span.hi()
3421                    } else {
3422                        context.snippet_provider.span_before_last(span, "{")
3423                    },
3424                ),
3425                shape,
3426                context,
3427            )
3428            .ok(),
3429        )
3430    };
3431    // add missing comments
3432    let missed_line_comments = missed_comments
3433        .filter(|missed_comments| !missed_comments.is_empty())
3434        .map_or(false, |missed_comments| {
3435            let is_block = is_last_comment_block(&missed_comments);
3436            let sep = if is_block { " " } else { "\n" };
3437            result.push_str(sep);
3438            result.push_str(&missed_comments);
3439            !is_block
3440        });
3441    if brace_pos == BracePos::None {
3442        return Some(result);
3443    }
3444    let total_used_width = last_line_used_width(&result, used_width);
3445    let remaining_budget = context.budget(total_used_width);
3446    // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
3447    // and hence we take the closer into account as well for one line budget.
3448    // We assume that the closer has the same length as the opener.
3449    let overhead = if brace_pos == BracePos::ForceSameLine {
3450        // 3 = ` {}`
3451        3
3452    } else {
3453        // 2 = ` {`
3454        2
3455    };
3456    let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3457    if !forbid_same_line_brace && same_line_brace {
3458        result.push(' ');
3459    } else {
3460        result.push('\n');
3461        result.push_str(&offset.block_only().to_string(context.config));
3462    }
3463    result.push('{');
3464
3465    Some(result)
3466}
3467
3468impl Rewrite for ast::ForeignItem {
3469    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3470        self.rewrite_result(context, shape).ok()
3471    }
3472
3473    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
3474        let attrs_str = self.attrs.rewrite_result(context, shape)?;
3475        // Drop semicolon or it will be interpreted as comment.
3476        // FIXME: this may be a faulty span from libsyntax.
3477        let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3478
3479        let item_str = match self.kind {
3480            ast::ForeignItemKind::Fn(ref fn_kind) => {
3481                let ast::Fn {
3482                    defaultness,
3483                    ref sig,
3484                    ident,
3485                    ref generics,
3486                    ref body,
3487                    ..
3488                } = **fn_kind;
3489                if body.is_some() {
3490                    let mut visitor = FmtVisitor::from_context(context);
3491                    visitor.block_indent = shape.indent;
3492                    visitor.last_pos = self.span.lo();
3493                    let inner_attrs = inner_attributes(&self.attrs);
3494                    let fn_ctxt = visit::FnCtxt::Foreign;
3495                    visitor.visit_fn(
3496                        ident,
3497                        visit::FnKind::Fn(fn_ctxt, &self.vis, fn_kind),
3498                        &sig.decl,
3499                        self.span,
3500                        defaultness,
3501                        Some(&inner_attrs),
3502                    );
3503                    Ok(visitor.buffer.to_owned())
3504                } else {
3505                    rewrite_fn_base(
3506                        context,
3507                        shape.indent,
3508                        ident,
3509                        &FnSig::from_method_sig(sig, generics, &self.vis, defaultness),
3510                        span,
3511                        FnBraceStyle::None,
3512                    )
3513                    .map(|(s, _, _)| format!("{};", s))
3514                }
3515            }
3516            ast::ForeignItemKind::Static(ref static_foreign_item) => {
3517                // FIXME(#21): we're dropping potential comments in between the
3518                // function kw here.
3519                let vis = format_visibility(context, &self.vis);
3520                let safety = format_safety(static_foreign_item.safety);
3521                let mut_str = format_mutability(static_foreign_item.mutability);
3522                let prefix = format!(
3523                    "{}{}static {}{}:",
3524                    vis,
3525                    safety,
3526                    mut_str,
3527                    rewrite_ident(context, static_foreign_item.ident)
3528                );
3529                // 1 = ;
3530                rewrite_assign_rhs(
3531                    context,
3532                    prefix,
3533                    &static_foreign_item.ty,
3534                    &RhsAssignKind::Ty,
3535                    shape.sub_width(1, static_foreign_item.ty.span)?,
3536                )
3537                .map(|s| s + ";")
3538            }
3539            ast::ForeignItemKind::TyAlias(ref ty_alias) => {
3540                let kind = ItemVisitorKind::ForeignItem;
3541                rewrite_type_alias(ty_alias, &self.vis, context, shape.indent, kind, self.span)
3542            }
3543            ast::ForeignItemKind::MacCall(ref mac) => {
3544                rewrite_macro(mac, context, shape, MacroPosition::Item)
3545            }
3546        }?;
3547
3548        let missing_span = if self.attrs.is_empty() {
3549            mk_sp(self.span.lo(), self.span.lo())
3550        } else {
3551            mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3552        };
3553        combine_strs_with_missing_comments(
3554            context,
3555            &attrs_str,
3556            &item_str,
3557            missing_span,
3558            shape,
3559            false,
3560        )
3561    }
3562}
3563
3564/// Rewrite the attributes of an item.
3565fn rewrite_attrs(
3566    context: &RewriteContext<'_>,
3567    item: &ast::Item,
3568    item_str: &str,
3569    shape: Shape,
3570) -> RewriteResult {
3571    let attrs = filter_inline_attrs(&item.attrs, item.span());
3572    let attrs_str = attrs.rewrite_result(context, shape)?;
3573
3574    let missed_span = if attrs.is_empty() {
3575        mk_sp(item.span.lo(), item.span.lo())
3576    } else {
3577        mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3578    };
3579
3580    let allow_extend = if attrs.len() == 1 {
3581        let line_len = attrs_str.len() + 1 + item_str.len();
3582        !attrs.first().unwrap().is_doc_comment()
3583            && context.config.inline_attribute_width() >= line_len
3584    } else {
3585        false
3586    };
3587
3588    combine_strs_with_missing_comments(
3589        context,
3590        &attrs_str,
3591        item_str,
3592        missed_span,
3593        shape,
3594        allow_extend,
3595    )
3596}
3597
3598/// Rewrite an inline mod.
3599/// The given shape is used to format the mod's attributes.
3600pub(crate) fn rewrite_mod(
3601    context: &RewriteContext<'_>,
3602    item: &ast::Item,
3603    ident: Ident,
3604    attrs_shape: Shape,
3605) -> RewriteResult {
3606    let mut result = String::with_capacity(32);
3607    result.push_str(&*format_visibility(context, &item.vis));
3608    result.push_str("mod ");
3609    result.push_str(rewrite_ident(context, ident));
3610    result.push(';');
3611    rewrite_attrs(context, item, &result, attrs_shape)
3612}
3613
3614/// Rewrite `extern crate foo;`.
3615/// The given shape is used to format the extern crate's attributes.
3616pub(crate) fn rewrite_extern_crate(
3617    context: &RewriteContext<'_>,
3618    item: &ast::Item,
3619    attrs_shape: Shape,
3620) -> RewriteResult {
3621    assert!(is_extern_crate(item));
3622    let new_str = context.snippet(item.span);
3623    let item_str = if contains_comment(new_str) {
3624        new_str.to_owned()
3625    } else {
3626        let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3627        String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3628    };
3629    rewrite_attrs(context, item, &item_str, attrs_shape)
3630}
3631
3632/// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3633pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3634    !matches!(
3635        item.kind,
3636        ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::Yes, _))
3637    )
3638}
3639
3640pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3641    matches!(item.kind, ast::ItemKind::Use(_))
3642}
3643
3644pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3645    matches!(item.kind, ast::ItemKind::ExternCrate(..))
3646}