rustfmt_nightly/
items.rs

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