1use 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
48impl 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 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 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 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 .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 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 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 let max_width =
163 std::cmp::min(shape.width, context.config.single_line_let_else_max_width());
164
165 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 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 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
200fn 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 return init_shape.width.saturating_sub(init_str.len()) >= 7;
219 }
220
221 if !init_str.ends_with([')', ']', '}']) {
223 return false;
224 }
225
226 let else_kw_snippet = context.snippet(else_kw_span).trim();
229 if else_kw_snippet != "else" {
230 return false;
231 }
232
233 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#[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 ForeignItem(&'a ast::ForeignItem),
293}
294
295pub(crate) struct FnSig<'a> {
297 decl: &'a ast::FnDecl,
298 generics: &'a ast::Generics,
299 ext: ast::Extern,
300 coroutine_kind: Cow<'a, Option<ast::CoroutineKind>>,
301 constness: ast::Const,
302 defaultness: ast::Defaultness,
303 safety: ast::Safety,
304 visibility: &'a ast::Visibility,
305}
306
307impl<'a> FnSig<'a> {
308 pub(crate) fn from_method_sig(
309 method_sig: &'a ast::FnSig,
310 generics: &'a ast::Generics,
311 visibility: &'a ast::Visibility,
312 defaultness: ast::Defaultness,
313 ) -> FnSig<'a> {
314 FnSig {
315 safety: method_sig.header.safety,
316 coroutine_kind: Cow::Borrowed(&method_sig.header.coroutine_kind),
317 constness: method_sig.header.constness,
318 defaultness,
319 ext: method_sig.header.ext,
320 decl: &*method_sig.decl,
321 generics,
322 visibility,
323 }
324 }
325
326 pub(crate) fn from_fn_kind(
327 fn_kind: &'a visit::FnKind<'_>,
328 decl: &'a ast::FnDecl,
329 defaultness: ast::Defaultness,
330 ) -> FnSig<'a> {
331 match *fn_kind {
332 visit::FnKind::Fn(visit::FnCtxt::Assoc(..), vis, ast::Fn { sig, generics, .. }) => {
333 FnSig::from_method_sig(sig, generics, vis, defaultness)
334 }
335 visit::FnKind::Fn(_, vis, ast::Fn { sig, generics, .. }) => FnSig {
336 decl,
337 generics,
338 ext: sig.header.ext,
339 constness: sig.header.constness,
340 coroutine_kind: Cow::Borrowed(&sig.header.coroutine_kind),
341 defaultness,
342 safety: sig.header.safety,
343 visibility: vis,
344 },
345 _ => unreachable!(),
346 }
347 }
348
349 fn to_str(&self, context: &RewriteContext<'_>) -> String {
350 let mut result = String::with_capacity(128);
351 result.push_str(&*format_visibility(context, self.visibility));
353 result.push_str(format_defaultness(self.defaultness));
354 result.push_str(format_constness(self.constness));
355 self.coroutine_kind
356 .map(|coroutine_kind| result.push_str(format_coro(&coroutine_kind)));
357 result.push_str(format_safety(self.safety));
358 result.push_str(&format_extern(
359 self.ext,
360 context.config.force_explicit_abi(),
361 ));
362 result
363 }
364}
365
366impl<'a> FmtVisitor<'a> {
367 fn format_item(&mut self, item: &Item<'_>) {
368 self.buffer.push_str(format_safety(item.safety));
369 self.buffer.push_str(&item.abi);
370
371 let snippet = self.snippet(item.span);
372 let brace_pos = snippet.find_uncommented("{").unwrap();
373
374 self.push_str("{");
375 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
376 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 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 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 ends_with_comment {
469 result.push_str(&indent.to_string_with_newline(context.config));
470 }
471
472 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 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 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 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 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 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 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 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 field.attrs.rewrite(&context, shape.sub_width_opt(1)?)?
678 };
679 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(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) =>
729 {
730 false
731 }
732 (Const(..), Const(..)) => false,
733 _ => true,
734 };
735
736 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(<y.ty, &rty.ty) || both_opaque(<y.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 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 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 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 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 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
999 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 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 result.push('\n');
1025 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 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 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 if !bounds.is_empty() {
1183 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 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 !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 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 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 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 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 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 mk_sp(header_hi, body_lo),
1453 last_line_width(&result),
1454 )?,
1455 None => {
1456 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 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 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
1526fn 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 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 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 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 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 match (visitor_kind, &op_ty) {
1712 (Item | AssocTraitItem | ForeignItem, Some(op_bounds)) => {
1713 let op = OpaqueType { bounds: op_bounds };
1714 rewrite_ty(rw_info, Some(bounds), Some(&op), rhs_hi, vis)
1715 }
1716 (Item | AssocTraitItem | ForeignItem, None) => {
1717 rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis)
1718 }
1719 (AssocImplItem, _) => {
1720 let result = if let Some(op_bounds) = op_ty {
1721 let op = OpaqueType { bounds: op_bounds };
1722 rewrite_ty(
1723 rw_info,
1724 Some(bounds),
1725 Some(&op),
1726 rhs_hi,
1727 &DEFAULT_VISIBILITY,
1728 )
1729 } else {
1730 rewrite_ty(rw_info, Some(bounds), ty_opt, rhs_hi, vis)
1731 }?;
1732 match defaultness {
1733 ast::Defaultness::Default(..) => Ok(format!("default {result}")),
1734 _ => Ok(result),
1735 }
1736 }
1737 }
1738}
1739
1740fn rewrite_ty<R: Rewrite>(
1741 rw_info: &TyAliasRewriteInfo<'_, '_>,
1742 generic_bounds_opt: Option<&ast::GenericBounds>,
1743 rhs: Option<&R>,
1744 rhs_hi: BytePos,
1746 vis: &ast::Visibility,
1747) -> RewriteResult {
1748 let mut result = String::with_capacity(128);
1749 let TyAliasRewriteInfo(context, indent, generics, after_where_clause, ident, span) = *rw_info;
1750 result.push_str(&format!("{}type ", format_visibility(context, vis)));
1751 let ident_str = rewrite_ident(context, ident);
1752
1753 if generics.params.is_empty() {
1754 result.push_str(ident_str)
1755 } else {
1756 let g_shape = Shape::indented(indent, context.config);
1758 let g_shape = g_shape
1759 .offset_left(result.len(), span)?
1760 .sub_width(2, span)?;
1761 let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1762 result.push_str(&generics_str);
1763 }
1764
1765 if let Some(bounds) = generic_bounds_opt {
1766 if !bounds.is_empty() {
1767 let shape = Shape::indented(indent, context.config);
1769 let shape = shape.offset_left(result.len() + 2, span)?;
1770 let type_bounds = bounds
1771 .rewrite_result(context, shape)
1772 .map(|s| format!(": {}", s))?;
1773 result.push_str(&type_bounds);
1774 }
1775 }
1776
1777 let where_budget = context.budget(last_line_width(&result));
1778 let mut option = WhereClauseOption::snuggled(&result);
1779 if rhs.is_none() {
1780 option.suppress_comma();
1781 }
1782 let before_where_clause_str = rewrite_where_clause(
1783 context,
1784 &generics.where_clause,
1785 context.config.brace_style(),
1786 Shape::legacy(where_budget, indent),
1787 false,
1788 "=",
1789 None,
1790 generics.span.hi(),
1791 option,
1792 )?;
1793 result.push_str(&before_where_clause_str);
1794
1795 let mut result = if let Some(ty) = rhs {
1796 if !generics.where_clause.predicates.is_empty() {
1800 result.push_str(&indent.to_string_with_newline(context.config));
1801 } else if !after_where_clause.predicates.is_empty() {
1802 result.push_str(
1803 &indent
1804 .block_indent(context.config)
1805 .to_string_with_newline(context.config),
1806 );
1807 } else {
1808 result.push(' ');
1809 }
1810
1811 let comment_span = context
1812 .snippet_provider
1813 .opt_span_before(span, "=")
1814 .map(|op_lo| mk_sp(generics.where_clause.span.hi(), op_lo));
1815
1816 let lhs = match comment_span {
1817 Some(comment_span)
1818 if contains_comment(
1819 context
1820 .snippet_provider
1821 .span_to_snippet(comment_span)
1822 .unknown_error()?,
1823 ) =>
1824 {
1825 let comment_shape = if !generics.where_clause.predicates.is_empty() {
1826 Shape::indented(indent, context.config)
1827 } else {
1828 let shape = Shape::indented(indent, context.config);
1829 shape.block_left(context.config.tab_spaces(), span)?
1830 };
1831
1832 combine_strs_with_missing_comments(
1833 context,
1834 result.trim_end(),
1835 "=",
1836 comment_span,
1837 comment_shape,
1838 true,
1839 )?
1840 }
1841 _ => format!("{result}="),
1842 };
1843
1844 let shape = Shape::indented(indent, context.config);
1846 let shape = if after_where_clause.predicates.is_empty() {
1847 Shape::indented(indent, context.config).sub_width(1, span)?
1848 } else {
1849 shape
1850 };
1851 rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape)?
1852 } else {
1853 result
1854 };
1855
1856 if !after_where_clause.predicates.is_empty() {
1857 let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1858 let after_where_clause_str = rewrite_where_clause(
1859 context,
1860 &after_where_clause,
1861 context.config.brace_style(),
1862 Shape::indented(indent, context.config),
1863 false,
1864 ";",
1865 None,
1866 rhs_hi,
1867 option,
1868 )?;
1869 result.push_str(&after_where_clause_str);
1870 }
1871
1872 result += ";";
1873 Ok(result)
1874}
1875
1876fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1877 (
1878 if config.space_before_colon() { " " } else { "" },
1879 if config.space_after_colon() { " " } else { "" },
1880 )
1881}
1882
1883pub(crate) fn rewrite_struct_field_prefix(
1884 context: &RewriteContext<'_>,
1885 field: &ast::FieldDef,
1886) -> RewriteResult {
1887 let vis = format_visibility(context, &field.vis);
1888 let mut_restriction = format_mut_restriction(context, field.mut_restriction());
1889 let safety = format_safety(field.safety());
1890 let type_annotation_spacing = type_annotation_spacing(context.config);
1891 Ok(match field.ident {
1892 Some(name) => format!(
1893 "{vis}{mut_restriction}{safety}{}{}:",
1894 rewrite_ident(context, name),
1895 type_annotation_spacing.0
1896 ),
1897 None => format!("{vis}{mut_restriction}{safety}"),
1898 })
1899}
1900
1901impl Rewrite for ast::FieldDef {
1902 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1903 self.rewrite_result(context, shape).ok()
1904 }
1905
1906 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
1907 rewrite_struct_field(context, self, shape, 0)
1908 }
1909}
1910
1911pub(crate) fn rewrite_struct_field(
1912 context: &RewriteContext<'_>,
1913 field: &ast::FieldDef,
1914 shape: Shape,
1915 lhs_max_width: usize,
1916) -> RewriteResult {
1917 if field.default_value().is_some() {
1919 return Err(RewriteError::Unknown);
1920 }
1921
1922 if contains_skip(&field.attrs) {
1923 return Ok(context.snippet(field.span()).to_owned());
1924 }
1925
1926 let type_annotation_spacing = type_annotation_spacing(context.config);
1927 let prefix = rewrite_struct_field_prefix(context, field)?;
1928
1929 let attrs_str = field.attrs.rewrite_result(context, shape)?;
1930 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1931 let missing_span = if field.attrs.is_empty() {
1932 mk_sp(field.span.lo(), field.span.lo())
1933 } else {
1934 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1935 };
1936 let mut spacing = String::from(if field.ident.is_some() {
1937 type_annotation_spacing.1
1938 } else {
1939 ""
1940 });
1941 let attr_prefix = combine_strs_with_missing_comments(
1943 context,
1944 &attrs_str,
1945 &prefix,
1946 missing_span,
1947 shape,
1948 attrs_extendable,
1949 )?;
1950 let overhead = trimmed_last_line_width(&attr_prefix);
1951 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1952 for _ in 0..lhs_offset {
1953 spacing.push(' ');
1954 }
1955 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1957 spacing.push(' ');
1958 }
1959
1960 let orig_ty = shape
1961 .offset_left_opt(overhead + spacing.len())
1962 .and_then(|ty_shape| field.ty.rewrite_result(context, ty_shape).ok());
1963
1964 if let Some(ref ty) = orig_ty {
1965 if !ty.contains('\n') && !contains_comment(context.snippet(missing_span)) {
1966 return Ok(attr_prefix + &spacing + ty);
1967 }
1968 }
1969
1970 let is_prefix_empty = prefix.is_empty();
1971 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, &RhsAssignKind::Ty, shape)?;
1973 let field_str = if is_prefix_empty {
1975 field_str.trim_start()
1976 } else {
1977 &field_str
1978 };
1979 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1980}
1981
1982pub(crate) struct StaticParts<'a> {
1983 prefix: &'a str,
1984 safety: ast::Safety,
1985 vis: &'a ast::Visibility,
1986 ident: symbol::Ident,
1987 generics: Option<&'a ast::Generics>,
1988 ty: &'a ast::Ty,
1989 mutability: ast::Mutability,
1990 expr_opt: Option<&'a ast::Expr>,
1991 defaultness: Option<ast::Defaultness>,
1992 span: Span,
1993}
1994
1995impl<'a> StaticParts<'a> {
1996 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1997 let (defaultness, prefix, safety, ident, ty, mutability, expr_opt, generics) =
1998 match &item.kind {
1999 ast::ItemKind::Static(s) => (
2000 None,
2001 "static",
2002 s.safety,
2003 s.ident,
2004 &s.ty,
2005 s.mutability,
2006 s.expr.as_deref(),
2007 None,
2008 ),
2009 ast::ItemKind::Const(c) => (
2010 Some(c.defaultness),
2011 if c.kind == ast::ConstItemKind::TypeConst {
2012 "type const"
2013 } else {
2014 "const"
2015 },
2016 ast::Safety::Default,
2017 c.ident,
2018 &c.ty,
2019 ast::Mutability::Not,
2020 c.body.as_deref(),
2021 Some(&c.generics),
2022 ),
2023 _ => unreachable!(),
2024 };
2025 StaticParts {
2026 prefix,
2027 safety,
2028 vis: &item.vis,
2029 ident,
2030 generics,
2031 ty,
2032 mutability,
2033 expr_opt,
2034 defaultness,
2035 span: item.span,
2036 }
2037 }
2038
2039 pub(crate) fn from_trait_item(ti: &'a ast::AssocItem, ident: Ident) -> Self {
2040 let (defaultness, ty, expr_opt, generics, prefix) = match &ti.kind {
2041 ast::AssocItemKind::Const(c) => {
2042 let prefix = if c.kind == ast::ConstItemKind::TypeConst {
2043 "type const"
2044 } else {
2045 "const"
2046 };
2047 (
2048 c.defaultness,
2049 &c.ty,
2050 c.body.as_deref(),
2051 Some(&c.generics),
2052 prefix,
2053 )
2054 }
2055 _ => unreachable!(),
2056 };
2057 StaticParts {
2058 prefix,
2059 safety: ast::Safety::Default,
2060 vis: &ti.vis,
2061 ident,
2062 generics,
2063 ty,
2064 mutability: ast::Mutability::Not,
2065 expr_opt,
2066 defaultness: Some(defaultness),
2067 span: ti.span,
2068 }
2069 }
2070
2071 pub(crate) fn from_impl_item(ii: &'a ast::AssocItem, ident: Ident) -> Self {
2072 let (defaultness, ty, expr_opt, generics, prefix) = match &ii.kind {
2073 ast::AssocItemKind::Const(c) => {
2074 let prefix = if c.kind == ast::ConstItemKind::TypeConst {
2075 "type const"
2076 } else {
2077 "const"
2078 };
2079 (
2080 c.defaultness,
2081 &c.ty,
2082 c.body.as_deref(),
2083 Some(&c.generics),
2084 prefix,
2085 )
2086 }
2087 _ => unreachable!(),
2088 };
2089 StaticParts {
2090 prefix,
2091 safety: ast::Safety::Default,
2092 vis: &ii.vis,
2093 ident,
2094 generics,
2095 ty,
2096 mutability: ast::Mutability::Not,
2097 expr_opt,
2098 defaultness: Some(defaultness),
2099 span: ii.span,
2100 }
2101 }
2102}
2103
2104fn rewrite_static(
2105 context: &RewriteContext<'_>,
2106 static_parts: &StaticParts<'_>,
2107 offset: Indent,
2108) -> Option<String> {
2109 if static_parts
2111 .generics
2112 .is_some_and(|g| !g.params.is_empty() || !g.where_clause.is_empty())
2113 {
2114 return None;
2115 }
2116
2117 let colon = colon_spaces(context.config);
2118 let mut prefix = format!(
2119 "{}{}{}{} {}{}{}",
2120 format_visibility(context, static_parts.vis),
2121 static_parts.defaultness.map_or("", format_defaultness),
2122 format_safety(static_parts.safety),
2123 static_parts.prefix,
2124 format_mutability(static_parts.mutability),
2125 rewrite_ident(context, static_parts.ident),
2126 colon,
2127 );
2128 let ty_shape =
2130 Shape::indented(offset.block_only(), context.config).offset_left_opt(prefix.len() + 2)?;
2131 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
2132 Some(ty_str) => ty_str,
2133 None => {
2134 if prefix.ends_with(' ') {
2135 prefix.pop();
2136 }
2137 let nested_indent = offset.block_indent(context.config);
2138 let nested_shape = Shape::indented(nested_indent, context.config);
2139 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
2140 format!(
2141 "{}{}",
2142 nested_indent.to_string_with_newline(context.config),
2143 ty_str
2144 )
2145 }
2146 };
2147
2148 if let Some(expr) = static_parts.expr_opt {
2149 let comments_lo = context.snippet_provider.span_after(static_parts.span, "=");
2150 let expr_lo = expr.span.lo();
2151 let comments_span = mk_sp(comments_lo, expr_lo);
2152
2153 let lhs = format!("{prefix}{ty_str} =");
2154
2155 let remaining_width = context.budget(offset.block_indent + 1);
2157 rewrite_assign_rhs_with_comments(
2158 context,
2159 &lhs,
2160 expr,
2161 Shape::legacy(remaining_width, offset.block_only()),
2162 &RhsAssignKind::Expr(&expr.kind, expr.span),
2163 RhsTactics::Default,
2164 comments_span,
2165 true,
2166 )
2167 .ok()
2168 .map(|res| recover_comment_removed(res, static_parts.span, context))
2169 .map(|s| if s.ends_with(';') { s } else { s + ";" })
2170 } else {
2171 Some(format!("{prefix}{ty_str};"))
2172 }
2173}
2174
2175struct OpaqueType<'a> {
2181 bounds: &'a ast::GenericBounds,
2182}
2183
2184impl<'a> Rewrite for OpaqueType<'a> {
2185 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2186 let shape = shape.offset_left_opt(5)?; self.bounds
2188 .rewrite(context, shape)
2189 .map(|s| format!("impl {}", s))
2190 }
2191}
2192
2193impl Rewrite for ast::FnRetTy {
2194 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2195 self.rewrite_result(context, shape).ok()
2196 }
2197
2198 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2199 match *self {
2200 ast::FnRetTy::Default(_) => Ok(String::new()),
2201 ast::FnRetTy::Ty(ref ty) => {
2202 let arrow_width = "-> ".len();
2203 if context.config.style_edition() <= StyleEdition::Edition2021
2204 || context.config.indent_style() == IndentStyle::Visual
2205 {
2206 let inner_width = shape
2207 .width
2208 .checked_sub(arrow_width)
2209 .max_width_error(shape.width, self.span())?;
2210 return ty
2211 .rewrite_result(
2212 context,
2213 Shape::legacy(inner_width, shape.indent + arrow_width),
2214 )
2215 .map(|r| format!("-> {}", r));
2216 }
2217
2218 let shape = shape.offset_left(arrow_width, self.span())?;
2219
2220 ty.rewrite_result(context, shape)
2221 .map(|s| format!("-> {}", s))
2222 }
2223 }
2224 }
2225}
2226
2227fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
2228 match ty.kind {
2229 ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
2230 _ => false,
2231 }
2232}
2233
2234fn get_missing_param_comments(
2241 context: &RewriteContext<'_>,
2242 pat_span: Span,
2243 ty_span: Span,
2244 shape: Shape,
2245) -> (String, String) {
2246 let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
2247
2248 let span_before_colon = {
2249 let missing_comment_span_hi = context
2250 .snippet_provider
2251 .span_before(missing_comment_span, ":");
2252 mk_sp(pat_span.hi(), missing_comment_span_hi)
2253 };
2254 let span_after_colon = {
2255 let missing_comment_span_lo = context
2256 .snippet_provider
2257 .span_after(missing_comment_span, ":");
2258 mk_sp(missing_comment_span_lo, ty_span.lo())
2259 };
2260
2261 let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
2262 .ok()
2263 .filter(|comment| !comment.is_empty())
2264 .map_or(String::new(), |comment| format!(" {}", comment));
2265 let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
2266 .ok()
2267 .filter(|comment| !comment.is_empty())
2268 .map_or(String::new(), |comment| format!("{} ", comment));
2269 (comment_before_colon, comment_after_colon)
2270}
2271
2272impl Rewrite for ast::Param {
2273 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2274 self.rewrite_result(context, shape).ok()
2275 }
2276
2277 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
2278 let param_attrs_result = self
2279 .attrs
2280 .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2281 let (span, has_multiple_attr_lines, has_doc_comments) = if !self.attrs.is_empty() {
2284 let num_attrs = self.attrs.len();
2285 (
2286 mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
2287 param_attrs_result.contains('\n'),
2288 self.attrs.iter().any(|a| a.is_doc_comment()),
2289 )
2290 } else {
2291 (mk_sp(self.span.lo(), self.span.lo()), false, false)
2292 };
2293
2294 if let Some(ref explicit_self) = self.to_self() {
2295 rewrite_explicit_self(
2296 context,
2297 explicit_self,
2298 ¶m_attrs_result,
2299 span,
2300 shape,
2301 has_multiple_attr_lines,
2302 )
2303 } else if is_named_param(self) {
2304 let param_name = &self
2305 .pat
2306 .rewrite_result(context, Shape::legacy(shape.width, shape.indent))?;
2307 let mut result = combine_strs_with_missing_comments(
2308 context,
2309 ¶m_attrs_result,
2310 param_name,
2311 span,
2312 shape,
2313 !has_multiple_attr_lines && !has_doc_comments,
2314 )?;
2315
2316 if !is_empty_infer(&*self.ty, self.pat.span) {
2317 let (before_comment, after_comment) =
2318 get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
2319 result.push_str(&before_comment);
2320 result.push_str(colon_spaces(context.config));
2321 result.push_str(&after_comment);
2322 let overhead = last_line_width(&result);
2323 let max_width = shape
2324 .width
2325 .checked_sub(overhead)
2326 .max_width_error(shape.width, self.span())?;
2327 if let Ok(ty_str) = self
2328 .ty
2329 .rewrite_result(context, Shape::legacy(max_width, shape.indent))
2330 {
2331 result.push_str(&ty_str);
2332 } else {
2333 let prev_str = if param_attrs_result.is_empty() {
2334 param_attrs_result
2335 } else {
2336 param_attrs_result + &shape.to_string_with_newline(context.config)
2337 };
2338
2339 result = combine_strs_with_missing_comments(
2340 context,
2341 &prev_str,
2342 param_name,
2343 span,
2344 shape,
2345 !has_multiple_attr_lines,
2346 )?;
2347 result.push_str(&before_comment);
2348 result.push_str(colon_spaces(context.config));
2349 result.push_str(&after_comment);
2350 let overhead = last_line_width(&result);
2351 let max_width = shape
2352 .width
2353 .checked_sub(overhead)
2354 .max_width_error(shape.width, self.span())?;
2355 let ty_str = self
2356 .ty
2357 .rewrite_result(context, Shape::legacy(max_width, shape.indent))?;
2358 result.push_str(&ty_str);
2359 }
2360 }
2361
2362 Ok(result)
2363 } else {
2364 self.ty.rewrite_result(context, shape)
2365 }
2366 }
2367}
2368
2369fn rewrite_opt_lifetime(
2370 context: &RewriteContext<'_>,
2371 lifetime: Option<ast::Lifetime>,
2372) -> RewriteResult {
2373 let Some(l) = lifetime else {
2374 return Ok(String::new());
2375 };
2376 let mut result = l.rewrite_result(
2377 context,
2378 Shape::legacy(context.config.max_width(), Indent::empty()),
2379 )?;
2380 result.push(' ');
2381 Ok(result)
2382}
2383
2384fn rewrite_explicit_self(
2385 context: &RewriteContext<'_>,
2386 explicit_self: &ast::ExplicitSelf,
2387 param_attrs: &str,
2388 span: Span,
2389 shape: Shape,
2390 has_multiple_attr_lines: bool,
2391) -> RewriteResult {
2392 let self_str = match explicit_self.node {
2393 ast::SelfKind::Region(lt, m) => {
2394 let mut_str = format_mutability(m);
2395 let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2396 format!("&{lifetime_str}{mut_str}self")
2397 }
2398 ast::SelfKind::Pinned(lt, m) => {
2399 let mut_str = m.ptr_str();
2400 let lifetime_str = rewrite_opt_lifetime(context, lt)?;
2401 format!("&{lifetime_str}pin {mut_str} self")
2402 }
2403 ast::SelfKind::Explicit(ref ty, mutability) => {
2404 let type_str = ty.rewrite_result(
2405 context,
2406 Shape::legacy(context.config.max_width(), Indent::empty()),
2407 )?;
2408 format!("{}self: {}", format_mutability(mutability), type_str)
2409 }
2410 ast::SelfKind::Value(mutability) => format!("{}self", format_mutability(mutability)),
2411 };
2412 Ok(combine_strs_with_missing_comments(
2413 context,
2414 param_attrs,
2415 &self_str,
2416 span,
2417 shape,
2418 !has_multiple_attr_lines,
2419 )?)
2420}
2421
2422pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2423 if param.attrs.is_empty() {
2424 if is_named_param(param) {
2425 param.pat.span.lo()
2426 } else {
2427 param.ty.span.lo()
2428 }
2429 } else {
2430 param.attrs[0].span.lo()
2431 }
2432}
2433
2434pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2435 match param.ty.kind {
2436 ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2437 ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2438 _ => param.ty.span.hi(),
2439 }
2440}
2441
2442pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2443 !matches!(param.pat.kind, ast::PatKind::Missing)
2444}
2445
2446#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2447pub(crate) enum FnBraceStyle {
2448 SameLine,
2449 NextLine,
2450 None,
2451}
2452
2453fn rewrite_fn_base(
2455 context: &RewriteContext<'_>,
2456 indent: Indent,
2457 ident: symbol::Ident,
2458 fn_sig: &FnSig<'_>,
2459 span: Span,
2460 fn_brace_style: FnBraceStyle,
2461) -> Result<(String, bool, bool), RewriteError> {
2462 let mut force_new_line_for_brace = false;
2463
2464 let where_clause = &fn_sig.generics.where_clause;
2465
2466 let mut result = String::with_capacity(1024);
2467 result.push_str(&fn_sig.to_str(context));
2468
2469 result.push_str("fn ");
2471
2472 let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2474 4
2476 } else {
2477 2
2479 };
2480 let used_width = last_line_used_width(&result, indent.width());
2481 let one_line_budget = context.budget(used_width + overhead);
2482 let shape = Shape {
2483 width: one_line_budget,
2484 indent,
2485 offset: used_width,
2486 };
2487 let fd = fn_sig.decl;
2488 let generics_str = rewrite_generics(
2489 context,
2490 rewrite_ident(context, ident),
2491 &fn_sig.generics,
2492 shape,
2493 )?;
2494 result.push_str(&generics_str);
2495
2496 let snuggle_angle_bracket = generics_str
2497 .lines()
2498 .last()
2499 .map_or(false, |l| l.trim_start().len() == 1);
2500
2501 let ret_str = fd
2504 .output
2505 .rewrite_result(context, Shape::indented(indent, context.config))?;
2506
2507 let multi_line_ret_str = ret_str.contains('\n');
2508 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2509
2510 let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2512 context,
2513 &result,
2514 indent,
2515 ret_str_len,
2516 fn_brace_style,
2517 multi_line_ret_str,
2518 );
2519
2520 debug!(
2521 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2522 one_line_budget, multi_line_budget, param_indent
2523 );
2524
2525 result.push('(');
2526 if one_line_budget == 0
2528 && !snuggle_angle_bracket
2529 && context.config.indent_style() == IndentStyle::Visual
2530 {
2531 result.push_str(¶m_indent.to_string_with_newline(context.config));
2532 }
2533
2534 let params_end = if fd.inputs.is_empty() {
2535 context
2536 .snippet_provider
2537 .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), ")")
2538 } else {
2539 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2540 context.snippet_provider.span_after(last_span, ")")
2541 };
2542 let params_span = mk_sp(
2543 context
2544 .snippet_provider
2545 .span_after(mk_sp(fn_sig.generics.span.hi(), span.hi()), "("),
2546 params_end,
2547 );
2548 let param_str = rewrite_params(
2549 context,
2550 &fd.inputs,
2551 one_line_budget,
2552 multi_line_budget,
2553 indent,
2554 param_indent,
2555 params_span,
2556 fd.c_variadic(),
2557 )?;
2558
2559 let put_params_in_block = match context.config.indent_style() {
2560 IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2561 _ => false,
2562 } && !fd.inputs.is_empty();
2563
2564 let mut params_last_line_contains_comment = false;
2565 let mut no_params_and_over_max_width = false;
2566
2567 if put_params_in_block {
2568 param_indent = indent.block_indent(context.config);
2569 result.push_str(¶m_indent.to_string_with_newline(context.config));
2570 result.push_str(¶m_str);
2571 result.push_str(&indent.to_string_with_newline(context.config));
2572 result.push(')');
2573 } else {
2574 result.push_str(¶m_str);
2575 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2576 let closing_paren_overflow_max_width =
2579 fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2580 params_last_line_contains_comment = param_str
2583 .lines()
2584 .last()
2585 .map_or(false, |last_line| last_line.contains("//"));
2586
2587 if context.config.style_edition() >= StyleEdition::Edition2024 {
2588 if params_last_line_contains_comment {
2589 result.push_str(&indent.to_string_with_newline(context.config));
2590 result.push(')');
2591 no_params_and_over_max_width = true;
2592 } else if closing_paren_overflow_max_width {
2593 result.push(')');
2594 result.push_str(&indent.to_string_with_newline(context.config));
2595 no_params_and_over_max_width = true;
2596 } else {
2597 result.push(')');
2598 }
2599 } else {
2600 if closing_paren_overflow_max_width || params_last_line_contains_comment {
2601 result.push_str(&indent.to_string_with_newline(context.config));
2602 }
2603 result.push(')');
2604 }
2605 }
2606
2607 if let ast::FnRetTy::Ty(..) = fd.output {
2609 let ret_should_indent = match context.config.indent_style() {
2610 IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2612 _ if params_last_line_contains_comment => false,
2613 _ if result.contains('\n') || multi_line_ret_str => true,
2614 _ => {
2615 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2619
2620 if where_clause.predicates.is_empty() {
2623 sig_length += 2;
2624 }
2625
2626 sig_length > context.config.max_width()
2627 }
2628 };
2629 let ret_shape = if ret_should_indent {
2630 if context.config.style_edition() <= StyleEdition::Edition2021
2631 || context.config.indent_style() == IndentStyle::Visual
2632 {
2633 let indent = if param_str.is_empty() {
2634 force_new_line_for_brace = true;
2636 indent + 4
2637 } else {
2638 param_indent
2642 };
2643
2644 result.push_str(&indent.to_string_with_newline(context.config));
2645 Shape::indented(indent, context.config)
2646 } else {
2647 let mut ret_shape = Shape::indented(indent, context.config);
2648 if param_str.is_empty() {
2649 force_new_line_for_brace = true;
2651 ret_shape = if context.use_block_indent() {
2652 ret_shape.offset_left_opt(4).unwrap_or(ret_shape)
2653 } else {
2654 ret_shape.indent = ret_shape.indent + 4;
2655 ret_shape
2656 };
2657 }
2658
2659 result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2660 ret_shape
2661 }
2662 } else {
2663 if context.config.style_edition() >= StyleEdition::Edition2024 {
2664 if !param_str.is_empty() || !no_params_and_over_max_width {
2665 result.push(' ');
2666 }
2667 } else {
2668 result.push(' ');
2669 }
2670
2671 let ret_shape = Shape::indented(indent, context.config);
2672 ret_shape
2673 .offset_left_opt(last_line_width(&result))
2674 .unwrap_or(ret_shape)
2675 };
2676
2677 let exceeds_max_width = last_line_width(&result) + ret_str_len > context.config.max_width();
2678
2679 if multi_line_ret_str
2680 || ret_should_indent
2681 || (context.config.style_edition() >= StyleEdition::Edition2027 && exceeds_max_width)
2682 {
2683 let ret_str = fd.output.rewrite_result(context, ret_shape)?;
2686 result.push_str(&ret_str);
2687 } else {
2688 result.push_str(&ret_str);
2689 }
2690
2691 let snippet_lo = fd.output.span().hi();
2693 if where_clause.predicates.is_empty() {
2694 let snippet_hi = span.hi();
2695 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2696 let original_starts_with_newline = snippet
2698 .find(|c| c != ' ')
2699 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2700 let original_ends_with_newline = snippet
2701 .rfind(|c| c != ' ')
2702 .map_or(false, |i| snippet[i..].ends_with('\n'));
2703 let snippet = snippet.trim();
2704 if !snippet.is_empty() {
2705 result.push(if original_starts_with_newline {
2706 '\n'
2707 } else {
2708 ' '
2709 });
2710 result.push_str(snippet);
2711 if original_ends_with_newline {
2712 force_new_line_for_brace = true;
2713 }
2714 }
2715 }
2716 }
2717
2718 let pos_before_where = match fd.output {
2719 ast::FnRetTy::Default(..) => params_span.hi(),
2720 ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
2721 };
2722
2723 let is_params_multi_lined = param_str.contains('\n');
2724
2725 let space = if put_params_in_block && ret_str.is_empty() {
2726 WhereClauseSpace::Space
2727 } else {
2728 WhereClauseSpace::Newline
2729 };
2730 let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2731 if is_params_multi_lined {
2732 option.veto_single_line();
2733 }
2734 let where_clause_str = rewrite_where_clause(
2735 context,
2736 &where_clause,
2737 context.config.brace_style(),
2738 Shape::indented(indent, context.config),
2739 true,
2740 "{",
2741 Some(span.hi()),
2742 pos_before_where,
2743 option,
2744 )?;
2745 if where_clause_str.is_empty() {
2748 if let ast::FnRetTy::Default(ret_span) = fd.output {
2749 match recover_missing_comment_in_span(
2750 mk_sp(ret_span.lo(), span.hi()),
2752 shape,
2753 context,
2754 last_line_width(&result),
2755 ) {
2756 Ok(ref missing_comment) if !missing_comment.is_empty() => {
2757 result.push_str(missing_comment);
2758 force_new_line_for_brace = true;
2759 }
2760 _ => (),
2761 }
2762 }
2763 }
2764
2765 result.push_str(&where_clause_str);
2766
2767 let ends_with_comment = last_line_contains_single_line_comment(&result);
2768 force_new_line_for_brace |= ends_with_comment;
2769 force_new_line_for_brace |=
2770 is_params_multi_lined && context.config.where_single_line() && !where_clause_str.is_empty();
2771 Ok((result, ends_with_comment, force_new_line_for_brace))
2772}
2773
2774#[derive(Copy, Clone)]
2776enum WhereClauseSpace {
2777 Space,
2779 Newline,
2781 None,
2783}
2784
2785#[derive(Copy, Clone)]
2786struct WhereClauseOption {
2787 suppress_comma: bool, snuggle: WhereClauseSpace,
2789 allow_single_line: bool, veto_single_line: bool, }
2792
2793impl WhereClauseOption {
2794 fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2795 WhereClauseOption {
2796 suppress_comma,
2797 snuggle,
2798 allow_single_line: false,
2799 veto_single_line: false,
2800 }
2801 }
2802
2803 fn snuggled(current: &str) -> WhereClauseOption {
2804 WhereClauseOption {
2805 suppress_comma: false,
2806 snuggle: if last_line_width(current) == 1 {
2807 WhereClauseSpace::Space
2808 } else {
2809 WhereClauseSpace::Newline
2810 },
2811 allow_single_line: false,
2812 veto_single_line: false,
2813 }
2814 }
2815
2816 fn suppress_comma(&mut self) {
2817 self.suppress_comma = true
2818 }
2819
2820 fn allow_single_line(&mut self) {
2821 self.allow_single_line = true
2822 }
2823
2824 fn snuggle(&mut self) {
2825 self.snuggle = WhereClauseSpace::Space
2826 }
2827
2828 fn veto_single_line(&mut self) {
2829 self.veto_single_line = true;
2830 }
2831}
2832
2833fn rewrite_params(
2834 context: &RewriteContext<'_>,
2835 params: &[ast::Param],
2836 one_line_budget: usize,
2837 multi_line_budget: usize,
2838 indent: Indent,
2839 param_indent: Indent,
2840 span: Span,
2841 variadic: bool,
2842) -> RewriteResult {
2843 if params.is_empty() {
2844 let comment = context
2845 .snippet(mk_sp(
2846 span.lo(),
2847 span.hi() - BytePos(1),
2849 ))
2850 .trim();
2851 return Ok(comment.to_owned());
2852 }
2853 let param_items: Vec<_> = itemize_list(
2854 context.snippet_provider,
2855 params.iter(),
2856 ")",
2857 ",",
2858 |param| span_lo_for_param(param),
2859 |param| param.ty.span.hi(),
2860 |param| {
2861 param
2862 .rewrite_result(context, Shape::legacy(multi_line_budget, param_indent))
2863 .or_else(|_| Ok(context.snippet(param.span()).to_owned()))
2864 },
2865 span.lo(),
2866 span.hi(),
2867 false,
2868 )
2869 .collect();
2870
2871 let tactic = definitive_tactic(
2872 ¶m_items,
2873 context
2874 .config
2875 .fn_params_layout()
2876 .to_list_tactic(param_items.len()),
2877 Separator::Comma,
2878 one_line_budget,
2879 );
2880 let budget = match tactic {
2881 DefinitiveListTactic::Horizontal => one_line_budget,
2882 _ => multi_line_budget,
2883 };
2884 let indent = match context.config.indent_style() {
2885 IndentStyle::Block => indent.block_indent(context.config),
2886 IndentStyle::Visual => param_indent,
2887 };
2888 let trailing_separator = if variadic {
2889 SeparatorTactic::Never
2890 } else {
2891 match context.config.indent_style() {
2892 IndentStyle::Block => context.config.trailing_comma(),
2893 IndentStyle::Visual => SeparatorTactic::Never,
2894 }
2895 };
2896 let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2897 .tactic(tactic)
2898 .trailing_separator(trailing_separator)
2899 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2900 .preserve_newline(true);
2901 write_list(¶m_items, &fmt)
2902}
2903
2904fn compute_budgets_for_params(
2905 context: &RewriteContext<'_>,
2906 result: &str,
2907 indent: Indent,
2908 ret_str_len: usize,
2909 fn_brace_style: FnBraceStyle,
2910 force_vertical_layout: bool,
2911) -> (usize, usize, Indent) {
2912 debug!(
2913 "compute_budgets_for_params {} {:?}, {}, {:?}",
2914 result.len(),
2915 indent,
2916 ret_str_len,
2917 fn_brace_style,
2918 );
2919 if !result.contains('\n') && !force_vertical_layout {
2921 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2923 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2924 match fn_brace_style {
2925 FnBraceStyle::None => used_space += 1, FnBraceStyle::SameLine => used_space += 2, FnBraceStyle::NextLine => (),
2928 }
2929 let one_line_budget = context.budget(used_space);
2930
2931 if one_line_budget > 0 {
2932 let (indent, multi_line_budget) = match context.config.indent_style() {
2934 IndentStyle::Block => {
2935 let indent = indent.block_indent(context.config);
2936 (indent, context.budget(indent.width() + 1))
2937 }
2938 IndentStyle::Visual => {
2939 let indent = indent + result.len() + 1;
2940 let multi_line_overhead = match fn_brace_style {
2941 FnBraceStyle::SameLine => 4,
2942 _ => 2,
2943 } + indent.width();
2944 (indent, context.budget(multi_line_overhead))
2945 }
2946 };
2947
2948 return (one_line_budget, multi_line_budget, indent);
2949 }
2950 }
2951
2952 let new_indent = indent.block_indent(context.config);
2954 let used_space = match context.config.indent_style() {
2955 IndentStyle::Block => new_indent.width() + 1,
2957 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2959 };
2960 (0, context.budget(used_space), new_indent)
2961}
2962
2963fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2964 let predicate_count = where_clause.predicates.len();
2965
2966 if config.where_single_line() && predicate_count == 1 {
2967 return FnBraceStyle::SameLine;
2968 }
2969 let brace_style = config.brace_style();
2970
2971 let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2972 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2973 if use_next_line {
2974 FnBraceStyle::NextLine
2975 } else {
2976 FnBraceStyle::SameLine
2977 }
2978}
2979
2980fn rewrite_generics(
2981 context: &RewriteContext<'_>,
2982 ident: &str,
2983 generics: &ast::Generics,
2984 shape: Shape,
2985) -> RewriteResult {
2986 if generics.params.is_empty() {
2990 return Ok(ident.to_owned());
2991 }
2992
2993 let params = generics.params.iter();
2994 overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2995}
2996
2997fn generics_shape_from_config(
2998 config: &Config,
2999 shape: Shape,
3000 offset: usize,
3001 span: Span,
3002) -> Result<Shape, ExceedsMaxWidthError> {
3003 match config.indent_style() {
3004 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2, span),
3005 IndentStyle::Block => {
3006 shape
3008 .block()
3009 .block_indent(config.tab_spaces())
3010 .with_max_width(config)
3011 .sub_width(1, span)
3012 }
3013 }
3014}
3015
3016fn rewrite_where_clause_rfc_style(
3017 context: &RewriteContext<'_>,
3018 predicates: &[ast::WherePredicate],
3019 where_span: Span,
3020 shape: Shape,
3021 terminator: &str,
3022 span_end: Option<BytePos>,
3023 span_end_before_where: BytePos,
3024 where_clause_option: WhereClauseOption,
3025) -> RewriteResult {
3026 let (where_keyword, allow_single_line) = rewrite_where_keyword(
3027 context,
3028 predicates,
3029 where_span,
3030 shape,
3031 span_end_before_where,
3032 where_clause_option,
3033 )?;
3034
3035 let clause_shape = shape
3037 .block()
3038 .with_max_width(context.config)
3039 .block_left(context.config.tab_spaces(), where_span)?
3040 .sub_width(1, where_span)?;
3041 let force_single_line = context.config.where_single_line()
3042 && predicates.len() == 1
3043 && !where_clause_option.veto_single_line;
3044
3045 let preds_str = rewrite_bounds_on_where_clause(
3046 context,
3047 predicates,
3048 clause_shape,
3049 terminator,
3050 span_end,
3051 where_clause_option,
3052 force_single_line,
3053 )?;
3054
3055 let clause_sep =
3057 if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
3058 || force_single_line
3059 {
3060 Cow::from(" ")
3061 } else {
3062 clause_shape.indent.to_string_with_newline(context.config)
3063 };
3064
3065 Ok(format!("{where_keyword}{clause_sep}{preds_str}"))
3066}
3067
3068fn rewrite_where_keyword(
3070 context: &RewriteContext<'_>,
3071 predicates: &[ast::WherePredicate],
3072 where_span: Span,
3073 shape: Shape,
3074 span_end_before_where: BytePos,
3075 where_clause_option: WhereClauseOption,
3076) -> Result<(String, bool), RewriteError> {
3077 let block_shape = shape.block().with_max_width(context.config);
3078 let clause_shape = block_shape
3080 .block_left(context.config.tab_spaces(), where_span)?
3081 .sub_width(1, where_span)?;
3082
3083 let comment_separator = |comment: &str, shape: Shape| {
3084 if comment.is_empty() {
3085 Cow::from("")
3086 } else {
3087 shape.indent.to_string_with_newline(context.config)
3088 }
3089 };
3090
3091 let (span_before, span_after) =
3092 missing_span_before_after_where(span_end_before_where, predicates, where_span);
3093 let (comment_before, comment_after) =
3094 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
3095
3096 let starting_newline = match where_clause_option.snuggle {
3097 WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
3098 WhereClauseSpace::None => Cow::from(""),
3099 _ => block_shape.indent.to_string_with_newline(context.config),
3100 };
3101
3102 let newline_before_where = comment_separator(&comment_before, shape);
3103 let newline_after_where = comment_separator(&comment_after, clause_shape);
3104 let result = format!(
3105 "{starting_newline}{comment_before}{newline_before_where}where\
3106{newline_after_where}{comment_after}"
3107 );
3108 let allow_single_line = where_clause_option.allow_single_line
3109 && comment_before.is_empty()
3110 && comment_after.is_empty();
3111
3112 Ok((result, allow_single_line))
3113}
3114
3115fn rewrite_bounds_on_where_clause(
3117 context: &RewriteContext<'_>,
3118 predicates: &[ast::WherePredicate],
3119 shape: Shape,
3120 terminator: &str,
3121 span_end: Option<BytePos>,
3122 where_clause_option: WhereClauseOption,
3123 force_single_line: bool,
3124) -> RewriteResult {
3125 let span_start = predicates[0].span().lo();
3126 let len = predicates.len();
3129 let end_of_preds = predicates[len - 1].span().hi();
3130 let span_end = span_end.unwrap_or(end_of_preds);
3131 let items = itemize_list(
3132 context.snippet_provider,
3133 predicates.iter(),
3134 terminator,
3135 ",",
3136 |pred| pred.span().lo(),
3137 |pred| pred.span().hi(),
3138 |pred| pred.rewrite_result(context, shape),
3139 span_start,
3140 span_end,
3141 false,
3142 );
3143 let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
3144 SeparatorTactic::Never
3145 } else {
3146 context.config.trailing_comma()
3147 };
3148
3149 let shape_tactic = if force_single_line {
3152 DefinitiveListTactic::Horizontal
3153 } else {
3154 DefinitiveListTactic::Vertical
3155 };
3156
3157 let preserve_newline = context.config.style_edition() <= StyleEdition::Edition2021;
3158
3159 let fmt = ListFormatting::new(shape, context.config)
3160 .tactic(shape_tactic)
3161 .trailing_separator(comma_tactic)
3162 .preserve_newline(preserve_newline);
3163 write_list(&items.collect::<Vec<_>>(), &fmt)
3164}
3165
3166fn rewrite_where_clause(
3167 context: &RewriteContext<'_>,
3168 where_clause: &ast::WhereClause,
3169 brace_style: BraceStyle,
3170 shape: Shape,
3171 on_new_line: bool,
3172 terminator: &str,
3173 span_end: Option<BytePos>,
3174 span_end_before_where: BytePos,
3175 where_clause_option: WhereClauseOption,
3176) -> RewriteResult {
3177 let ast::WhereClause {
3178 ref predicates,
3179 span: where_span,
3180 has_where_token: _,
3181 } = *where_clause;
3182
3183 if predicates.is_empty() {
3184 return Ok(String::new());
3185 }
3186
3187 if context.config.indent_style() == IndentStyle::Block {
3188 return rewrite_where_clause_rfc_style(
3189 context,
3190 predicates,
3191 where_span,
3192 shape,
3193 terminator,
3194 span_end,
3195 span_end_before_where,
3196 where_clause_option,
3197 );
3198 }
3199
3200 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
3201
3202 let offset = match context.config.indent_style() {
3203 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
3204 IndentStyle::Visual => shape.indent + extra_indent + 6,
3206 };
3207 let budget = context.config.max_width() - offset.width();
3211 let span_start = predicates[0].span().lo();
3212 let len = predicates.len();
3215 let end_of_preds = predicates[len - 1].span().hi();
3216 let span_end = span_end.unwrap_or(end_of_preds);
3217 let items = itemize_list(
3218 context.snippet_provider,
3219 predicates.iter(),
3220 terminator,
3221 ",",
3222 |pred| pred.span().lo(),
3223 |pred| pred.span().hi(),
3224 |pred| pred.rewrite_result(context, Shape::legacy(budget, offset)),
3225 span_start,
3226 span_end,
3227 false,
3228 );
3229 let item_vec = items.collect::<Vec<_>>();
3230 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
3232
3233 let mut comma_tactic = context.config.trailing_comma();
3234 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
3236 comma_tactic = SeparatorTactic::Never;
3237 }
3238
3239 let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
3240 .tactic(tactic)
3241 .trailing_separator(comma_tactic)
3242 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
3243 .preserve_newline(true);
3244 let preds_str = write_list(&item_vec, &fmt)?;
3245
3246 let end_length = if terminator == "{" {
3247 match brace_style {
3250 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
3251 BraceStyle::PreferSameLine => 2,
3252 }
3253 } else if terminator == "=" {
3254 2
3255 } else {
3256 terminator.len()
3257 };
3258 if on_new_line
3259 || preds_str.contains('\n')
3260 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
3261 {
3262 Ok(format!(
3263 "\n{}where {}",
3264 (shape.indent + extra_indent).to_string(context.config),
3265 preds_str
3266 ))
3267 } else {
3268 Ok(format!(" where {preds_str}"))
3269 }
3270}
3271
3272fn missing_span_before_after_where(
3273 before_item_span_end: BytePos,
3274 predicates: &[ast::WherePredicate],
3275 where_span: Span,
3276) -> (Span, Span) {
3277 let missing_span_before = mk_sp(before_item_span_end, where_span.lo());
3278 let pos_after_where = where_span.lo() + BytePos(5);
3280 let missing_span_after = mk_sp(pos_after_where, predicates[0].span().lo());
3281 (missing_span_before, missing_span_after)
3282}
3283
3284fn rewrite_comments_before_after_where(
3285 context: &RewriteContext<'_>,
3286 span_before_where: Span,
3287 span_after_where: Span,
3288 shape: Shape,
3289) -> Result<(String, String), RewriteError> {
3290 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
3291 let after_comment = rewrite_missing_comment(
3292 span_after_where,
3293 shape.block_indent(context.config.tab_spaces()),
3294 context,
3295 )?;
3296 Ok((before_comment, after_comment))
3297}
3298
3299fn format_header(
3300 context: &RewriteContext<'_>,
3301 item_name: &str,
3302 ident: symbol::Ident,
3303 vis: &ast::Visibility,
3304 offset: Indent,
3305) -> String {
3306 let mut result = String::with_capacity(128);
3307 let shape = Shape::indented(offset, context.config);
3308
3309 result.push_str(format_visibility(context, vis).trim());
3310
3311 let after_vis = vis.span.hi();
3313 if let Some(before_item_name) = context
3314 .snippet_provider
3315 .opt_span_before(mk_sp(vis.span.lo(), ident.span.hi()), item_name.trim())
3316 {
3317 let missing_span = mk_sp(after_vis, before_item_name);
3318 if let Ok(result_with_comment) = combine_strs_with_missing_comments(
3319 context,
3320 &result,
3321 item_name,
3322 missing_span,
3323 shape,
3324 true,
3325 ) {
3326 result = result_with_comment;
3327 }
3328 }
3329
3330 result.push_str(rewrite_ident(context, ident));
3331
3332 result
3333}
3334
3335#[derive(PartialEq, Eq, Clone, Copy)]
3336enum BracePos {
3337 None,
3338 Auto,
3339 ForceSameLine,
3340}
3341
3342fn format_generics(
3343 context: &RewriteContext<'_>,
3344 generics: &ast::Generics,
3345 brace_style: BraceStyle,
3346 brace_pos: BracePos,
3347 offset: Indent,
3348 span: Span,
3349 used_width: usize,
3350) -> Option<String> {
3351 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
3352 let mut result = rewrite_generics(context, "", generics, shape).ok()?;
3353
3354 let span_end_before_where = if !generics.params.is_empty() {
3357 generics.span.hi()
3358 } else {
3359 span.lo()
3360 };
3361 let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
3362 let budget = context.budget(last_line_used_width(&result, offset.width()));
3363 let mut option = WhereClauseOption::snuggled(&result);
3364 if brace_pos == BracePos::None {
3365 option.suppress_comma = true;
3366 }
3367 let where_clause_str = rewrite_where_clause(
3368 context,
3369 &generics.where_clause,
3370 brace_style,
3371 Shape::legacy(budget, offset.block_only()),
3372 true,
3373 "{",
3374 Some(span.hi()),
3375 span_end_before_where,
3376 option,
3377 )
3378 .ok()?;
3379 result.push_str(&where_clause_str);
3380 (
3381 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
3382 None,
3384 )
3385 } else {
3386 (
3387 brace_pos == BracePos::ForceSameLine
3388 || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
3389 || brace_style != BraceStyle::AlwaysNextLine)
3390 || trimmed_last_line_width(&result) == 1,
3391 rewrite_missing_comment(
3392 mk_sp(
3393 span_end_before_where,
3394 if brace_pos == BracePos::None {
3395 span.hi()
3396 } else {
3397 context.snippet_provider.span_before_last(span, "{")
3398 },
3399 ),
3400 shape,
3401 context,
3402 )
3403 .ok(),
3404 )
3405 };
3406 let missed_line_comments = missed_comments
3408 .filter(|missed_comments| !missed_comments.is_empty())
3409 .map_or(false, |missed_comments| {
3410 let is_block = is_last_comment_block(&missed_comments);
3411 let sep = if is_block { " " } else { "\n" };
3412 result.push_str(sep);
3413 result.push_str(&missed_comments);
3414 !is_block
3415 });
3416 if brace_pos == BracePos::None {
3417 return Some(result);
3418 }
3419 let total_used_width = last_line_used_width(&result, used_width);
3420 let remaining_budget = context.budget(total_used_width);
3421 let overhead = if brace_pos == BracePos::ForceSameLine {
3425 3
3427 } else {
3428 2
3430 };
3431 let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3432 if !forbid_same_line_brace && same_line_brace {
3433 result.push(' ');
3434 } else {
3435 result.push('\n');
3436 result.push_str(&offset.block_only().to_string(context.config));
3437 }
3438 result.push('{');
3439
3440 Some(result)
3441}
3442
3443impl Rewrite for ast::ForeignItem {
3444 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3445 self.rewrite_result(context, shape).ok()
3446 }
3447
3448 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
3449 let attrs_str = self.attrs.rewrite_result(context, shape)?;
3450 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3453
3454 let item_str = match self.kind {
3455 ast::ForeignItemKind::Fn(ref fn_kind) => {
3456 let ast::Fn {
3457 defaultness,
3458 ref sig,
3459 ident,
3460 ref generics,
3461 ref body,
3462 ..
3463 } = **fn_kind;
3464 if body.is_some() {
3465 let mut visitor = FmtVisitor::from_context(context);
3466 visitor.block_indent = shape.indent;
3467 visitor.last_pos = self.span.lo();
3468 let inner_attrs = inner_attributes(&self.attrs);
3469 let fn_ctxt = visit::FnCtxt::Foreign;
3470 visitor.visit_fn(
3471 ident,
3472 visit::FnKind::Fn(fn_ctxt, &self.vis, fn_kind),
3473 &sig.decl,
3474 self.span,
3475 defaultness,
3476 Some(&inner_attrs),
3477 );
3478 Ok(visitor.buffer.to_owned())
3479 } else {
3480 rewrite_fn_base(
3481 context,
3482 shape.indent,
3483 ident,
3484 &FnSig::from_method_sig(sig, generics, &self.vis, defaultness),
3485 span,
3486 FnBraceStyle::None,
3487 )
3488 .map(|(s, _, _)| format!("{};", s))
3489 }
3490 }
3491 ast::ForeignItemKind::Static(ref static_foreign_item) => {
3492 let vis = format_visibility(context, &self.vis);
3495 let safety = format_safety(static_foreign_item.safety);
3496 let mut_str = format_mutability(static_foreign_item.mutability);
3497 let prefix = format!(
3498 "{}{}static {}{}:",
3499 vis,
3500 safety,
3501 mut_str,
3502 rewrite_ident(context, static_foreign_item.ident)
3503 );
3504 rewrite_assign_rhs(
3506 context,
3507 prefix,
3508 &static_foreign_item.ty,
3509 &RhsAssignKind::Ty,
3510 shape.sub_width(1, static_foreign_item.ty.span)?,
3511 )
3512 .map(|s| s + ";")
3513 }
3514 ast::ForeignItemKind::TyAlias(ref ty_alias) => {
3515 let kind = ItemVisitorKind::ForeignItem;
3516 rewrite_type_alias(ty_alias, &self.vis, context, shape.indent, kind, self.span)
3517 }
3518 ast::ForeignItemKind::MacCall(ref mac) => {
3519 rewrite_macro(mac, context, shape, MacroPosition::Item)
3520 }
3521 }?;
3522
3523 let missing_span = if self.attrs.is_empty() {
3524 mk_sp(self.span.lo(), self.span.lo())
3525 } else {
3526 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3527 };
3528 combine_strs_with_missing_comments(
3529 context,
3530 &attrs_str,
3531 &item_str,
3532 missing_span,
3533 shape,
3534 false,
3535 )
3536 }
3537}
3538
3539fn rewrite_attrs(
3541 context: &RewriteContext<'_>,
3542 item: &ast::Item,
3543 item_str: &str,
3544 shape: Shape,
3545) -> RewriteResult {
3546 let attrs = filter_inline_attrs(&item.attrs, item.span());
3547 let attrs_str = attrs.rewrite_result(context, shape)?;
3548
3549 let missed_span = if attrs.is_empty() {
3550 mk_sp(item.span.lo(), item.span.lo())
3551 } else {
3552 mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3553 };
3554
3555 let allow_extend = if attrs.len() == 1 {
3556 let line_len = attrs_str.len() + 1 + item_str.len();
3557 !attrs.first().unwrap().is_doc_comment()
3558 && context.config.inline_attribute_width() >= line_len
3559 } else {
3560 false
3561 };
3562
3563 combine_strs_with_missing_comments(
3564 context,
3565 &attrs_str,
3566 item_str,
3567 missed_span,
3568 shape,
3569 allow_extend,
3570 )
3571}
3572
3573pub(crate) fn rewrite_mod(
3576 context: &RewriteContext<'_>,
3577 item: &ast::Item,
3578 ident: Ident,
3579 attrs_shape: Shape,
3580) -> RewriteResult {
3581 let mut result = String::with_capacity(32);
3582 result.push_str(&*format_visibility(context, &item.vis));
3583 result.push_str("mod ");
3584 result.push_str(rewrite_ident(context, ident));
3585 result.push(';');
3586 rewrite_attrs(context, item, &result, attrs_shape)
3587}
3588
3589pub(crate) fn rewrite_extern_crate(
3592 context: &RewriteContext<'_>,
3593 item: &ast::Item,
3594 attrs_shape: Shape,
3595) -> RewriteResult {
3596 assert!(is_extern_crate(item));
3597 let new_str = context.snippet(item.span);
3598 let item_str = if contains_comment(new_str) {
3599 new_str.to_owned()
3600 } else {
3601 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3602 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3603 };
3604 rewrite_attrs(context, item, &item_str, attrs_shape)
3605}
3606
3607pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3609 !matches!(
3610 item.kind,
3611 ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::Yes, _))
3612 )
3613}
3614
3615pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3616 matches!(item.kind, ast::ItemKind::Use(_))
3617}
3618
3619pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3620 matches!(item.kind, ast::ItemKind::ExternCrate(..))
3621}