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