Skip to main content

rustfmt_nightly/
items.rs

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