Skip to main content

rustfmt_nightly/
items.rs

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