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