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::visit;
8use rustc_ast::{ast, ptr};
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: &[ptr::P<ast::AssocItem>]) {
729        if self.get_context().config.reorder_impl_items() {
730            type TyOpt = Option<ptr::P<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.predicates,
840        generics.where_clause.span,
841        context.config.brace_style(),
842        Shape::legacy(where_budget, offset.block_only()),
843        false,
844        "{",
845        where_span_end,
846        self_ty.span.hi(),
847        option,
848    )
849    .ok()?;
850
851    // If there is no where-clause, we may have missing comments between the trait name and
852    // the opening brace.
853    if generics.where_clause.predicates.is_empty() {
854        if let Some(hi) = where_span_end {
855            match recover_missing_comment_in_span(
856                mk_sp(self_ty.span.hi(), hi),
857                Shape::indented(offset, context.config),
858                context,
859                last_line_width(&result),
860            ) {
861                Ok(ref missing_comment) if !missing_comment.is_empty() => {
862                    result.push_str(missing_comment);
863                }
864                _ => (),
865            }
866        }
867    }
868
869    if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
870        result.push_str(&where_clause_str);
871        if where_clause_str.contains('\n') {
872            // If there is only one where-clause predicate
873            // and the where-clause spans multiple lines,
874            // then recover the suppressed comma in single line where-clause formatting
875            if generics.where_clause.predicates.len() == 1 {
876                result.push(',');
877            }
878        }
879        if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
880            result.push_str(&format!("{sep}{{{sep}}}"));
881        } else {
882            result.push_str(" {}");
883        }
884        return Some(result);
885    }
886
887    result.push_str(&where_clause_str);
888
889    let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
890    match context.config.brace_style() {
891        _ if need_newline => result.push_str(&sep),
892        BraceStyle::AlwaysNextLine => result.push_str(&sep),
893        BraceStyle::PreferSameLine => result.push(' '),
894        BraceStyle::SameLineWhere => {
895            if !where_clause_str.is_empty() {
896                result.push_str(&sep);
897            } else {
898                result.push(' ');
899            }
900        }
901    }
902
903    result.push('{');
904    // this is an impl body snippet(impl SampleImpl { /* here */ })
905    let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
906    let snippet = context.snippet(mk_sp(lo, item.span.hi()));
907    let open_pos = snippet.find_uncommented("{")? + 1;
908
909    if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
910        let mut visitor = FmtVisitor::from_context(context);
911        let item_indent = offset.block_only().block_indent(context.config);
912        visitor.block_indent = item_indent;
913        visitor.last_pos = lo + BytePos(open_pos as u32);
914
915        visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
916        visitor.visit_impl_items(items);
917
918        visitor.format_missing(item.span.hi() - BytePos(1));
919
920        let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
921        let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
922
923        result.push_str(&inner_indent_str);
924        result.push_str(visitor.buffer.trim());
925        result.push_str(&outer_indent_str);
926    } else if need_newline || !context.config.empty_item_single_line() {
927        result.push_str(&sep);
928    }
929
930    result.push('}');
931
932    Some(result)
933}
934
935fn is_impl_single_line(
936    context: &RewriteContext<'_>,
937    items: &[ptr::P<ast::AssocItem>],
938    result: &str,
939    where_clause_str: &str,
940    item: &ast::Item,
941) -> Option<bool> {
942    let snippet = context.snippet(item.span);
943    let open_pos = snippet.find_uncommented("{")? + 1;
944
945    Some(
946        context.config.empty_item_single_line()
947            && items.is_empty()
948            && !result.contains('\n')
949            && result.len() + where_clause_str.len() <= context.config.max_width()
950            && !contains_comment(&snippet[open_pos..]),
951    )
952}
953
954fn format_impl_ref_and_type(
955    context: &RewriteContext<'_>,
956    item: &ast::Item,
957    iimpl: &ast::Impl,
958    offset: Indent,
959) -> Option<String> {
960    let ast::Impl {
961        safety,
962        polarity,
963        defaultness,
964        constness,
965        ref generics,
966        of_trait: ref trait_ref,
967        ref self_ty,
968        ..
969    } = *iimpl;
970    let mut result = String::with_capacity(128);
971
972    result.push_str(&format_visibility(context, &item.vis));
973    result.push_str(format_defaultness(defaultness));
974    result.push_str(format_safety(safety));
975
976    let shape = if context.config.style_edition() >= StyleEdition::Edition2024 {
977        Shape::indented(offset + last_line_width(&result), context.config)
978    } else {
979        generics_shape_from_config(
980            context.config,
981            Shape::indented(offset + last_line_width(&result), context.config),
982            0,
983        )?
984    };
985    let generics_str = rewrite_generics(context, "impl", generics, shape).ok()?;
986    result.push_str(&generics_str);
987    result.push_str(format_constness_right(constness));
988
989    let polarity_str = match polarity {
990        ast::ImplPolarity::Negative(_) => "!",
991        ast::ImplPolarity::Positive => "",
992    };
993
994    let polarity_overhead;
995    let trait_ref_overhead;
996    if let Some(ref trait_ref) = *trait_ref {
997        let result_len = last_line_width(&result);
998        result.push_str(&rewrite_trait_ref(
999            context,
1000            trait_ref,
1001            offset,
1002            polarity_str,
1003            result_len,
1004        )?);
1005        polarity_overhead = 0; // already written
1006        trait_ref_overhead = " for".len();
1007    } else {
1008        polarity_overhead = polarity_str.len();
1009        trait_ref_overhead = 0;
1010    }
1011
1012    // Try to put the self type in a single line.
1013    let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
1014        // If there is no where-clause adapt budget for type formatting to take space and curly
1015        // brace into account.
1016        match context.config.brace_style() {
1017            BraceStyle::AlwaysNextLine => 0,
1018            _ => 2,
1019        }
1020    } else {
1021        0
1022    };
1023    let used_space =
1024        last_line_width(&result) + polarity_overhead + trait_ref_overhead + curly_brace_overhead;
1025    // 1 = space before the type.
1026    let budget = context.budget(used_space + 1);
1027    if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
1028        if !self_ty_str.contains('\n') {
1029            if trait_ref.is_some() {
1030                result.push_str(" for ");
1031            } else {
1032                result.push(' ');
1033                result.push_str(polarity_str);
1034            }
1035            result.push_str(&self_ty_str);
1036            return Some(result);
1037        }
1038    }
1039
1040    // Couldn't fit the self type on a single line, put it on a new line.
1041    result.push('\n');
1042    // Add indentation of one additional tab.
1043    let new_line_offset = offset.block_indent(context.config);
1044    result.push_str(&new_line_offset.to_string(context.config));
1045    if trait_ref.is_some() {
1046        result.push_str("for ");
1047    } else {
1048        result.push_str(polarity_str);
1049    }
1050    let budget = context.budget(last_line_width(&result) + polarity_overhead);
1051    let type_offset = match context.config.indent_style() {
1052        IndentStyle::Visual => new_line_offset + trait_ref_overhead,
1053        IndentStyle::Block => new_line_offset,
1054    };
1055    result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
1056    Some(result)
1057}
1058
1059fn rewrite_trait_ref(
1060    context: &RewriteContext<'_>,
1061    trait_ref: &ast::TraitRef,
1062    offset: Indent,
1063    polarity_str: &str,
1064    result_len: usize,
1065) -> Option<String> {
1066    // 1 = space between generics and trait_ref
1067    let used_space = 1 + polarity_str.len() + result_len;
1068    let shape = Shape::indented(offset + used_space, context.config);
1069    if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
1070        if !trait_ref_str.contains('\n') {
1071            return Some(format!(" {polarity_str}{trait_ref_str}"));
1072        }
1073    }
1074    // We could not make enough space for trait_ref, so put it on new line.
1075    let offset = offset.block_indent(context.config);
1076    let shape = Shape::indented(offset, context.config);
1077    let trait_ref_str = trait_ref.rewrite(context, shape)?;
1078    Some(format!(
1079        "{}{}{}",
1080        offset.to_string_with_newline(context.config),
1081        polarity_str,
1082        trait_ref_str
1083    ))
1084}
1085
1086pub(crate) struct StructParts<'a> {
1087    prefix: &'a str,
1088    ident: symbol::Ident,
1089    vis: &'a ast::Visibility,
1090    def: &'a ast::VariantData,
1091    generics: Option<&'a ast::Generics>,
1092    span: Span,
1093}
1094
1095impl<'a> StructParts<'a> {
1096    fn format_header(&self, context: &RewriteContext<'_>, offset: Indent) -> String {
1097        format_header(context, self.prefix, self.ident, self.vis, offset)
1098    }
1099
1100    fn from_variant(variant: &'a ast::Variant, context: &RewriteContext<'_>) -> Self {
1101        StructParts {
1102            prefix: "",
1103            ident: variant.ident,
1104            vis: &DEFAULT_VISIBILITY,
1105            def: &variant.data,
1106            generics: None,
1107            span: enum_variant_span(variant, context),
1108        }
1109    }
1110
1111    pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1112        let (prefix, def, ident, generics) = match item.kind {
1113            ast::ItemKind::Struct(ident, ref generics, ref def) => {
1114                ("struct ", def, ident, generics)
1115            }
1116            ast::ItemKind::Union(ident, ref generics, ref def) => ("union ", def, ident, generics),
1117            _ => unreachable!(),
1118        };
1119        StructParts {
1120            prefix,
1121            ident,
1122            vis: &item.vis,
1123            def,
1124            generics: Some(generics),
1125            span: item.span,
1126        }
1127    }
1128}
1129
1130fn enum_variant_span(variant: &ast::Variant, context: &RewriteContext<'_>) -> Span {
1131    use ast::VariantData::*;
1132    if let Some(ref anon_const) = variant.disr_expr {
1133        let span_before_consts = variant.span.until(anon_const.value.span);
1134        let hi = match &variant.data {
1135            Struct { .. } => context
1136                .snippet_provider
1137                .span_after_last(span_before_consts, "}"),
1138            Tuple(..) => context
1139                .snippet_provider
1140                .span_after_last(span_before_consts, ")"),
1141            Unit(..) => variant.ident.span.hi(),
1142        };
1143        mk_sp(span_before_consts.lo(), hi)
1144    } else {
1145        variant.span
1146    }
1147}
1148
1149fn format_struct(
1150    context: &RewriteContext<'_>,
1151    struct_parts: &StructParts<'_>,
1152    offset: Indent,
1153    one_line_width: Option<usize>,
1154) -> Option<String> {
1155    match struct_parts.def {
1156        ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
1157        ast::VariantData::Tuple(fields, _) => {
1158            format_tuple_struct(context, struct_parts, fields, offset)
1159        }
1160        ast::VariantData::Struct { fields, .. } => {
1161            format_struct_struct(context, struct_parts, fields, offset, one_line_width)
1162        }
1163    }
1164}
1165
1166pub(crate) fn format_trait(
1167    context: &RewriteContext<'_>,
1168    item: &ast::Item,
1169    offset: Indent,
1170) -> Option<String> {
1171    let ast::ItemKind::Trait(trait_kind) = &item.kind else {
1172        unreachable!();
1173    };
1174    let ast::Trait {
1175        is_auto,
1176        safety,
1177        ident,
1178        ref generics,
1179        ref bounds,
1180        ref items,
1181    } = **trait_kind;
1182
1183    let mut result = String::with_capacity(128);
1184    let header = format!(
1185        "{}{}{}trait ",
1186        format_visibility(context, &item.vis),
1187        format_safety(safety),
1188        format_auto(is_auto),
1189    );
1190    result.push_str(&header);
1191
1192    let body_lo = context.snippet_provider.span_after(item.span, "{");
1193
1194    let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
1195    let generics_str =
1196        rewrite_generics(context, rewrite_ident(context, ident), generics, shape).ok()?;
1197    result.push_str(&generics_str);
1198
1199    // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
1200    if !bounds.is_empty() {
1201        // Retrieve *unnormalized* ident (See #6069)
1202        let source_ident = context.snippet(ident.span);
1203        let ident_hi = context.snippet_provider.span_after(item.span, source_ident);
1204        let bound_hi = bounds.last().unwrap().span().hi();
1205        let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1206        if contains_comment(snippet) {
1207            return None;
1208        }
1209
1210        result = rewrite_assign_rhs_with(
1211            context,
1212            result + ":",
1213            bounds,
1214            shape,
1215            &RhsAssignKind::Bounds,
1216            RhsTactics::ForceNextLineWithoutIndent,
1217        )
1218        .ok()?;
1219    }
1220
1221    // Rewrite where-clause.
1222    if !generics.where_clause.predicates.is_empty() {
1223        let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1224
1225        let where_budget = context.budget(last_line_width(&result));
1226        let pos_before_where = if bounds.is_empty() {
1227            generics.where_clause.span.lo()
1228        } else {
1229            bounds[bounds.len() - 1].span().hi()
1230        };
1231        let option = WhereClauseOption::snuggled(&generics_str);
1232        let where_clause_str = rewrite_where_clause(
1233            context,
1234            &generics.where_clause.predicates,
1235            generics.where_clause.span,
1236            context.config.brace_style(),
1237            Shape::legacy(where_budget, offset.block_only()),
1238            where_on_new_line,
1239            "{",
1240            None,
1241            pos_before_where,
1242            option,
1243        )
1244        .ok()?;
1245        // If the where-clause cannot fit on the same line,
1246        // put the where-clause on a new line
1247        if !where_clause_str.contains('\n')
1248            && last_line_width(&result) + where_clause_str.len() + offset.width()
1249                > context.config.comment_width()
1250        {
1251            let width = offset.block_indent + context.config.tab_spaces() - 1;
1252            let where_indent = Indent::new(0, width);
1253            result.push_str(&where_indent.to_string_with_newline(context.config));
1254        }
1255        result.push_str(&where_clause_str);
1256    } else {
1257        let item_snippet = context.snippet(item.span);
1258        if let Some(lo) = item_snippet.find('/') {
1259            // 1 = `{`
1260            let comment_hi = if generics.params.len() > 0 {
1261                generics.span.lo() - BytePos(1)
1262            } else {
1263                body_lo - BytePos(1)
1264            };
1265            let comment_lo = item.span.lo() + BytePos(lo as u32);
1266            if comment_lo < comment_hi {
1267                match recover_missing_comment_in_span(
1268                    mk_sp(comment_lo, comment_hi),
1269                    Shape::indented(offset, context.config),
1270                    context,
1271                    last_line_width(&result),
1272                ) {
1273                    Ok(ref missing_comment) if !missing_comment.is_empty() => {
1274                        result.push_str(missing_comment);
1275                    }
1276                    _ => (),
1277                }
1278            }
1279        }
1280    }
1281
1282    let block_span = mk_sp(generics.where_clause.span.hi(), item.span.hi());
1283    let snippet = context.snippet(block_span);
1284    let open_pos = snippet.find_uncommented("{")? + 1;
1285
1286    match context.config.brace_style() {
1287        _ if last_line_contains_single_line_comment(&result)
1288            || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1289        {
1290            result.push_str(&offset.to_string_with_newline(context.config));
1291        }
1292        _ if context.config.empty_item_single_line()
1293            && items.is_empty()
1294            && !result.contains('\n')
1295            && !contains_comment(&snippet[open_pos..]) =>
1296        {
1297            result.push_str(" {}");
1298            return Some(result);
1299        }
1300        BraceStyle::AlwaysNextLine => {
1301            result.push_str(&offset.to_string_with_newline(context.config));
1302        }
1303        BraceStyle::PreferSameLine => result.push(' '),
1304        BraceStyle::SameLineWhere => {
1305            if result.contains('\n')
1306                || (!generics.where_clause.predicates.is_empty() && !items.is_empty())
1307            {
1308                result.push_str(&offset.to_string_with_newline(context.config));
1309            } else {
1310                result.push(' ');
1311            }
1312        }
1313    }
1314    result.push('{');
1315
1316    let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1317
1318    if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
1319        let mut visitor = FmtVisitor::from_context(context);
1320        visitor.block_indent = offset.block_only().block_indent(context.config);
1321        visitor.last_pos = block_span.lo() + BytePos(open_pos as u32);
1322
1323        for item in items {
1324            visitor.visit_trait_item(item);
1325        }
1326
1327        visitor.format_missing(item.span.hi() - BytePos(1));
1328
1329        let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1330
1331        result.push_str(&inner_indent_str);
1332        result.push_str(visitor.buffer.trim());
1333        result.push_str(&outer_indent_str);
1334    } else if result.contains('\n') {
1335        result.push_str(&outer_indent_str);
1336    }
1337
1338    result.push('}');
1339    Some(result)
1340}
1341
1342pub(crate) struct TraitAliasBounds<'a> {
1343    generic_bounds: &'a ast::GenericBounds,
1344    generics: &'a ast::Generics,
1345}
1346
1347impl<'a> Rewrite for TraitAliasBounds<'a> {
1348    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1349        self.rewrite_result(context, shape).ok()
1350    }
1351
1352    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1353        let generic_bounds_str = self.generic_bounds.rewrite_result(context, shape)?;
1354
1355        let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1356        option.allow_single_line();
1357
1358        let where_str = rewrite_where_clause(
1359            context,
1360            &self.generics.where_clause.predicates,
1361            self.generics.where_clause.span,
1362            context.config.brace_style(),
1363            shape,
1364            false,
1365            ";",
1366            None,
1367            self.generics.where_clause.span.lo(),
1368            option,
1369        )?;
1370
1371        let fits_single_line = !generic_bounds_str.contains('\n')
1372            && !where_str.contains('\n')
1373            && generic_bounds_str.len() + where_str.len() < shape.width;
1374        let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1375            Cow::from("")
1376        } else if fits_single_line {
1377            Cow::from(" ")
1378        } else {
1379            shape.indent.to_string_with_newline(context.config)
1380        };
1381
1382        Ok(format!("{generic_bounds_str}{space}{where_str}"))
1383    }
1384}
1385
1386pub(crate) fn format_trait_alias(
1387    context: &RewriteContext<'_>,
1388    ident: symbol::Ident,
1389    vis: &ast::Visibility,
1390    generics: &ast::Generics,
1391    generic_bounds: &ast::GenericBounds,
1392    shape: Shape,
1393) -> Option<String> {
1394    let alias = rewrite_ident(context, ident);
1395    // 6 = "trait ", 2 = " ="
1396    let g_shape = shape.offset_left(6)?.sub_width(2)?;
1397    let generics_str = rewrite_generics(context, alias, generics, g_shape).ok()?;
1398    let vis_str = format_visibility(context, vis);
1399    let lhs = format!("{vis_str}trait {generics_str} =");
1400    // 1 = ";"
1401    let trait_alias_bounds = TraitAliasBounds {
1402        generic_bounds,
1403        generics,
1404    };
1405    rewrite_assign_rhs(
1406        context,
1407        lhs,
1408        &trait_alias_bounds,
1409        &RhsAssignKind::Bounds,
1410        shape.sub_width(1)?,
1411    )
1412    .map(|s| s + ";")
1413    .ok()
1414}
1415
1416fn format_unit_struct(
1417    context: &RewriteContext<'_>,
1418    p: &StructParts<'_>,
1419    offset: Indent,
1420) -> Option<String> {
1421    let header_str = format_header(context, p.prefix, p.ident, p.vis, offset);
1422    let generics_str = if let Some(generics) = p.generics {
1423        let hi = context.snippet_provider.span_before_last(p.span, ";");
1424        format_generics(
1425            context,
1426            generics,
1427            context.config.brace_style(),
1428            BracePos::None,
1429            offset,
1430            // make a span that starts right after `struct Foo`
1431            mk_sp(p.ident.span.hi(), hi),
1432            last_line_width(&header_str),
1433        )?
1434    } else {
1435        String::new()
1436    };
1437    Some(format!("{header_str}{generics_str};"))
1438}
1439
1440pub(crate) fn format_struct_struct(
1441    context: &RewriteContext<'_>,
1442    struct_parts: &StructParts<'_>,
1443    fields: &[ast::FieldDef],
1444    offset: Indent,
1445    one_line_width: Option<usize>,
1446) -> Option<String> {
1447    let mut result = String::with_capacity(1024);
1448    let span = struct_parts.span;
1449
1450    let header_str = struct_parts.format_header(context, offset);
1451    result.push_str(&header_str);
1452
1453    let header_hi = struct_parts.ident.span.hi();
1454    let body_lo = if let Some(generics) = struct_parts.generics {
1455        // Adjust the span to start at the end of the generic arguments before searching for the '{'
1456        let span = span.with_lo(generics.where_clause.span.hi());
1457        context.snippet_provider.span_after(span, "{")
1458    } else {
1459        context.snippet_provider.span_after(span, "{")
1460    };
1461
1462    let generics_str = match struct_parts.generics {
1463        Some(g) => format_generics(
1464            context,
1465            g,
1466            context.config.brace_style(),
1467            if fields.is_empty() {
1468                BracePos::ForceSameLine
1469            } else {
1470                BracePos::Auto
1471            },
1472            offset,
1473            // make a span that starts right after `struct Foo`
1474            mk_sp(header_hi, body_lo),
1475            last_line_width(&result),
1476        )?,
1477        None => {
1478            // 3 = ` {}`, 2 = ` {`.
1479            let overhead = if fields.is_empty() { 3 } else { 2 };
1480            if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1481                || context.config.max_width() < overhead + result.len()
1482            {
1483                format!("\n{}{{", offset.block_only().to_string(context.config))
1484            } else {
1485                " {".to_owned()
1486            }
1487        }
1488    };
1489    // 1 = `}`
1490    let overhead = if fields.is_empty() { 1 } else { 0 };
1491    let total_width = result.len() + generics_str.len() + overhead;
1492    if !generics_str.is_empty()
1493        && !generics_str.contains('\n')
1494        && total_width > context.config.max_width()
1495    {
1496        result.push('\n');
1497        result.push_str(&offset.to_string(context.config));
1498        result.push_str(generics_str.trim_start());
1499    } else {
1500        result.push_str(&generics_str);
1501    }
1502
1503    if fields.is_empty() {
1504        let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1505        format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1506        return Some(result);
1507    }
1508
1509    // 3 = ` ` and ` }`
1510    let one_line_budget = context.budget(result.len() + 3 + offset.width());
1511    let one_line_budget =
1512        one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1513
1514    let items_str = rewrite_with_alignment(
1515        fields,
1516        context,
1517        Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
1518        mk_sp(body_lo, span.hi()),
1519        one_line_budget,
1520    )?;
1521
1522    if !items_str.contains('\n')
1523        && !result.contains('\n')
1524        && items_str.len() <= one_line_budget
1525        && !last_line_contains_single_line_comment(&items_str)
1526    {
1527        Some(format!("{result} {items_str} }}"))
1528    } else {
1529        Some(format!(
1530            "{}\n{}{}\n{}}}",
1531            result,
1532            offset
1533                .block_indent(context.config)
1534                .to_string(context.config),
1535            items_str,
1536            offset.to_string(context.config)
1537        ))
1538    }
1539}
1540
1541fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1542    match vis.kind {
1543        ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1544        _ => default_span.lo(),
1545    }
1546}
1547
1548// Format tuple or struct without any fields. We need to make sure that the comments
1549// inside the delimiters are preserved.
1550fn format_empty_struct_or_tuple(
1551    context: &RewriteContext<'_>,
1552    span: Span,
1553    offset: Indent,
1554    result: &mut String,
1555    opener: &str,
1556    closer: &str,
1557) {
1558    // 3 = " {}" or "();"
1559    let used_width = last_line_used_width(result, offset.width()) + 3;
1560    if used_width > context.config.max_width() {
1561        result.push_str(&offset.to_string_with_newline(context.config))
1562    }
1563    result.push_str(opener);
1564
1565    // indented shape for proper indenting of multi-line comments
1566    let shape = Shape::indented(offset.block_indent(context.config), context.config);
1567    match rewrite_missing_comment(span, shape, context) {
1568        Ok(ref s) if s.is_empty() => (),
1569        Ok(ref s) => {
1570            let is_multi_line = !is_single_line(s);
1571            if is_multi_line || first_line_contains_single_line_comment(s) {
1572                let nested_indent_str = offset
1573                    .block_indent(context.config)
1574                    .to_string_with_newline(context.config);
1575                result.push_str(&nested_indent_str);
1576            }
1577            result.push_str(s);
1578            if is_multi_line || last_line_contains_single_line_comment(s) {
1579                result.push_str(&offset.to_string_with_newline(context.config));
1580            }
1581        }
1582        Err(_) => result.push_str(context.snippet(span)),
1583    }
1584    result.push_str(closer);
1585}
1586
1587fn format_tuple_struct(
1588    context: &RewriteContext<'_>,
1589    struct_parts: &StructParts<'_>,
1590    fields: &[ast::FieldDef],
1591    offset: Indent,
1592) -> Option<String> {
1593    let mut result = String::with_capacity(1024);
1594    let span = struct_parts.span;
1595
1596    let header_str = struct_parts.format_header(context, offset);
1597    result.push_str(&header_str);
1598
1599    let body_lo = if fields.is_empty() {
1600        let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1601        context
1602            .snippet_provider
1603            .span_after(mk_sp(lo, span.hi()), "(")
1604    } else {
1605        fields[0].span.lo()
1606    };
1607    let body_hi = if fields.is_empty() {
1608        context
1609            .snippet_provider
1610            .span_after(mk_sp(body_lo, span.hi()), ")")
1611    } else {
1612        // This is a dirty hack to work around a missing `)` from the span of the last field.
1613        let last_arg_span = fields[fields.len() - 1].span;
1614        context
1615            .snippet_provider
1616            .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1617            .unwrap_or_else(|| last_arg_span.hi())
1618    };
1619
1620    let where_clause_str = match struct_parts.generics {
1621        Some(generics) => {
1622            let budget = context.budget(last_line_width(&header_str));
1623            let shape = Shape::legacy(budget, offset);
1624            let generics_str = rewrite_generics(context, "", generics, shape).ok()?;
1625            result.push_str(&generics_str);
1626
1627            let where_budget = context.budget(last_line_width(&result));
1628            let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1629            rewrite_where_clause(
1630                context,
1631                &generics.where_clause.predicates,
1632                generics.where_clause.span,
1633                context.config.brace_style(),
1634                Shape::legacy(where_budget, offset.block_only()),
1635                false,
1636                ";",
1637                None,
1638                body_hi,
1639                option,
1640            )
1641            .ok()?
1642        }
1643        None => "".to_owned(),
1644    };
1645
1646    if fields.is_empty() {
1647        let body_hi = context
1648            .snippet_provider
1649            .span_before(mk_sp(body_lo, span.hi()), ")");
1650        let inner_span = mk_sp(body_lo, body_hi);
1651        format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1652    } else {
1653        let shape = Shape::indented(offset, context.config).sub_width(1)?;
1654        let lo = if let Some(generics) = struct_parts.generics {
1655            generics.span.hi()
1656        } else {
1657            struct_parts.ident.span.hi()
1658        };
1659        result = overflow::rewrite_with_parens(
1660            context,
1661            &result,
1662            fields.iter(),
1663            shape,
1664            mk_sp(lo, span.hi()),
1665            context.config.fn_call_width(),
1666            None,
1667        )
1668        .ok()?;
1669    }
1670
1671    if !where_clause_str.is_empty()
1672        && !where_clause_str.contains('\n')
1673        && (result.contains('\n')
1674            || offset.block_indent + result.len() + where_clause_str.len() + 1
1675                > context.config.max_width())
1676    {
1677        // We need to put the where-clause on a new line, but we didn't
1678        // know that earlier, so the where-clause will not be indented properly.
1679        result.push('\n');
1680        result.push_str(
1681            &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1682        );
1683    }
1684    result.push_str(&where_clause_str);
1685
1686    Some(result)
1687}
1688
1689#[derive(Clone, Copy)]
1690pub(crate) enum ItemVisitorKind {
1691    Item,
1692    AssocTraitItem,
1693    AssocImplItem,
1694    ForeignItem,
1695}
1696
1697struct TyAliasRewriteInfo<'c, 'g>(
1698    &'c RewriteContext<'c>,
1699    Indent,
1700    &'g ast::Generics,
1701    ast::TyAliasWhereClauses,
1702    symbol::Ident,
1703    Span,
1704);
1705
1706pub(crate) fn rewrite_type_alias<'a>(
1707    ty_alias_kind: &ast::TyAlias,
1708    vis: &ast::Visibility,
1709    context: &RewriteContext<'a>,
1710    indent: Indent,
1711    visitor_kind: ItemVisitorKind,
1712    span: Span,
1713) -> RewriteResult {
1714    use ItemVisitorKind::*;
1715
1716    let ast::TyAlias {
1717        defaultness,
1718        ident,
1719        ref generics,
1720        ref bounds,
1721        ref ty,
1722        where_clauses,
1723    } = *ty_alias_kind;
1724    let ty_opt = ty.as_ref();
1725    let rhs_hi = ty
1726        .as_ref()
1727        .map_or(where_clauses.before.span.hi(), |ty| ty.span.hi());
1728    let rw_info = &TyAliasRewriteInfo(context, indent, generics, where_clauses, ident, span);
1729    let op_ty = opaque_ty(ty);
1730    // Type Aliases are formatted slightly differently depending on the context
1731    // in which they appear, whether they are opaque, and whether they are associated.
1732    // https://rustc-dev-guide.rust-lang.org/opaque-types-type-alias-impl-trait.html
1733    // https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/items.md#type-aliases
1734    match (visitor_kind, &op_ty) {
1735        (Item | AssocTraitItem | ForeignItem, Some(op_bounds)) => {
1736            let op = OpaqueType { bounds: op_bounds };
1737            rewrite_ty(rw_info, Some(bounds), Some(&op), rhs_hi, vis)
1738        }
1739        (Item | AssocTraitItem | ForeignItem, None) => {
1740            rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis)
1741        }
1742        (AssocImplItem, _) => {
1743            let result = if let Some(op_bounds) = op_ty {
1744                let op = OpaqueType { bounds: op_bounds };
1745                rewrite_ty(
1746                    rw_info,
1747                    Some(bounds),
1748                    Some(&op),
1749                    rhs_hi,
1750                    &DEFAULT_VISIBILITY,
1751                )
1752            } else {
1753                rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis)
1754            }?;
1755            match defaultness {
1756                ast::Defaultness::Default(..) => Ok(format!("default {result}")),
1757                _ => Ok(result),
1758            }
1759        }
1760    }
1761}
1762
1763fn rewrite_ty<R: Rewrite>(
1764    rw_info: &TyAliasRewriteInfo<'_, '_>,
1765    generic_bounds_opt: Option<&ast::GenericBounds>,
1766    rhs: Option<&R>,
1767    // the span of the end of the RHS (or the end of the generics, if there is no RHS)
1768    rhs_hi: BytePos,
1769    vis: &ast::Visibility,
1770) -> RewriteResult {
1771    let mut result = String::with_capacity(128);
1772    let TyAliasRewriteInfo(context, indent, generics, where_clauses, ident, span) = *rw_info;
1773    let (before_where_predicates, after_where_predicates) = generics
1774        .where_clause
1775        .predicates
1776        .split_at(where_clauses.split);
1777    result.push_str(&format!("{}type ", format_visibility(context, vis)));
1778    let ident_str = rewrite_ident(context, ident);
1779
1780    if generics.params.is_empty() {
1781        result.push_str(ident_str)
1782    } else {
1783        // 2 = `= `
1784        let g_shape = Shape::indented(indent, context.config);
1785        let g_shape = g_shape
1786            .offset_left(result.len())
1787            .and_then(|s| s.sub_width(2))
1788            .max_width_error(g_shape.width, span)?;
1789        let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1790        result.push_str(&generics_str);
1791    }
1792
1793    if let Some(bounds) = generic_bounds_opt {
1794        if !bounds.is_empty() {
1795            // 2 = `: `
1796            let shape = Shape::indented(indent, context.config);
1797            let shape = shape
1798                .offset_left(result.len() + 2)
1799                .max_width_error(shape.width, span)?;
1800            let type_bounds = bounds
1801                .rewrite_result(context, shape)
1802                .map(|s| format!(": {}", s))?;
1803            result.push_str(&type_bounds);
1804        }
1805    }
1806
1807    let where_budget = context.budget(last_line_width(&result));
1808    let mut option = WhereClauseOption::snuggled(&result);
1809    if rhs.is_none() {
1810        option.suppress_comma();
1811    }
1812    let before_where_clause_str = rewrite_where_clause(
1813        context,
1814        before_where_predicates,
1815        where_clauses.before.span,
1816        context.config.brace_style(),
1817        Shape::legacy(where_budget, indent),
1818        false,
1819        "=",
1820        None,
1821        generics.span.hi(),
1822        option,
1823    )?;
1824    result.push_str(&before_where_clause_str);
1825
1826    let mut result = if let Some(ty) = rhs {
1827        // If there are any where clauses, add a newline before the assignment.
1828        // If there is a before where clause, do not indent, but if there is
1829        // only an after where clause, additionally indent the type.
1830        if !before_where_predicates.is_empty() {
1831            result.push_str(&indent.to_string_with_newline(context.config));
1832        } else if !after_where_predicates.is_empty() {
1833            result.push_str(
1834                &indent
1835                    .block_indent(context.config)
1836                    .to_string_with_newline(context.config),
1837            );
1838        } else {
1839            result.push(' ');
1840        }
1841
1842        let comment_span = context
1843            .snippet_provider
1844            .opt_span_before(span, "=")
1845            .map(|op_lo| mk_sp(where_clauses.before.span.hi(), op_lo));
1846
1847        let lhs = match comment_span {
1848            Some(comment_span)
1849                if contains_comment(
1850                    context
1851                        .snippet_provider
1852                        .span_to_snippet(comment_span)
1853                        .unknown_error()?,
1854                ) =>
1855            {
1856                let comment_shape = if !before_where_predicates.is_empty() {
1857                    Shape::indented(indent, context.config)
1858                } else {
1859                    let shape = Shape::indented(indent, context.config);
1860                    shape
1861                        .block_left(context.config.tab_spaces())
1862                        .max_width_error(shape.width, span)?
1863                };
1864
1865                combine_strs_with_missing_comments(
1866                    context,
1867                    result.trim_end(),
1868                    "=",
1869                    comment_span,
1870                    comment_shape,
1871                    true,
1872                )?
1873            }
1874            _ => format!("{result}="),
1875        };
1876
1877        // 1 = `;` unless there's a trailing where clause
1878        let shape = Shape::indented(indent, context.config);
1879        let shape = if after_where_predicates.is_empty() {
1880            Shape::indented(indent, context.config)
1881                .sub_width(1)
1882                .max_width_error(shape.width, span)?
1883        } else {
1884            shape
1885        };
1886        rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape)?
1887    } else {
1888        result
1889    };
1890
1891    if !after_where_predicates.is_empty() {
1892        let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1893        let after_where_clause_str = rewrite_where_clause(
1894            context,
1895            after_where_predicates,
1896            where_clauses.after.span,
1897            context.config.brace_style(),
1898            Shape::indented(indent, context.config),
1899            false,
1900            ";",
1901            None,
1902            rhs_hi,
1903            option,
1904        )?;
1905        result.push_str(&after_where_clause_str);
1906    }
1907
1908    result += ";";
1909    Ok(result)
1910}
1911
1912fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1913    (
1914        if config.space_before_colon() { " " } else { "" },
1915        if config.space_after_colon() { " " } else { "" },
1916    )
1917}
1918
1919pub(crate) fn rewrite_struct_field_prefix(
1920    context: &RewriteContext<'_>,
1921    field: &ast::FieldDef,
1922) -> RewriteResult {
1923    let vis = format_visibility(context, &field.vis);
1924    let safety = format_safety(field.safety);
1925    let type_annotation_spacing = type_annotation_spacing(context.config);
1926    Ok(match field.ident {
1927        Some(name) => format!(
1928            "{vis}{safety}{}{}:",
1929            rewrite_ident(context, name),
1930            type_annotation_spacing.0
1931        ),
1932        None => format!("{vis}{safety}"),
1933    })
1934}
1935
1936impl Rewrite for ast::FieldDef {
1937    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1938        self.rewrite_result(context, shape).ok()
1939    }
1940
1941    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1942        rewrite_struct_field(context, self, shape, 0)
1943    }
1944}
1945
1946pub(crate) fn rewrite_struct_field(
1947    context: &RewriteContext<'_>,
1948    field: &ast::FieldDef,
1949    shape: Shape,
1950    lhs_max_width: usize,
1951) -> RewriteResult {
1952    // FIXME(default_field_values): Implement formatting.
1953    if field.default.is_some() {
1954        return Err(RewriteError::Unknown);
1955    }
1956
1957    if contains_skip(&field.attrs) {
1958        return Ok(context.snippet(field.span()).to_owned());
1959    }
1960
1961    let type_annotation_spacing = type_annotation_spacing(context.config);
1962    let prefix = rewrite_struct_field_prefix(context, field)?;
1963
1964    let attrs_str = field.attrs.rewrite_result(context, shape)?;
1965    let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1966    let missing_span = if field.attrs.is_empty() {
1967        mk_sp(field.span.lo(), field.span.lo())
1968    } else {
1969        mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1970    };
1971    let mut spacing = String::from(if field.ident.is_some() {
1972        type_annotation_spacing.1
1973    } else {
1974        ""
1975    });
1976    // Try to put everything on a single line.
1977    let attr_prefix = combine_strs_with_missing_comments(
1978        context,
1979        &attrs_str,
1980        &prefix,
1981        missing_span,
1982        shape,
1983        attrs_extendable,
1984    )?;
1985    let overhead = trimmed_last_line_width(&attr_prefix);
1986    let lhs_offset = lhs_max_width.saturating_sub(overhead);
1987    for _ in 0..lhs_offset {
1988        spacing.push(' ');
1989    }
1990    // In this extreme case we will be missing a space between an attribute and a field.
1991    if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1992        spacing.push(' ');
1993    }
1994
1995    let orig_ty = shape
1996        .offset_left(overhead + spacing.len())
1997        .and_then(|ty_shape| field.ty.rewrite_result(context, ty_shape).ok());
1998
1999    if let Some(ref ty) = orig_ty {
2000        if !ty.contains('\n') && !contains_comment(context.snippet(missing_span)) {
2001            return Ok(attr_prefix + &spacing + ty);
2002        }
2003    }
2004
2005    let is_prefix_empty = prefix.is_empty();
2006    // We must use multiline. We are going to put attributes and a field on different lines.
2007    let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, &RhsAssignKind::Ty, shape)?;
2008    // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
2009    let field_str = if is_prefix_empty {
2010        field_str.trim_start()
2011    } else {
2012        &field_str
2013    };
2014    combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
2015}
2016
2017pub(crate) struct StaticParts<'a> {
2018    prefix: &'a str,
2019    safety: ast::Safety,
2020    vis: &'a ast::Visibility,
2021    ident: symbol::Ident,
2022    generics: Option<&'a ast::Generics>,
2023    ty: &'a ast::Ty,
2024    mutability: ast::Mutability,
2025    expr_opt: Option<&'a ptr::P<ast::Expr>>,
2026    defaultness: Option<ast::Defaultness>,
2027    span: Span,
2028}
2029
2030impl<'a> StaticParts<'a> {
2031    pub(crate) fn from_item(item: &'a ast::Item) -> Self {
2032        let (defaultness, prefix, safety, ident, ty, mutability, expr, generics) = match &item.kind
2033        {
2034            ast::ItemKind::Static(s) => (
2035                None,
2036                "static",
2037                s.safety,
2038                s.ident,
2039                &s.ty,
2040                s.mutability,
2041                &s.expr,
2042                None,
2043            ),
2044            ast::ItemKind::Const(c) => (
2045                Some(c.defaultness),
2046                "const",
2047                ast::Safety::Default,
2048                c.ident,
2049                &c.ty,
2050                ast::Mutability::Not,
2051                &c.expr,
2052                Some(&c.generics),
2053            ),
2054            _ => unreachable!(),
2055        };
2056        StaticParts {
2057            prefix,
2058            safety,
2059            vis: &item.vis,
2060            ident,
2061            generics,
2062            ty,
2063            mutability,
2064            expr_opt: expr.as_ref(),
2065            defaultness,
2066            span: item.span,
2067        }
2068    }
2069
2070    pub(crate) fn from_trait_item(ti: &'a ast::AssocItem, ident: Ident) -> Self {
2071        let (defaultness, ty, expr_opt, generics) = match &ti.kind {
2072            ast::AssocItemKind::Const(c) => (c.defaultness, &c.ty, &c.expr, Some(&c.generics)),
2073            _ => unreachable!(),
2074        };
2075        StaticParts {
2076            prefix: "const",
2077            safety: ast::Safety::Default,
2078            vis: &ti.vis,
2079            ident,
2080            generics,
2081            ty,
2082            mutability: ast::Mutability::Not,
2083            expr_opt: expr_opt.as_ref(),
2084            defaultness: Some(defaultness),
2085            span: ti.span,
2086        }
2087    }
2088
2089    pub(crate) fn from_impl_item(ii: &'a ast::AssocItem, ident: Ident) -> Self {
2090        let (defaultness, ty, expr, generics) = match &ii.kind {
2091            ast::AssocItemKind::Const(c) => (c.defaultness, &c.ty, &c.expr, Some(&c.generics)),
2092            _ => unreachable!(),
2093        };
2094        StaticParts {
2095            prefix: "const",
2096            safety: ast::Safety::Default,
2097            vis: &ii.vis,
2098            ident,
2099            generics,
2100            ty,
2101            mutability: ast::Mutability::Not,
2102            expr_opt: expr.as_ref(),
2103            defaultness: Some(defaultness),
2104            span: ii.span,
2105        }
2106    }
2107}
2108
2109fn rewrite_static(
2110    context: &RewriteContext<'_>,
2111    static_parts: &StaticParts<'_>,
2112    offset: Indent,
2113) -> Option<String> {
2114    // For now, if this static (or const) has generics, then bail.
2115    if static_parts
2116        .generics
2117        .is_some_and(|g| !g.params.is_empty() || !g.where_clause.is_empty())
2118    {
2119        return None;
2120    }
2121
2122    let colon = colon_spaces(context.config);
2123    let mut prefix = format!(
2124        "{}{}{}{} {}{}{}",
2125        format_visibility(context, static_parts.vis),
2126        static_parts.defaultness.map_or("", format_defaultness),
2127        format_safety(static_parts.safety),
2128        static_parts.prefix,
2129        format_mutability(static_parts.mutability),
2130        rewrite_ident(context, static_parts.ident),
2131        colon,
2132    );
2133    // 2 = " =".len()
2134    let ty_shape =
2135        Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
2136    let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
2137        Some(ty_str) => ty_str,
2138        None => {
2139            if prefix.ends_with(' ') {
2140                prefix.pop();
2141            }
2142            let nested_indent = offset.block_indent(context.config);
2143            let nested_shape = Shape::indented(nested_indent, context.config);
2144            let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
2145            format!(
2146                "{}{}",
2147                nested_indent.to_string_with_newline(context.config),
2148                ty_str
2149            )
2150        }
2151    };
2152
2153    if let Some(expr) = static_parts.expr_opt {
2154        let comments_lo = context.snippet_provider.span_after(static_parts.span, "=");
2155        let expr_lo = expr.span.lo();
2156        let comments_span = mk_sp(comments_lo, expr_lo);
2157
2158        let lhs = format!("{prefix}{ty_str} =");
2159
2160        // 1 = ;
2161        let remaining_width = context.budget(offset.block_indent + 1);
2162        rewrite_assign_rhs_with_comments(
2163            context,
2164            &lhs,
2165            &**expr,
2166            Shape::legacy(remaining_width, offset.block_only()),
2167            &RhsAssignKind::Expr(&expr.kind, expr.span),
2168            RhsTactics::Default,
2169            comments_span,
2170            true,
2171        )
2172        .ok()
2173        .map(|res| recover_comment_removed(res, static_parts.span, context))
2174        .map(|s| if s.ends_with(';') { s } else { s + ";" })
2175    } else {
2176        Some(format!("{prefix}{ty_str};"))
2177    }
2178}
2179
2180// FIXME(calebcartwright) - This is a hack around a bug in the handling of TyKind::ImplTrait.
2181// This should be removed once that bug is resolved, with the type alias formatting using the
2182// defined Ty for the RHS directly.
2183// https://github.com/rust-lang/rustfmt/issues/4373
2184// https://github.com/rust-lang/rustfmt/issues/5027
2185struct OpaqueType<'a> {
2186    bounds: &'a ast::GenericBounds,
2187}
2188
2189impl<'a> Rewrite for OpaqueType<'a> {
2190    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2191        let shape = shape.offset_left(5)?; // `impl `
2192        self.bounds
2193            .rewrite(context, shape)
2194            .map(|s| format!("impl {}", s))
2195    }
2196}
2197
2198impl Rewrite for ast::FnRetTy {
2199    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2200        self.rewrite_result(context, shape).ok()
2201    }
2202
2203    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2204        match *self {
2205            ast::FnRetTy::Default(_) => Ok(String::new()),
2206            ast::FnRetTy::Ty(ref ty) => {
2207                let arrow_width = "-> ".len();
2208                if context.config.style_edition() <= StyleEdition::Edition2021
2209                    || context.config.indent_style() == IndentStyle::Visual
2210                {
2211                    let inner_width = shape
2212                        .width
2213                        .checked_sub(arrow_width)
2214                        .max_width_error(shape.width, self.span())?;
2215                    return ty
2216                        .rewrite_result(
2217                            context,
2218                            Shape::legacy(inner_width, shape.indent + arrow_width),
2219                        )
2220                        .map(|r| format!("-> {}", r));
2221                }
2222
2223                let shape = shape
2224                    .offset_left(arrow_width)
2225                    .max_width_error(shape.width, self.span())?;
2226
2227                ty.rewrite_result(context, shape)
2228                    .map(|s| format!("-> {}", s))
2229            }
2230        }
2231    }
2232}
2233
2234fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
2235    match ty.kind {
2236        ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
2237        _ => false,
2238    }
2239}
2240
2241/// Recover any missing comments between the param and the type.
2242///
2243/// # Returns
2244///
2245/// A 2-len tuple with the comment before the colon in first position, and the comment after the
2246/// colon in second position.
2247fn get_missing_param_comments(
2248    context: &RewriteContext<'_>,
2249    pat_span: Span,
2250    ty_span: Span,
2251    shape: Shape,
2252) -> (String, String) {
2253    let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
2254
2255    let span_before_colon = {
2256        let missing_comment_span_hi = context
2257            .snippet_provider
2258            .span_before(missing_comment_span, ":");
2259        mk_sp(pat_span.hi(), missing_comment_span_hi)
2260    };
2261    let span_after_colon = {
2262        let missing_comment_span_lo = context
2263            .snippet_provider
2264            .span_after(missing_comment_span, ":");
2265        mk_sp(missing_comment_span_lo, ty_span.lo())
2266    };
2267
2268    let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
2269        .ok()
2270        .filter(|comment| !comment.is_empty())
2271        .map_or(String::new(), |comment| format!(" {}", comment));
2272    let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
2273        .ok()
2274        .filter(|comment| !comment.is_empty())
2275        .map_or(String::new(), |comment| format!("{} ", comment));
2276    (comment_before_colon, comment_after_colon)
2277}
2278
2279impl Rewrite for ast::Param {
2280    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2281        self.rewrite_result(context, shape).ok()
2282    }
2283
2284    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2285        let param_attrs_result = self
2286            .attrs
2287            .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2288        // N.B. Doc comments aren't typically valid syntax, but could appear
2289        // in the presence of certain macros - https://github.com/rust-lang/rustfmt/issues/4936
2290        let (span, has_multiple_attr_lines, has_doc_comments) = if !self.attrs.is_empty() {
2291            let num_attrs = self.attrs.len();
2292            (
2293                mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
2294                param_attrs_result.contains('\n'),
2295                self.attrs.iter().any(|a| a.is_doc_comment()),
2296            )
2297        } else {
2298            (mk_sp(self.span.lo(), self.span.lo()), false, false)
2299        };
2300
2301        if let Some(ref explicit_self) = self.to_self() {
2302            rewrite_explicit_self(
2303                context,
2304                explicit_self,
2305                &param_attrs_result,
2306                span,
2307                shape,
2308                has_multiple_attr_lines,
2309            )
2310        } else if is_named_param(self) {
2311            let param_name = &self
2312                .pat
2313                .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2314            let mut result = combine_strs_with_missing_comments(
2315                context,
2316                &param_attrs_result,
2317                param_name,
2318                span,
2319                shape,
2320                !has_multiple_attr_lines && !has_doc_comments,
2321            )?;
2322
2323            if !is_empty_infer(&*self.ty, self.pat.span) {
2324                let (before_comment, after_comment) =
2325                    get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
2326                result.push_str(&before_comment);
2327                result.push_str(colon_spaces(context.config));
2328                result.push_str(&after_comment);
2329                let overhead = last_line_width(&result);
2330                let max_width = shape
2331                    .width
2332                    .checked_sub(overhead)
2333                    .max_width_error(shape.width, self.span())?;
2334                if let Ok(ty_str) = self
2335                    .ty
2336                    .rewrite_result(context, Shape::legacy(max_width, shape.indent))
2337                {
2338                    result.push_str(&ty_str);
2339                } else {
2340                    let prev_str = if param_attrs_result.is_empty() {
2341                        param_attrs_result
2342                    } else {
2343                        param_attrs_result + &shape.to_string_with_newline(context.config)
2344                    };
2345
2346                    result = combine_strs_with_missing_comments(
2347                        context,
2348                        &prev_str,
2349                        param_name,
2350                        span,
2351                        shape,
2352                        !has_multiple_attr_lines,
2353                    )?;
2354                    result.push_str(&before_comment);
2355                    result.push_str(colon_spaces(context.config));
2356                    result.push_str(&after_comment);
2357                    let overhead = last_line_width(&result);
2358                    let max_width = shape
2359                        .width
2360                        .checked_sub(overhead)
2361                        .max_width_error(shape.width, self.span())?;
2362                    let ty_str = self
2363                        .ty
2364                        .rewrite_result(context, Shape::legacy(max_width, shape.indent))?;
2365                    result.push_str(&ty_str);
2366                }
2367            }
2368
2369            Ok(result)
2370        } else {
2371            self.ty.rewrite_result(context, shape)
2372        }
2373    }
2374}
2375
2376fn rewrite_opt_lifetime(
2377    context: &RewriteContext<'_>,
2378    lifetime: Option<ast::Lifetime>,
2379) -> RewriteResult {
2380    let Some(l) = lifetime else {
2381        return Ok(String::new());
2382    };
2383    let mut result = l.rewrite_result(
2384        context,
2385        Shape::legacy(context.config.max_width(), Indent::empty()),
2386    )?;
2387    result.push(' ');
2388    Ok(result)
2389}
2390
2391fn rewrite_explicit_self(
2392    context: &RewriteContext<'_>,
2393    explicit_self: &ast::ExplicitSelf,
2394    param_attrs: &str,
2395    span: Span,
2396    shape: Shape,
2397    has_multiple_attr_lines: bool,
2398) -> RewriteResult {
2399    let self_str = match explicit_self.node {
2400        ast::SelfKind::Region(lt, m) => {
2401            let mut_str = format_mutability(m);
2402            let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2403            format!("&{lifetime_str}{mut_str}self")
2404        }
2405        ast::SelfKind::Pinned(lt, m) => {
2406            let mut_str = m.ptr_str();
2407            let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2408            format!("&{lifetime_str}pin {mut_str} self")
2409        }
2410        ast::SelfKind::Explicit(ref ty, mutability) => {
2411            let type_str = ty.rewrite_result(
2412                context,
2413                Shape::legacy(context.config.max_width(), Indent::empty()),
2414            )?;
2415            format!("{}self: {}", format_mutability(mutability), type_str)
2416        }
2417        ast::SelfKind::Value(mutability) => format!("{}self", format_mutability(mutability)),
2418    };
2419    Ok(combine_strs_with_missing_comments(
2420        context,
2421        param_attrs,
2422        &self_str,
2423        span,
2424        shape,
2425        !has_multiple_attr_lines,
2426    )?)
2427}
2428
2429pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2430    if param.attrs.is_empty() {
2431        if is_named_param(param) {
2432            param.pat.span.lo()
2433        } else {
2434            param.ty.span.lo()
2435        }
2436    } else {
2437        param.attrs[0].span.lo()
2438    }
2439}
2440
2441pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2442    match param.ty.kind {
2443        ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2444        ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2445        _ => param.ty.span.hi(),
2446    }
2447}
2448
2449pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2450    !matches!(param.pat.kind, ast::PatKind::Missing)
2451}
2452
2453#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2454pub(crate) enum FnBraceStyle {
2455    SameLine,
2456    NextLine,
2457    None,
2458}
2459
2460// Return type is (result, force_new_line_for_brace)
2461fn rewrite_fn_base(
2462    context: &RewriteContext<'_>,
2463    indent: Indent,
2464    ident: symbol::Ident,
2465    fn_sig: &FnSig<'_>,
2466    span: Span,
2467    fn_brace_style: FnBraceStyle,
2468) -> Result<(String, bool, bool), RewriteError> {
2469    let mut force_new_line_for_brace = false;
2470
2471    let where_clause = &fn_sig.generics.where_clause;
2472
2473    let mut result = String::with_capacity(1024);
2474    result.push_str(&fn_sig.to_str(context));
2475
2476    // fn foo
2477    result.push_str("fn ");
2478
2479    // Generics.
2480    let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2481        // 4 = `() {`
2482        4
2483    } else {
2484        // 2 = `()`
2485        2
2486    };
2487    let used_width = last_line_used_width(&result, indent.width());
2488    let one_line_budget = context.budget(used_width + overhead);
2489    let shape = Shape {
2490        width: one_line_budget,
2491        indent,
2492        offset: used_width,
2493    };
2494    let fd = fn_sig.decl;
2495    let generics_str = rewrite_generics(
2496        context,
2497        rewrite_ident(context, ident),
2498        &fn_sig.generics,
2499        shape,
2500    )?;
2501    result.push_str(&generics_str);
2502
2503    let snuggle_angle_bracket = generics_str
2504        .lines()
2505        .last()
2506        .map_or(false, |l| l.trim_start().len() == 1);
2507
2508    // Note that the width and indent don't really matter, we'll re-layout the
2509    // return type later anyway.
2510    let ret_str = fd
2511        .output
2512        .rewrite_result(context, Shape::indented(indent, context.config))?;
2513
2514    let multi_line_ret_str = ret_str.contains('\n');
2515    let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2516
2517    // Params.
2518    let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2519        context,
2520        &result,
2521        indent,
2522        ret_str_len,
2523        fn_brace_style,
2524        multi_line_ret_str,
2525    );
2526
2527    debug!(
2528        "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2529        one_line_budget, multi_line_budget, param_indent
2530    );
2531
2532    result.push('(');
2533    // Check if vertical layout was forced.
2534    if one_line_budget == 0
2535        && !snuggle_angle_bracket
2536        && context.config.indent_style() == IndentStyle::Visual
2537    {
2538        result.push_str(&param_indent.to_string_with_newline(context.config));
2539    }
2540
2541    let params_end = if fd.inputs.is_empty() {
2542        context
2543            .snippet_provider
2544            .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), ")")
2545    } else {
2546        let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2547        context.snippet_provider.span_after(last_span, ")")
2548    };
2549    let params_span = mk_sp(
2550        context
2551            .snippet_provider
2552            .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), "("),
2553        params_end,
2554    );
2555    let param_str = rewrite_params(
2556        context,
2557        &fd.inputs,
2558        one_line_budget,
2559        multi_line_budget,
2560        indent,
2561        param_indent,
2562        params_span,
2563        fd.c_variadic(),
2564    )?;
2565
2566    let put_params_in_block = match context.config.indent_style() {
2567        IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2568        _ => false,
2569    } && !fd.inputs.is_empty();
2570
2571    let mut params_last_line_contains_comment = false;
2572    let mut no_params_and_over_max_width = false;
2573
2574    if put_params_in_block {
2575        param_indent = indent.block_indent(context.config);
2576        result.push_str(&param_indent.to_string_with_newline(context.config));
2577        result.push_str(&param_str);
2578        result.push_str(&indent.to_string_with_newline(context.config));
2579        result.push(')');
2580    } else {
2581        result.push_str(&param_str);
2582        let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2583        // Put the closing brace on the next line if it overflows the max width.
2584        // 1 = `)`
2585        let closing_paren_overflow_max_width =
2586            fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2587        // If the last line of params contains comment, we cannot put the closing paren
2588        // on the same line.
2589        params_last_line_contains_comment = param_str
2590            .lines()
2591            .last()
2592            .map_or(false, |last_line| last_line.contains("//"));
2593
2594        if context.config.style_edition() >= StyleEdition::Edition2024 {
2595            if closing_paren_overflow_max_width {
2596                result.push(')');
2597                result.push_str(&indent.to_string_with_newline(context.config));
2598                no_params_and_over_max_width = true;
2599            } else if params_last_line_contains_comment {
2600                result.push_str(&indent.to_string_with_newline(context.config));
2601                result.push(')');
2602                no_params_and_over_max_width = true;
2603            } else {
2604                result.push(')');
2605            }
2606        } else {
2607            if closing_paren_overflow_max_width || params_last_line_contains_comment {
2608                result.push_str(&indent.to_string_with_newline(context.config));
2609            }
2610            result.push(')');
2611        }
2612    }
2613
2614    // Return type.
2615    if let ast::FnRetTy::Ty(..) = fd.output {
2616        let ret_should_indent = match context.config.indent_style() {
2617            // If our params are block layout then we surely must have space.
2618            IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2619            _ if params_last_line_contains_comment => false,
2620            _ if result.contains('\n') || multi_line_ret_str => true,
2621            _ => {
2622                // If the return type would push over the max width, then put the return type on
2623                // a new line. With the +1 for the signature length an additional space between
2624                // the closing parenthesis of the param and the arrow '->' is considered.
2625                let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2626
2627                // If there is no where-clause, take into account the space after the return type
2628                // and the brace.
2629                if where_clause.predicates.is_empty() {
2630                    sig_length += 2;
2631                }
2632
2633                sig_length > context.config.max_width()
2634            }
2635        };
2636        let ret_shape = if ret_should_indent {
2637            if context.config.style_edition() <= StyleEdition::Edition2021
2638                || context.config.indent_style() == IndentStyle::Visual
2639            {
2640                let indent = if param_str.is_empty() {
2641                    // Aligning with nonexistent params looks silly.
2642                    force_new_line_for_brace = true;
2643                    indent + 4
2644                } else {
2645                    // FIXME: we might want to check that using the param indent
2646                    // doesn't blow our budget, and if it does, then fallback to
2647                    // the where-clause indent.
2648                    param_indent
2649                };
2650
2651                result.push_str(&indent.to_string_with_newline(context.config));
2652                Shape::indented(indent, context.config)
2653            } else {
2654                let mut ret_shape = Shape::indented(indent, context.config);
2655                if param_str.is_empty() {
2656                    // Aligning with nonexistent params looks silly.
2657                    force_new_line_for_brace = true;
2658                    ret_shape = if context.use_block_indent() {
2659                        ret_shape.offset_left(4).unwrap_or(ret_shape)
2660                    } else {
2661                        ret_shape.indent = ret_shape.indent + 4;
2662                        ret_shape
2663                    };
2664                }
2665
2666                result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2667                ret_shape
2668            }
2669        } else {
2670            if context.config.style_edition() >= StyleEdition::Edition2024 {
2671                if !param_str.is_empty() || !no_params_and_over_max_width {
2672                    result.push(' ');
2673                }
2674            } else {
2675                result.push(' ');
2676            }
2677
2678            let ret_shape = Shape::indented(indent, context.config);
2679            ret_shape
2680                .offset_left(last_line_width(&result))
2681                .unwrap_or(ret_shape)
2682        };
2683
2684        if multi_line_ret_str || ret_should_indent {
2685            // Now that we know the proper indent and width, we need to
2686            // re-layout the return type.
2687            let ret_str = fd.output.rewrite_result(context, ret_shape)?;
2688            result.push_str(&ret_str);
2689        } else {
2690            result.push_str(&ret_str);
2691        }
2692
2693        // Comment between return type and the end of the decl.
2694        let snippet_lo = fd.output.span().hi();
2695        if where_clause.predicates.is_empty() {
2696            let snippet_hi = span.hi();
2697            let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2698            // Try to preserve the layout of the original snippet.
2699            let original_starts_with_newline = snippet
2700                .find(|c| c != ' ')
2701                .map_or(false, |i| starts_with_newline(&snippet[i..]));
2702            let original_ends_with_newline = snippet
2703                .rfind(|c| c != ' ')
2704                .map_or(false, |i| snippet[i..].ends_with('\n'));
2705            let snippet = snippet.trim();
2706            if !snippet.is_empty() {
2707                result.push(if original_starts_with_newline {
2708                    '\n'
2709                } else {
2710                    ' '
2711                });
2712                result.push_str(snippet);
2713                if original_ends_with_newline {
2714                    force_new_line_for_brace = true;
2715                }
2716            }
2717        }
2718    }
2719
2720    let pos_before_where = match fd.output {
2721        ast::FnRetTy::Default(..) => params_span.hi(),
2722        ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
2723    };
2724
2725    let is_params_multi_lined = param_str.contains('\n');
2726
2727    let space = if put_params_in_block && ret_str.is_empty() {
2728        WhereClauseSpace::Space
2729    } else {
2730        WhereClauseSpace::Newline
2731    };
2732    let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2733    if is_params_multi_lined {
2734        option.veto_single_line();
2735    }
2736    let where_clause_str = rewrite_where_clause(
2737        context,
2738        &where_clause.predicates,
2739        where_clause.span,
2740        context.config.brace_style(),
2741        Shape::indented(indent, context.config),
2742        true,
2743        "{",
2744        Some(span.hi()),
2745        pos_before_where,
2746        option,
2747    )?;
2748    // If there are neither where-clause nor return type, we may be missing comments between
2749    // params and `{`.
2750    if where_clause_str.is_empty() {
2751        if let ast::FnRetTy::Default(ret_span) = fd.output {
2752            match recover_missing_comment_in_span(
2753                // from after the closing paren to right before block or semicolon
2754                mk_sp(ret_span.lo(), span.hi()),
2755                shape,
2756                context,
2757                last_line_width(&result),
2758            ) {
2759                Ok(ref missing_comment) if !missing_comment.is_empty() => {
2760                    result.push_str(missing_comment);
2761                    force_new_line_for_brace = true;
2762                }
2763                _ => (),
2764            }
2765        }
2766    }
2767
2768    result.push_str(&where_clause_str);
2769
2770    let ends_with_comment = last_line_contains_single_line_comment(&result);
2771    force_new_line_for_brace |= ends_with_comment;
2772    force_new_line_for_brace |=
2773        is_params_multi_lined && context.config.where_single_line() && !where_clause_str.is_empty();
2774    Ok((result, ends_with_comment, force_new_line_for_brace))
2775}
2776
2777/// Kind of spaces to put before `where`.
2778#[derive(Copy, Clone)]
2779enum WhereClauseSpace {
2780    /// A single space.
2781    Space,
2782    /// A new line.
2783    Newline,
2784    /// Nothing.
2785    None,
2786}
2787
2788#[derive(Copy, Clone)]
2789struct WhereClauseOption {
2790    suppress_comma: bool, // Force no trailing comma
2791    snuggle: WhereClauseSpace,
2792    allow_single_line: bool, // Try single line where-clause instead of vertical layout
2793    veto_single_line: bool,  // Disallow a single-line where-clause.
2794}
2795
2796impl WhereClauseOption {
2797    fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2798        WhereClauseOption {
2799            suppress_comma,
2800            snuggle,
2801            allow_single_line: false,
2802            veto_single_line: false,
2803        }
2804    }
2805
2806    fn snuggled(current: &str) -> WhereClauseOption {
2807        WhereClauseOption {
2808            suppress_comma: false,
2809            snuggle: if last_line_width(current) == 1 {
2810                WhereClauseSpace::Space
2811            } else {
2812                WhereClauseSpace::Newline
2813            },
2814            allow_single_line: false,
2815            veto_single_line: false,
2816        }
2817    }
2818
2819    fn suppress_comma(&mut self) {
2820        self.suppress_comma = true
2821    }
2822
2823    fn allow_single_line(&mut self) {
2824        self.allow_single_line = true
2825    }
2826
2827    fn snuggle(&mut self) {
2828        self.snuggle = WhereClauseSpace::Space
2829    }
2830
2831    fn veto_single_line(&mut self) {
2832        self.veto_single_line = true;
2833    }
2834}
2835
2836fn rewrite_params(
2837    context: &RewriteContext<'_>,
2838    params: &[ast::Param],
2839    one_line_budget: usize,
2840    multi_line_budget: usize,
2841    indent: Indent,
2842    param_indent: Indent,
2843    span: Span,
2844    variadic: bool,
2845) -> RewriteResult {
2846    if params.is_empty() {
2847        let comment = context
2848            .snippet(mk_sp(
2849                span.lo(),
2850                // to remove ')'
2851                span.hi() - BytePos(1),
2852            ))
2853            .trim();
2854        return Ok(comment.to_owned());
2855    }
2856    let param_items: Vec<_> = itemize_list(
2857        context.snippet_provider,
2858        params.iter(),
2859        ")",
2860        ",",
2861        |param| span_lo_for_param(param),
2862        |param| param.ty.span.hi(),
2863        |param| {
2864            param
2865                .rewrite_result(context, Shape::legacy(multi_line_budget, param_indent))
2866                .or_else(|_| Ok(context.snippet(param.span()).to_owned()))
2867        },
2868        span.lo(),
2869        span.hi(),
2870        false,
2871    )
2872    .collect();
2873
2874    let tactic = definitive_tactic(
2875        &param_items,
2876        context
2877            .config
2878            .fn_params_layout()
2879            .to_list_tactic(param_items.len()),
2880        Separator::Comma,
2881        one_line_budget,
2882    );
2883    let budget = match tactic {
2884        DefinitiveListTactic::Horizontal => one_line_budget,
2885        _ => multi_line_budget,
2886    };
2887    let indent = match context.config.indent_style() {
2888        IndentStyle::Block => indent.block_indent(context.config),
2889        IndentStyle::Visual => param_indent,
2890    };
2891    let trailing_separator = if variadic {
2892        SeparatorTactic::Never
2893    } else {
2894        match context.config.indent_style() {
2895            IndentStyle::Block => context.config.trailing_comma(),
2896            IndentStyle::Visual => SeparatorTactic::Never,
2897        }
2898    };
2899    let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2900        .tactic(tactic)
2901        .trailing_separator(trailing_separator)
2902        .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2903        .preserve_newline(true);
2904    write_list(&param_items, &fmt)
2905}
2906
2907fn compute_budgets_for_params(
2908    context: &RewriteContext<'_>,
2909    result: &str,
2910    indent: Indent,
2911    ret_str_len: usize,
2912    fn_brace_style: FnBraceStyle,
2913    force_vertical_layout: bool,
2914) -> (usize, usize, Indent) {
2915    debug!(
2916        "compute_budgets_for_params {} {:?}, {}, {:?}",
2917        result.len(),
2918        indent,
2919        ret_str_len,
2920        fn_brace_style,
2921    );
2922    // Try keeping everything on the same line.
2923    if !result.contains('\n') && !force_vertical_layout {
2924        // 2 = `()`, 3 = `() `, space is before ret_string.
2925        let overhead = if ret_str_len == 0 { 2 } else { 3 };
2926        let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2927        match fn_brace_style {
2928            FnBraceStyle::None => used_space += 1,     // 1 = `;`
2929            FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2930            FnBraceStyle::NextLine => (),
2931        }
2932        let one_line_budget = context.budget(used_space);
2933
2934        if one_line_budget > 0 {
2935            // 4 = "() {".len()
2936            let (indent, multi_line_budget) = match context.config.indent_style() {
2937                IndentStyle::Block => {
2938                    let indent = indent.block_indent(context.config);
2939                    (indent, context.budget(indent.width() + 1))
2940                }
2941                IndentStyle::Visual => {
2942                    let indent = indent + result.len() + 1;
2943                    let multi_line_overhead = match fn_brace_style {
2944                        FnBraceStyle::SameLine => 4,
2945                        _ => 2,
2946                    } + indent.width();
2947                    (indent, context.budget(multi_line_overhead))
2948                }
2949            };
2950
2951            return (one_line_budget, multi_line_budget, indent);
2952        }
2953    }
2954
2955    // Didn't work. we must force vertical layout and put params on a newline.
2956    let new_indent = indent.block_indent(context.config);
2957    let used_space = match context.config.indent_style() {
2958        // 1 = `,`
2959        IndentStyle::Block => new_indent.width() + 1,
2960        // Account for `)` and possibly ` {`.
2961        IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2962    };
2963    (0, context.budget(used_space), new_indent)
2964}
2965
2966fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2967    let predicate_count = where_clause.predicates.len();
2968
2969    if config.where_single_line() && predicate_count == 1 {
2970        return FnBraceStyle::SameLine;
2971    }
2972    let brace_style = config.brace_style();
2973
2974    let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2975        || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2976    if use_next_line {
2977        FnBraceStyle::NextLine
2978    } else {
2979        FnBraceStyle::SameLine
2980    }
2981}
2982
2983fn rewrite_generics(
2984    context: &RewriteContext<'_>,
2985    ident: &str,
2986    generics: &ast::Generics,
2987    shape: Shape,
2988) -> RewriteResult {
2989    // FIXME: convert bounds to where-clauses where they get too big or if
2990    // there is a where-clause at all.
2991
2992    if generics.params.is_empty() {
2993        return Ok(ident.to_owned());
2994    }
2995
2996    let params = generics.params.iter();
2997    overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2998}
2999
3000fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
3001    match config.indent_style() {
3002        IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
3003        IndentStyle::Block => {
3004            // 1 = ","
3005            shape
3006                .block()
3007                .block_indent(config.tab_spaces())
3008                .with_max_width(config)
3009                .sub_width(1)
3010        }
3011    }
3012}
3013
3014fn rewrite_where_clause_rfc_style(
3015    context: &RewriteContext<'_>,
3016    predicates: &[ast::WherePredicate],
3017    where_span: Span,
3018    shape: Shape,
3019    terminator: &str,
3020    span_end: Option<BytePos>,
3021    span_end_before_where: BytePos,
3022    where_clause_option: WhereClauseOption,
3023) -> RewriteResult {
3024    let (where_keyword, allow_single_line) = rewrite_where_keyword(
3025        context,
3026        predicates,
3027        where_span,
3028        shape,
3029        span_end_before_where,
3030        where_clause_option,
3031    )?;
3032
3033    // 1 = `,`
3034    let clause_shape = shape
3035        .block()
3036        .with_max_width(context.config)
3037        .block_left(context.config.tab_spaces())
3038        .and_then(|s| s.sub_width(1))
3039        .max_width_error(shape.width, where_span)?;
3040    let force_single_line = context.config.where_single_line()
3041        && predicates.len() == 1
3042        && !where_clause_option.veto_single_line;
3043
3044    let preds_str = rewrite_bounds_on_where_clause(
3045        context,
3046        predicates,
3047        clause_shape,
3048        terminator,
3049        span_end,
3050        where_clause_option,
3051        force_single_line,
3052    )?;
3053
3054    // 6 = `where `
3055    let clause_sep =
3056        if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
3057            || force_single_line
3058        {
3059            Cow::from(" ")
3060        } else {
3061            clause_shape.indent.to_string_with_newline(context.config)
3062        };
3063
3064    Ok(format!("{where_keyword}{clause_sep}{preds_str}"))
3065}
3066
3067/// Rewrite `where` and comment around it.
3068fn rewrite_where_keyword(
3069    context: &RewriteContext<'_>,
3070    predicates: &[ast::WherePredicate],
3071    where_span: Span,
3072    shape: Shape,
3073    span_end_before_where: BytePos,
3074    where_clause_option: WhereClauseOption,
3075) -> Result<(String, bool), RewriteError> {
3076    let block_shape = shape.block().with_max_width(context.config);
3077    // 1 = `,`
3078    let clause_shape = block_shape
3079        .block_left(context.config.tab_spaces())
3080        .and_then(|s| s.sub_width(1))
3081        .max_width_error(block_shape.width, where_span)?;
3082
3083    let comment_separator = |comment: &str, shape: Shape| {
3084        if comment.is_empty() {
3085            Cow::from("")
3086        } else {
3087            shape.indent.to_string_with_newline(context.config)
3088        }
3089    };
3090
3091    let (span_before, span_after) =
3092        missing_span_before_after_where(span_end_before_where, predicates, where_span);
3093    let (comment_before, comment_after) =
3094        rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
3095
3096    let starting_newline = match where_clause_option.snuggle {
3097        WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
3098        WhereClauseSpace::None => Cow::from(""),
3099        _ => block_shape.indent.to_string_with_newline(context.config),
3100    };
3101
3102    let newline_before_where = comment_separator(&comment_before, shape);
3103    let newline_after_where = comment_separator(&comment_after, clause_shape);
3104    let result = format!(
3105        "{starting_newline}{comment_before}{newline_before_where}where\
3106{newline_after_where}{comment_after}"
3107    );
3108    let allow_single_line = where_clause_option.allow_single_line
3109        && comment_before.is_empty()
3110        && comment_after.is_empty();
3111
3112    Ok((result, allow_single_line))
3113}
3114
3115/// Rewrite bounds on a where clause.
3116fn rewrite_bounds_on_where_clause(
3117    context: &RewriteContext<'_>,
3118    predicates: &[ast::WherePredicate],
3119    shape: Shape,
3120    terminator: &str,
3121    span_end: Option<BytePos>,
3122    where_clause_option: WhereClauseOption,
3123    force_single_line: bool,
3124) -> RewriteResult {
3125    let span_start = predicates[0].span().lo();
3126    // If we don't have the start of the next span, then use the end of the
3127    // predicates, but that means we miss comments.
3128    let len = predicates.len();
3129    let end_of_preds = predicates[len - 1].span().hi();
3130    let span_end = span_end.unwrap_or(end_of_preds);
3131    let items = itemize_list(
3132        context.snippet_provider,
3133        predicates.iter(),
3134        terminator,
3135        ",",
3136        |pred| pred.span().lo(),
3137        |pred| pred.span().hi(),
3138        |pred| pred.rewrite_result(context, shape),
3139        span_start,
3140        span_end,
3141        false,
3142    );
3143    let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
3144        SeparatorTactic::Never
3145    } else {
3146        context.config.trailing_comma()
3147    };
3148
3149    // shape should be vertical only and only if we have `force_single_line` option enabled
3150    // and the number of items of the where-clause is equal to 1
3151    let shape_tactic = if force_single_line {
3152        DefinitiveListTactic::Horizontal
3153    } else {
3154        DefinitiveListTactic::Vertical
3155    };
3156
3157    let preserve_newline = context.config.style_edition() <= StyleEdition::Edition2021;
3158
3159    let fmt = ListFormatting::new(shape, context.config)
3160        .tactic(shape_tactic)
3161        .trailing_separator(comma_tactic)
3162        .preserve_newline(preserve_newline);
3163    write_list(&items.collect::<Vec<_>>(), &fmt)
3164}
3165
3166fn rewrite_where_clause(
3167    context: &RewriteContext<'_>,
3168    predicates: &[ast::WherePredicate],
3169    where_span: Span,
3170    brace_style: BraceStyle,
3171    shape: Shape,
3172    on_new_line: bool,
3173    terminator: &str,
3174    span_end: Option<BytePos>,
3175    span_end_before_where: BytePos,
3176    where_clause_option: WhereClauseOption,
3177) -> RewriteResult {
3178    if predicates.is_empty() {
3179        return Ok(String::new());
3180    }
3181
3182    if context.config.indent_style() == IndentStyle::Block {
3183        return rewrite_where_clause_rfc_style(
3184            context,
3185            predicates,
3186            where_span,
3187            shape,
3188            terminator,
3189            span_end,
3190            span_end_before_where,
3191            where_clause_option,
3192        );
3193    }
3194
3195    let extra_indent = Indent::new(context.config.tab_spaces(), 0);
3196
3197    let offset = match context.config.indent_style() {
3198        IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
3199        // 6 = "where ".len()
3200        IndentStyle::Visual => shape.indent + extra_indent + 6,
3201    };
3202    // FIXME: if indent_style != Visual, then the budgets below might
3203    // be out by a char or two.
3204
3205    let budget = context.config.max_width() - offset.width();
3206    let span_start = predicates[0].span().lo();
3207    // If we don't have the start of the next span, then use the end of the
3208    // predicates, but that means we miss comments.
3209    let len = predicates.len();
3210    let end_of_preds = predicates[len - 1].span().hi();
3211    let span_end = span_end.unwrap_or(end_of_preds);
3212    let items = itemize_list(
3213        context.snippet_provider,
3214        predicates.iter(),
3215        terminator,
3216        ",",
3217        |pred| pred.span().lo(),
3218        |pred| pred.span().hi(),
3219        |pred| pred.rewrite_result(context, Shape::legacy(budget, offset)),
3220        span_start,
3221        span_end,
3222        false,
3223    );
3224    let item_vec = items.collect::<Vec<_>>();
3225    // FIXME: we don't need to collect here
3226    let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
3227
3228    let mut comma_tactic = context.config.trailing_comma();
3229    // Kind of a hack because we don't usually have trailing commas in where-clauses.
3230    if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
3231        comma_tactic = SeparatorTactic::Never;
3232    }
3233
3234    let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
3235        .tactic(tactic)
3236        .trailing_separator(comma_tactic)
3237        .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
3238        .preserve_newline(true);
3239    let preds_str = write_list(&item_vec, &fmt)?;
3240
3241    let end_length = if terminator == "{" {
3242        // If the brace is on the next line we don't need to count it otherwise it needs two
3243        // characters " {"
3244        match brace_style {
3245            BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
3246            BraceStyle::PreferSameLine => 2,
3247        }
3248    } else if terminator == "=" {
3249        2
3250    } else {
3251        terminator.len()
3252    };
3253    if on_new_line
3254        || preds_str.contains('\n')
3255        || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
3256    {
3257        Ok(format!(
3258            "\n{}where {}",
3259            (shape.indent + extra_indent).to_string(context.config),
3260            preds_str
3261        ))
3262    } else {
3263        Ok(format!(" where {preds_str}"))
3264    }
3265}
3266
3267fn missing_span_before_after_where(
3268    before_item_span_end: BytePos,
3269    predicates: &[ast::WherePredicate],
3270    where_span: Span,
3271) -> (Span, Span) {
3272    let missing_span_before = mk_sp(before_item_span_end, where_span.lo());
3273    // 5 = `where`
3274    let pos_after_where = where_span.lo() + BytePos(5);
3275    let missing_span_after = mk_sp(pos_after_where, predicates[0].span().lo());
3276    (missing_span_before, missing_span_after)
3277}
3278
3279fn rewrite_comments_before_after_where(
3280    context: &RewriteContext<'_>,
3281    span_before_where: Span,
3282    span_after_where: Span,
3283    shape: Shape,
3284) -> Result<(String, String), RewriteError> {
3285    let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
3286    let after_comment = rewrite_missing_comment(
3287        span_after_where,
3288        shape.block_indent(context.config.tab_spaces()),
3289        context,
3290    )?;
3291    Ok((before_comment, after_comment))
3292}
3293
3294fn format_header(
3295    context: &RewriteContext<'_>,
3296    item_name: &str,
3297    ident: symbol::Ident,
3298    vis: &ast::Visibility,
3299    offset: Indent,
3300) -> String {
3301    let mut result = String::with_capacity(128);
3302    let shape = Shape::indented(offset, context.config);
3303
3304    result.push_str(format_visibility(context, vis).trim());
3305
3306    // Check for a missing comment between the visibility and the item name.
3307    let after_vis = vis.span.hi();
3308    if let Some(before_item_name) = context
3309        .snippet_provider
3310        .opt_span_before(mk_sp(vis.span.lo(), ident.span.hi()), item_name.trim())
3311    {
3312        let missing_span = mk_sp(after_vis, before_item_name);
3313        if let Ok(result_with_comment) = combine_strs_with_missing_comments(
3314            context,
3315            &result,
3316            item_name,
3317            missing_span,
3318            shape,
3319            /* allow_extend */ true,
3320        ) {
3321            result = result_with_comment;
3322        }
3323    }
3324
3325    result.push_str(rewrite_ident(context, ident));
3326
3327    result
3328}
3329
3330#[derive(PartialEq, Eq, Clone, Copy)]
3331enum BracePos {
3332    None,
3333    Auto,
3334    ForceSameLine,
3335}
3336
3337fn format_generics(
3338    context: &RewriteContext<'_>,
3339    generics: &ast::Generics,
3340    brace_style: BraceStyle,
3341    brace_pos: BracePos,
3342    offset: Indent,
3343    span: Span,
3344    used_width: usize,
3345) -> Option<String> {
3346    let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
3347    let mut result = rewrite_generics(context, "", generics, shape).ok()?;
3348
3349    // If the generics are not parameterized then generics.span.hi() == 0,
3350    // so we use span.lo(), which is the position after `struct Foo`.
3351    let span_end_before_where = if !generics.params.is_empty() {
3352        generics.span.hi()
3353    } else {
3354        span.lo()
3355    };
3356    let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
3357        let budget = context.budget(last_line_used_width(&result, offset.width()));
3358        let mut option = WhereClauseOption::snuggled(&result);
3359        if brace_pos == BracePos::None {
3360            option.suppress_comma = true;
3361        }
3362        let where_clause_str = rewrite_where_clause(
3363            context,
3364            &generics.where_clause.predicates,
3365            generics.where_clause.span,
3366            brace_style,
3367            Shape::legacy(budget, offset.block_only()),
3368            true,
3369            "{",
3370            Some(span.hi()),
3371            span_end_before_where,
3372            option,
3373        )
3374        .ok()?;
3375        result.push_str(&where_clause_str);
3376        (
3377            brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
3378            // missed comments are taken care of in #rewrite_where_clause
3379            None,
3380        )
3381    } else {
3382        (
3383            brace_pos == BracePos::ForceSameLine
3384                || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
3385                    || brace_style != BraceStyle::AlwaysNextLine)
3386                || trimmed_last_line_width(&result) == 1,
3387            rewrite_missing_comment(
3388                mk_sp(
3389                    span_end_before_where,
3390                    if brace_pos == BracePos::None {
3391                        span.hi()
3392                    } else {
3393                        context.snippet_provider.span_before_last(span, "{")
3394                    },
3395                ),
3396                shape,
3397                context,
3398            )
3399            .ok(),
3400        )
3401    };
3402    // add missing comments
3403    let missed_line_comments = missed_comments
3404        .filter(|missed_comments| !missed_comments.is_empty())
3405        .map_or(false, |missed_comments| {
3406            let is_block = is_last_comment_block(&missed_comments);
3407            let sep = if is_block { " " } else { "\n" };
3408            result.push_str(sep);
3409            result.push_str(&missed_comments);
3410            !is_block
3411        });
3412    if brace_pos == BracePos::None {
3413        return Some(result);
3414    }
3415    let total_used_width = last_line_used_width(&result, used_width);
3416    let remaining_budget = context.budget(total_used_width);
3417    // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
3418    // and hence we take the closer into account as well for one line budget.
3419    // We assume that the closer has the same length as the opener.
3420    let overhead = if brace_pos == BracePos::ForceSameLine {
3421        // 3 = ` {}`
3422        3
3423    } else {
3424        // 2 = ` {`
3425        2
3426    };
3427    let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3428    if !forbid_same_line_brace && same_line_brace {
3429        result.push(' ');
3430    } else {
3431        result.push('\n');
3432        result.push_str(&offset.block_only().to_string(context.config));
3433    }
3434    result.push('{');
3435
3436    Some(result)
3437}
3438
3439impl Rewrite for ast::ForeignItem {
3440    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3441        self.rewrite_result(context, shape).ok()
3442    }
3443
3444    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
3445        let attrs_str = self.attrs.rewrite_result(context, shape)?;
3446        // Drop semicolon or it will be interpreted as comment.
3447        // FIXME: this may be a faulty span from libsyntax.
3448        let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3449
3450        let item_str = match self.kind {
3451            ast::ForeignItemKind::Fn(ref fn_kind) => {
3452                let ast::Fn {
3453                    defaultness,
3454                    ref sig,
3455                    ident,
3456                    ref generics,
3457                    ref body,
3458                    ..
3459                } = **fn_kind;
3460                if body.is_some() {
3461                    let mut visitor = FmtVisitor::from_context(context);
3462                    visitor.block_indent = shape.indent;
3463                    visitor.last_pos = self.span.lo();
3464                    let inner_attrs = inner_attributes(&self.attrs);
3465                    let fn_ctxt = visit::FnCtxt::Foreign;
3466                    visitor.visit_fn(
3467                        ident,
3468                        visit::FnKind::Fn(fn_ctxt, &self.vis, fn_kind),
3469                        &sig.decl,
3470                        self.span,
3471                        defaultness,
3472                        Some(&inner_attrs),
3473                    );
3474                    Ok(visitor.buffer.to_owned())
3475                } else {
3476                    rewrite_fn_base(
3477                        context,
3478                        shape.indent,
3479                        ident,
3480                        &FnSig::from_method_sig(sig, generics, &self.vis),
3481                        span,
3482                        FnBraceStyle::None,
3483                    )
3484                    .map(|(s, _, _)| format!("{};", s))
3485                }
3486            }
3487            ast::ForeignItemKind::Static(ref static_foreign_item) => {
3488                // FIXME(#21): we're dropping potential comments in between the
3489                // function kw here.
3490                let vis = format_visibility(context, &self.vis);
3491                let safety = format_safety(static_foreign_item.safety);
3492                let mut_str = format_mutability(static_foreign_item.mutability);
3493                let prefix = format!(
3494                    "{}{}static {}{}:",
3495                    vis,
3496                    safety,
3497                    mut_str,
3498                    rewrite_ident(context, static_foreign_item.ident)
3499                );
3500                // 1 = ;
3501                rewrite_assign_rhs(
3502                    context,
3503                    prefix,
3504                    &static_foreign_item.ty,
3505                    &RhsAssignKind::Ty,
3506                    shape
3507                        .sub_width(1)
3508                        .max_width_error(shape.width, static_foreign_item.ty.span)?,
3509                )
3510                .map(|s| s + ";")
3511            }
3512            ast::ForeignItemKind::TyAlias(ref ty_alias) => {
3513                let kind = ItemVisitorKind::ForeignItem;
3514                rewrite_type_alias(ty_alias, &self.vis, context, shape.indent, kind, self.span)
3515            }
3516            ast::ForeignItemKind::MacCall(ref mac) => {
3517                rewrite_macro(mac, context, shape, MacroPosition::Item)
3518            }
3519        }?;
3520
3521        let missing_span = if self.attrs.is_empty() {
3522            mk_sp(self.span.lo(), self.span.lo())
3523        } else {
3524            mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3525        };
3526        combine_strs_with_missing_comments(
3527            context,
3528            &attrs_str,
3529            &item_str,
3530            missing_span,
3531            shape,
3532            false,
3533        )
3534    }
3535}
3536
3537/// Rewrite the attributes of an item.
3538fn rewrite_attrs(
3539    context: &RewriteContext<'_>,
3540    item: &ast::Item,
3541    item_str: &str,
3542    shape: Shape,
3543) -> Option<String> {
3544    let attrs = filter_inline_attrs(&item.attrs, item.span());
3545    let attrs_str = attrs.rewrite(context, shape)?;
3546
3547    let missed_span = if attrs.is_empty() {
3548        mk_sp(item.span.lo(), item.span.lo())
3549    } else {
3550        mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3551    };
3552
3553    let allow_extend = if attrs.len() == 1 {
3554        let line_len = attrs_str.len() + 1 + item_str.len();
3555        !attrs.first().unwrap().is_doc_comment()
3556            && context.config.inline_attribute_width() >= line_len
3557    } else {
3558        false
3559    };
3560
3561    combine_strs_with_missing_comments(
3562        context,
3563        &attrs_str,
3564        item_str,
3565        missed_span,
3566        shape,
3567        allow_extend,
3568    )
3569    .ok()
3570}
3571
3572/// Rewrite an inline mod.
3573/// The given shape is used to format the mod's attributes.
3574pub(crate) fn rewrite_mod(
3575    context: &RewriteContext<'_>,
3576    item: &ast::Item,
3577    ident: Ident,
3578    attrs_shape: Shape,
3579) -> Option<String> {
3580    let mut result = String::with_capacity(32);
3581    result.push_str(&*format_visibility(context, &item.vis));
3582    result.push_str("mod ");
3583    result.push_str(rewrite_ident(context, ident));
3584    result.push(';');
3585    rewrite_attrs(context, item, &result, attrs_shape)
3586}
3587
3588/// Rewrite `extern crate foo;`.
3589/// The given shape is used to format the extern crate's attributes.
3590pub(crate) fn rewrite_extern_crate(
3591    context: &RewriteContext<'_>,
3592    item: &ast::Item,
3593    attrs_shape: Shape,
3594) -> Option<String> {
3595    assert!(is_extern_crate(item));
3596    let new_str = context.snippet(item.span);
3597    let item_str = if contains_comment(new_str) {
3598        new_str.to_owned()
3599    } else {
3600        let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3601        String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3602    };
3603    rewrite_attrs(context, item, &item_str, attrs_shape)
3604}
3605
3606/// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3607pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3608    !matches!(
3609        item.kind,
3610        ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::Yes, _, _))
3611    )
3612}
3613
3614pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3615    matches!(item.kind, ast::ItemKind::Use(_))
3616}
3617
3618pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3619    matches!(item.kind, ast::ItemKind::ExternCrate(..))
3620}