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