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