1 // Formatting top-level items - functions, structs, enums, traits, impls.
4 use std::cmp::{max, min, Ordering};
8 use rustc_ast::{ast, ptr};
9 use rustc_span::{symbol, BytePos, Span, DUMMY_SP};
11 use crate::attr::filter_inline_attrs;
13 combine_strs_with_missing_comments, contains_comment, is_last_comment_block,
14 recover_comment_removed, recover_missing_comment_in_span, rewrite_missing_comment,
17 use crate::config::lists::*;
18 use crate::config::{BraceStyle, Config, IndentStyle, Version};
20 is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
21 rewrite_assign_rhs_with_comments, RhsTactics,
23 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
24 use crate::macros::{rewrite_macro, MacroPosition};
26 use crate::rewrite::{Rewrite, RewriteContext};
27 use crate::shape::{Indent, Shape};
28 use crate::source_map::{LineRangeUtils, SpanUtils};
29 use crate::spanned::Spanned;
30 use crate::stmt::Stmt;
32 use crate::vertical::rewrite_with_alignment;
33 use crate::visitor::FmtVisitor;
35 const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
36 kind: ast::VisibilityKind::Inherited,
41 fn type_annotation_separator(config: &Config) -> &str {
45 // Statements of the form
46 // let pat: ty = init;
47 impl Rewrite for ast::Local {
48 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
50 "Local::rewrite {:?} {} {:?}",
51 self, shape.width, shape.indent
54 skip_out_of_file_lines_range!(context, self.span);
56 if contains_skip(&self.attrs) || matches!(self.kind, ast::LocalKind::InitElse(..)) {
60 let attrs_str = self.attrs.rewrite(context, shape)?;
61 let mut result = if attrs_str.is_empty() {
64 combine_strs_with_missing_comments(
69 self.attrs.last().map(|a| a.span.hi()).unwrap(),
78 let pat_shape = shape.offset_left(4)?;
80 let pat_shape = pat_shape.sub_width(1)?;
81 let pat_str = self.pat.rewrite(context, pat_shape)?;
82 result.push_str(&pat_str);
84 // String that is placed within the assignment pattern and expression.
86 let mut infix = String::with_capacity(32);
88 if let Some(ref ty) = self.ty {
89 let separator = type_annotation_separator(context.config);
90 let ty_shape = if pat_str.contains('\n') {
91 shape.with_max_width(context.config)
95 .offset_left(last_line_width(&result) + separator.len())?
99 let rewrite = ty.rewrite(context, ty_shape)?;
101 infix.push_str(separator);
102 infix.push_str(&rewrite);
105 if self.kind.init().is_some() {
106 infix.push_str(" =");
112 result.push_str(&infix);
114 if let Some((init, _els)) = self.kind.init_else_opt() {
115 // 1 = trailing semicolon;
116 let nested_shape = shape.sub_width(1)?;
118 result = rewrite_assign_rhs(context, result, init, nested_shape)?;
127 // FIXME convert to using rewrite style rather than visitor
128 // FIXME format modules in this style
132 unsafety: ast::Unsafe,
133 abi: Cow<'static, str>,
134 vis: Option<&'a ast::Visibility>,
135 body: Vec<BodyElement<'a>>,
140 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
142 unsafety: fm.unsafety,
144 ast::Extern::from_abi(fm.abi),
145 config.force_explicit_abi(),
152 .map(|i| BodyElement::ForeignItem(i))
160 enum BodyElement<'a> {
161 // Stmt(&'a ast::Stmt),
162 // Field(&'a ast::ExprField),
163 // Variant(&'a ast::Variant),
164 // Item(&'a ast::Item),
165 ForeignItem(&'a ast::ForeignItem),
168 /// Represents a fn's signature.
169 pub(crate) struct FnSig<'a> {
170 decl: &'a ast::FnDecl,
171 generics: &'a ast::Generics,
173 is_async: Cow<'a, ast::Async>,
174 constness: ast::Const,
175 defaultness: ast::Defaultness,
176 unsafety: ast::Unsafe,
177 visibility: &'a ast::Visibility,
181 pub(crate) fn from_method_sig(
182 method_sig: &'a ast::FnSig,
183 generics: &'a ast::Generics,
184 visibility: &'a ast::Visibility,
187 unsafety: method_sig.header.unsafety,
188 is_async: Cow::Borrowed(&method_sig.header.asyncness),
189 constness: method_sig.header.constness,
190 defaultness: ast::Defaultness::Final,
191 ext: method_sig.header.ext,
192 decl: &*method_sig.decl,
198 pub(crate) fn from_fn_kind(
199 fn_kind: &'a visit::FnKind<'_>,
200 generics: &'a ast::Generics,
201 decl: &'a ast::FnDecl,
202 defaultness: ast::Defaultness,
205 visit::FnKind::Fn(fn_ctxt, _, fn_sig, vis, _) => match fn_ctxt {
206 visit::FnCtxt::Assoc(..) => {
207 let mut fn_sig = FnSig::from_method_sig(fn_sig, generics, vis);
208 fn_sig.defaultness = defaultness;
214 ext: fn_sig.header.ext,
215 constness: fn_sig.header.constness,
216 is_async: Cow::Borrowed(&fn_sig.header.asyncness),
218 unsafety: fn_sig.header.unsafety,
226 fn to_str(&self, context: &RewriteContext<'_>) -> String {
227 let mut result = String::with_capacity(128);
228 // Vis defaultness constness unsafety abi.
229 result.push_str(&*format_visibility(context, &self.visibility));
230 result.push_str(format_defaultness(self.defaultness));
231 result.push_str(format_constness(self.constness));
232 result.push_str(format_async(&self.is_async));
233 result.push_str(format_unsafety(self.unsafety));
234 result.push_str(&format_extern(
236 context.config.force_explicit_abi(),
243 impl<'a> FmtVisitor<'a> {
244 fn format_item(&mut self, item: &Item<'_>) {
245 self.buffer.push_str(format_unsafety(item.unsafety));
246 self.buffer.push_str(&item.abi);
248 let snippet = self.snippet(item.span);
249 let brace_pos = snippet.find_uncommented("{").unwrap();
252 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
253 // FIXME: this skips comments between the extern keyword and the opening
255 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
256 self.block_indent = self.block_indent.block_indent(self.config);
258 if !item.body.is_empty() {
259 for item in &item.body {
260 self.format_body_element(item);
264 self.format_missing_no_indent(item.span.hi() - BytePos(1));
265 self.block_indent = self.block_indent.block_unindent(self.config);
266 let indent_str = self.block_indent.to_string(self.config);
267 self.push_str(&indent_str);
271 self.last_pos = item.span.hi();
274 fn format_body_element(&mut self, element: &BodyElement<'_>) {
276 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
280 pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
281 let item = Item::from_foreign_mod(fm, span, self.config);
282 self.format_item(&item);
285 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
286 let rewrite = item.rewrite(&self.get_context(), self.shape());
287 let hi = item.span.hi();
288 let span = if item.attrs.is_empty() {
291 mk_sp(item.attrs[0].span.lo(), hi)
293 self.push_rewrite(span, rewrite);
297 pub(crate) fn rewrite_fn_before_block(
300 ident: symbol::Ident,
303 ) -> Option<(String, FnBraceStyle)> {
304 let context = self.get_context();
306 let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
307 let (result, _, force_newline_brace) =
308 rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style)?;
311 if self.config.brace_style() == BraceStyle::AlwaysNextLine
312 || force_newline_brace
313 || last_line_width(&result) + 2 > self.shape().width
315 fn_brace_style = FnBraceStyle::NextLine
318 Some((result, fn_brace_style))
321 pub(crate) fn rewrite_required_fn(
324 ident: symbol::Ident,
326 vis: &ast::Visibility,
327 generics: &ast::Generics,
329 ) -> Option<String> {
330 // Drop semicolon or it will be interpreted as comment.
331 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
332 let context = self.get_context();
334 let (mut result, ends_with_comment, _) = rewrite_fn_base(
338 &FnSig::from_method_sig(sig, generics, vis),
343 // If `result` ends with a comment, then remember to add a newline
344 if ends_with_comment {
345 result.push_str(&indent.to_string_with_newline(context.config));
348 // Re-attach semicolon
354 pub(crate) fn single_line_fn(
358 inner_attrs: Option<&[ast::Attribute]>,
359 ) -> Option<String> {
360 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
364 let context = self.get_context();
366 if self.config.empty_item_single_line()
367 && is_empty_block(&context, block, None)
368 && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
369 && !last_line_contains_single_line_comment(fn_str)
371 return Some(format!("{} {{}}", fn_str));
374 if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
378 let res = Stmt::from_ast_node(block.stmts.first()?, true)
379 .rewrite(&self.get_context(), self.shape())?;
381 let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
382 if !res.contains('\n') && width <= self.config.max_width() {
383 Some(format!("{} {{ {} }}", fn_str, res))
389 pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
390 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
391 self.push_rewrite(static_parts.span, rewrite);
394 pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
395 let is_tuple = match struct_parts.def {
396 ast::VariantData::Tuple(..) => true,
399 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
400 .map(|s| if is_tuple { s + ";" } else { s });
401 self.push_rewrite(struct_parts.span, rewrite);
404 pub(crate) fn visit_enum(
406 ident: symbol::Ident,
407 vis: &ast::Visibility,
408 enum_def: &ast::EnumDef,
409 generics: &ast::Generics,
413 format_header(&self.get_context(), "enum ", ident, vis, self.block_indent);
414 self.push_str(&enum_header);
416 let enum_snippet = self.snippet(span);
417 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
418 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
419 let generics_str = format_generics(
422 self.config.brace_style(),
423 if enum_def.variants.is_empty() {
424 BracePos::ForceSameLine
429 // make a span that starts right after `enum Foo`
430 mk_sp(ident.span.hi(), body_start),
431 last_line_width(&enum_header),
434 self.push_str(&generics_str);
436 self.last_pos = body_start;
438 match self.format_variant_list(enum_def, body_start, span.hi()) {
439 Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
441 self.push_rewrite(mk_sp(body_start, span.hi()), rw);
442 self.block_indent = self.block_indent.block_unindent(self.config);
447 // Format the body of an enum definition
448 fn format_variant_list(
450 enum_def: &ast::EnumDef,
453 ) -> Option<String> {
454 if enum_def.variants.is_empty() {
455 let mut buffer = String::with_capacity(128);
457 let span = mk_sp(body_lo, body_hi - BytePos(1));
458 format_empty_struct_or_tuple(
468 let mut result = String::with_capacity(1024);
469 let original_offset = self.block_indent;
470 self.block_indent = self.block_indent.block_indent(self.config);
472 // If enum variants have discriminants, try to vertically align those,
473 // provided the discrims are not shifted too much to the right
474 let align_threshold: usize = self.config.enum_discrim_align_threshold();
475 let discr_ident_lens: Vec<usize> = enum_def
478 .filter(|var| var.disr_expr.is_some())
479 .map(|var| rewrite_ident(&self.get_context(), var.ident).len())
481 // cut the list at the point of longest discrim shorter than the threshold
482 // All of the discrims under the threshold will get padded, and all above - left as is.
483 let pad_discrim_ident_to = *discr_ident_lens
485 .filter(|&l| *l <= align_threshold)
489 let itemize_list_with = |one_line_width: usize| {
491 self.snippet_provider,
492 enum_def.variants.iter(),
496 if !f.attrs.is_empty() {
503 |f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
510 let mut items: Vec<_> = itemize_list_with(self.config.struct_variant_width());
512 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
513 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
514 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
515 if has_multiline_variant && has_single_line_variant {
516 items = itemize_list_with(0);
519 let shape = self.shape().sub_width(2)?;
520 let fmt = ListFormatting::new(shape, self.config)
521 .trailing_separator(self.config.trailing_comma())
522 .preserve_newline(true);
524 let list = write_list(&items, &fmt)?;
525 result.push_str(&list);
526 result.push_str(&original_offset.to_string_with_newline(self.config));
531 // Variant of an enum.
534 field: &ast::Variant,
535 one_line_width: usize,
536 pad_discrim_ident_to: usize,
537 ) -> Option<String> {
538 if contains_skip(&field.attrs) {
539 let lo = field.attrs[0].span.lo();
540 let span = mk_sp(lo, field.span.hi());
541 return Some(self.snippet(span).to_owned());
544 let context = self.get_context();
546 let shape = self.shape().sub_width(1)?;
547 let attrs_str = field.attrs.rewrite(&context, shape)?;
551 .map_or(field.span.lo(), |attr| attr.span.hi());
552 let span = mk_sp(lo, field.span.lo());
554 let variant_body = match field.data {
555 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
557 &StructParts::from_variant(field),
559 Some(one_line_width),
561 ast::VariantData::Unit(..) => rewrite_ident(&context, field.ident).to_owned(),
564 let variant_body = if let Some(ref expr) = field.disr_expr {
565 let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to);
566 rewrite_assign_rhs_with(
571 RhsTactics::AllowOverflow,
577 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
580 fn visit_impl_items(&mut self, items: &[ptr::P<ast::AssocItem>]) {
581 if self.get_context().config.reorder_impl_items() {
582 // Create visitor for each items, then reorder them.
583 let mut buffer = vec![];
585 self.visit_impl_item(item);
586 buffer.push((self.buffer.clone(), item.clone()));
590 fn is_type(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
591 if let Some(lty) = ty {
592 if let ast::TyKind::ImplTrait(..) = lty.kind {
599 fn is_opaque(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
604 a: &Option<rustc_ast::ptr::P<ast::Ty>>,
605 b: &Option<rustc_ast::ptr::P<ast::Ty>>,
607 is_type(a) && is_type(b)
611 a: &Option<rustc_ast::ptr::P<ast::Ty>>,
612 b: &Option<rustc_ast::ptr::P<ast::Ty>>,
614 is_opaque(a) && is_opaque(b)
617 // In rustc-ap-v638 the `OpaqueTy` AssocItemKind variant was removed but
618 // we still need to differentiate to maintain sorting order.
620 // type -> opaque -> const -> macro -> method
621 use crate::ast::AssocItemKind::*;
622 fn need_empty_line(a: &ast::AssocItemKind, b: &ast::AssocItemKind) -> bool {
624 (TyAlias(lty), TyAlias(rty))
625 if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) =>
629 (Const(..), Const(..)) => false,
634 buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
635 (TyAlias(lty), TyAlias(rty))
636 if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) =>
638 a.ident.as_str().cmp(&b.ident.as_str())
640 (Const(..), Const(..)) | (MacCall(..), MacCall(..)) => {
641 a.ident.as_str().cmp(&b.ident.as_str())
643 (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()),
644 (TyAlias(ty), _) if is_type(&ty.ty) => Ordering::Less,
645 (_, TyAlias(ty)) if is_type(&ty.ty) => Ordering::Greater,
646 (TyAlias(..), _) => Ordering::Less,
647 (_, TyAlias(..)) => Ordering::Greater,
648 (Const(..), _) => Ordering::Less,
649 (_, Const(..)) => Ordering::Greater,
650 (MacCall(..), _) => Ordering::Less,
651 (_, MacCall(..)) => Ordering::Greater,
653 let mut prev_kind = None;
654 for (buf, item) in buffer {
655 // Make sure that there are at least a single empty line between
656 // different impl items.
659 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind))
663 let indent_str = self.block_indent.to_string_with_newline(self.config);
664 self.push_str(&indent_str);
665 self.push_str(buf.trim());
666 prev_kind = Some(item.kind.clone());
670 self.visit_impl_item(item);
676 pub(crate) fn format_impl(
677 context: &RewriteContext<'_>,
680 ) -> Option<String> {
681 if let ast::ItemKind::Impl(impl_kind) = &item.kind {
688 let mut result = String::with_capacity(128);
689 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
690 let sep = offset.to_string_with_newline(context.config);
691 result.push_str(&ref_and_type);
693 let where_budget = if result.contains('\n') {
694 context.config.max_width()
696 context.budget(last_line_width(&result))
699 let mut option = WhereClauseOption::snuggled(&ref_and_type);
700 let snippet = context.snippet(item.span);
701 let open_pos = snippet.find_uncommented("{")? + 1;
702 if !contains_comment(&snippet[open_pos..])
704 && generics.where_clause.predicates.len() == 1
705 && !result.contains('\n')
707 option.suppress_comma();
709 option.allow_single_line();
712 let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
713 let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
714 let where_clause_str = rewrite_where_clause(
716 &generics.where_clause,
717 context.config.brace_style(),
718 Shape::legacy(where_budget, offset.block_only()),
726 // If there is no where-clause, we may have missing comments between the trait name and
727 // the opening brace.
728 if generics.where_clause.predicates.is_empty() {
729 if let Some(hi) = where_span_end {
730 match recover_missing_comment_in_span(
731 mk_sp(self_ty.span.hi(), hi),
732 Shape::indented(offset, context.config),
734 last_line_width(&result),
736 Some(ref missing_comment) if !missing_comment.is_empty() => {
737 result.push_str(missing_comment);
744 if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
745 result.push_str(&where_clause_str);
746 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
747 // if the where_clause contains extra comments AND
748 // there is only one where-clause predicate
749 // recover the suppressed comma in single line where_clause formatting
750 if generics.where_clause.predicates.len() == 1 {
753 result.push_str(&format!("{}{{{}}}", sep, sep));
755 result.push_str(" {}");
760 result.push_str(&where_clause_str);
762 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
763 match context.config.brace_style() {
764 _ if need_newline => result.push_str(&sep),
765 BraceStyle::AlwaysNextLine => result.push_str(&sep),
766 BraceStyle::PreferSameLine => result.push(' '),
767 BraceStyle::SameLineWhere => {
768 if !where_clause_str.is_empty() {
769 result.push_str(&sep);
777 // this is an impl body snippet(impl SampleImpl { /* here */ })
778 let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
779 let snippet = context.snippet(mk_sp(lo, item.span.hi()));
780 let open_pos = snippet.find_uncommented("{")? + 1;
782 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
783 let mut visitor = FmtVisitor::from_context(context);
784 let item_indent = offset.block_only().block_indent(context.config);
785 visitor.block_indent = item_indent;
786 visitor.last_pos = lo + BytePos(open_pos as u32);
788 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
789 visitor.visit_impl_items(items);
791 visitor.format_missing(item.span.hi() - BytePos(1));
793 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
794 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
796 result.push_str(&inner_indent_str);
797 result.push_str(visitor.buffer.trim());
798 result.push_str(&outer_indent_str);
799 } else if need_newline || !context.config.empty_item_single_line() {
800 result.push_str(&sep);
811 fn is_impl_single_line(
812 context: &RewriteContext<'_>,
813 items: &[ptr::P<ast::AssocItem>],
815 where_clause_str: &str,
818 let snippet = context.snippet(item.span);
819 let open_pos = snippet.find_uncommented("{")? + 1;
822 context.config.empty_item_single_line()
824 && !result.contains('\n')
825 && result.len() + where_clause_str.len() <= context.config.max_width()
826 && !contains_comment(&snippet[open_pos..]),
830 fn format_impl_ref_and_type(
831 context: &RewriteContext<'_>,
834 ) -> Option<String> {
835 if let ast::ItemKind::Impl(impl_kind) = &item.kind {
842 of_trait: ref trait_ref,
846 let mut result = String::with_capacity(128);
848 result.push_str(&format_visibility(context, &item.vis));
849 result.push_str(format_defaultness(defaultness));
850 result.push_str(format_unsafety(unsafety));
852 let shape = if context.config.version() == Version::Two {
853 Shape::indented(offset + last_line_width(&result), context.config)
855 generics_shape_from_config(
857 Shape::indented(offset + last_line_width(&result), context.config),
861 let generics_str = rewrite_generics(context, "impl", generics, shape)?;
862 result.push_str(&generics_str);
863 result.push_str(format_constness_right(constness));
865 let polarity_str = match polarity {
866 ast::ImplPolarity::Negative(_) => "!",
867 ast::ImplPolarity::Positive => "",
870 let polarity_overhead;
871 let trait_ref_overhead;
872 if let Some(ref trait_ref) = *trait_ref {
873 let result_len = last_line_width(&result);
874 result.push_str(&rewrite_trait_ref(
881 polarity_overhead = 0; // already written
882 trait_ref_overhead = " for".len();
884 polarity_overhead = polarity_str.len();
885 trait_ref_overhead = 0;
888 // Try to put the self type in a single line.
889 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
890 // If there is no where-clause adapt budget for type formatting to take space and curly
891 // brace into account.
892 match context.config.brace_style() {
893 BraceStyle::AlwaysNextLine => 0,
899 let used_space = last_line_width(&result)
902 + curly_brace_overhead;
903 // 1 = space before the type.
904 let budget = context.budget(used_space + 1);
905 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
906 if !self_ty_str.contains('\n') {
907 if trait_ref.is_some() {
908 result.push_str(" for ");
911 result.push_str(polarity_str);
913 result.push_str(&self_ty_str);
918 // Couldn't fit the self type on a single line, put it on a new line.
920 // Add indentation of one additional tab.
921 let new_line_offset = offset.block_indent(context.config);
922 result.push_str(&new_line_offset.to_string(context.config));
923 if trait_ref.is_some() {
924 result.push_str("for ");
926 result.push_str(polarity_str);
928 let budget = context.budget(last_line_width(&result) + polarity_overhead);
929 let type_offset = match context.config.indent_style() {
930 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
931 IndentStyle::Block => new_line_offset,
933 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
940 fn rewrite_trait_ref(
941 context: &RewriteContext<'_>,
942 trait_ref: &ast::TraitRef,
946 ) -> Option<String> {
947 // 1 = space between generics and trait_ref
948 let used_space = 1 + polarity_str.len() + result_len;
949 let shape = Shape::indented(offset + used_space, context.config);
950 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
951 if !trait_ref_str.contains('\n') {
952 return Some(format!(" {}{}", polarity_str, trait_ref_str));
955 // We could not make enough space for trait_ref, so put it on new line.
956 let offset = offset.block_indent(context.config);
957 let shape = Shape::indented(offset, context.config);
958 let trait_ref_str = trait_ref.rewrite(context, shape)?;
961 offset.to_string_with_newline(context.config),
967 pub(crate) struct StructParts<'a> {
969 ident: symbol::Ident,
970 vis: &'a ast::Visibility,
971 def: &'a ast::VariantData,
972 generics: Option<&'a ast::Generics>,
976 impl<'a> StructParts<'a> {
977 fn format_header(&self, context: &RewriteContext<'_>, offset: Indent) -> String {
978 format_header(context, self.prefix, self.ident, self.vis, offset)
981 fn from_variant(variant: &'a ast::Variant) -> Self {
984 ident: variant.ident,
985 vis: &DEFAULT_VISIBILITY,
992 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
993 let (prefix, def, generics) = match item.kind {
994 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
995 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
1003 generics: Some(generics),
1010 context: &RewriteContext<'_>,
1011 struct_parts: &StructParts<'_>,
1013 one_line_width: Option<usize>,
1014 ) -> Option<String> {
1015 match *struct_parts.def {
1016 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
1017 ast::VariantData::Tuple(ref fields, _) => {
1018 format_tuple_struct(context, struct_parts, fields, offset)
1020 ast::VariantData::Struct(ref fields, _) => {
1021 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
1026 pub(crate) fn format_trait(
1027 context: &RewriteContext<'_>,
1030 ) -> Option<String> {
1031 if let ast::ItemKind::Trait(trait_kind) = &item.kind {
1039 let mut result = String::with_capacity(128);
1040 let header = format!(
1042 format_visibility(context, &item.vis),
1043 format_unsafety(unsafety),
1044 format_auto(is_auto),
1046 result.push_str(&header);
1048 let body_lo = context.snippet_provider.span_after(item.span, "{");
1050 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
1052 rewrite_generics(context, rewrite_ident(context, item.ident), generics, shape)?;
1053 result.push_str(&generics_str);
1055 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
1056 if !bounds.is_empty() {
1057 let ident_hi = context
1059 .span_after(item.span, &item.ident.as_str());
1060 let bound_hi = bounds.last().unwrap().span().hi();
1061 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1062 if contains_comment(snippet) {
1066 result = rewrite_assign_rhs_with(
1071 RhsTactics::ForceNextLineWithoutIndent,
1075 // Rewrite where-clause.
1076 if !generics.where_clause.predicates.is_empty() {
1077 let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1079 let where_budget = context.budget(last_line_width(&result));
1080 let pos_before_where = if bounds.is_empty() {
1081 generics.where_clause.span.lo()
1083 bounds[bounds.len() - 1].span().hi()
1085 let option = WhereClauseOption::snuggled(&generics_str);
1086 let where_clause_str = rewrite_where_clause(
1088 &generics.where_clause,
1089 context.config.brace_style(),
1090 Shape::legacy(where_budget, offset.block_only()),
1097 // If the where-clause cannot fit on the same line,
1098 // put the where-clause on a new line
1099 if !where_clause_str.contains('\n')
1100 && last_line_width(&result) + where_clause_str.len() + offset.width()
1101 > context.config.comment_width()
1103 let width = offset.block_indent + context.config.tab_spaces() - 1;
1104 let where_indent = Indent::new(0, width);
1105 result.push_str(&where_indent.to_string_with_newline(context.config));
1107 result.push_str(&where_clause_str);
1109 let item_snippet = context.snippet(item.span);
1110 if let Some(lo) = item_snippet.find('/') {
1112 let comment_hi = body_lo - BytePos(1);
1113 let comment_lo = item.span.lo() + BytePos(lo as u32);
1114 if comment_lo < comment_hi {
1115 match recover_missing_comment_in_span(
1116 mk_sp(comment_lo, comment_hi),
1117 Shape::indented(offset, context.config),
1119 last_line_width(&result),
1121 Some(ref missing_comment) if !missing_comment.is_empty() => {
1122 result.push_str(missing_comment);
1130 match context.config.brace_style() {
1131 _ if last_line_contains_single_line_comment(&result)
1132 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1134 result.push_str(&offset.to_string_with_newline(context.config));
1136 BraceStyle::AlwaysNextLine => {
1137 result.push_str(&offset.to_string_with_newline(context.config));
1139 BraceStyle::PreferSameLine => result.push(' '),
1140 BraceStyle::SameLineWhere => {
1141 if result.contains('\n')
1142 || (!generics.where_clause.predicates.is_empty() && !items.is_empty())
1144 result.push_str(&offset.to_string_with_newline(context.config));
1152 let block_span = mk_sp(generics.where_clause.span.hi(), item.span.hi());
1153 let snippet = context.snippet(block_span);
1154 let open_pos = snippet.find_uncommented("{")? + 1;
1155 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1157 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
1158 let mut visitor = FmtVisitor::from_context(context);
1159 visitor.block_indent = offset.block_only().block_indent(context.config);
1160 visitor.last_pos = block_span.lo() + BytePos(open_pos as u32);
1163 visitor.visit_trait_item(item);
1166 visitor.format_missing(item.span.hi() - BytePos(1));
1168 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1170 result.push_str(&inner_indent_str);
1171 result.push_str(visitor.buffer.trim());
1172 result.push_str(&outer_indent_str);
1173 } else if result.contains('\n') {
1174 result.push_str(&outer_indent_str);
1184 struct OpaqueTypeBounds<'a> {
1185 generic_bounds: &'a ast::GenericBounds,
1188 impl<'a> Rewrite for OpaqueTypeBounds<'a> {
1189 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1191 .rewrite(context, shape)
1192 .map(|s| format!("impl {}", s))
1196 pub(crate) struct TraitAliasBounds<'a> {
1197 generic_bounds: &'a ast::GenericBounds,
1198 generics: &'a ast::Generics,
1201 impl<'a> Rewrite for TraitAliasBounds<'a> {
1202 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1203 let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
1205 let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1206 option.allow_single_line();
1208 let where_str = rewrite_where_clause(
1210 &self.generics.where_clause,
1211 context.config.brace_style(),
1216 self.generics.where_clause.span.lo(),
1220 let fits_single_line = !generic_bounds_str.contains('\n')
1221 && !where_str.contains('\n')
1222 && generic_bounds_str.len() + where_str.len() < shape.width;
1223 let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1225 } else if fits_single_line {
1228 shape.indent.to_string_with_newline(&context.config)
1231 Some(format!("{}{}{}", generic_bounds_str, space, where_str))
1235 pub(crate) fn format_trait_alias(
1236 context: &RewriteContext<'_>,
1237 ident: symbol::Ident,
1238 vis: &ast::Visibility,
1239 generics: &ast::Generics,
1240 generic_bounds: &ast::GenericBounds,
1242 ) -> Option<String> {
1243 let alias = rewrite_ident(context, ident);
1244 // 6 = "trait ", 2 = " ="
1245 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1246 let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
1247 let vis_str = format_visibility(context, vis);
1248 let lhs = format!("{}trait {} =", vis_str, generics_str);
1250 let trait_alias_bounds = TraitAliasBounds {
1254 rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";")
1257 fn format_unit_struct(
1258 context: &RewriteContext<'_>,
1259 p: &StructParts<'_>,
1261 ) -> Option<String> {
1262 let header_str = format_header(context, p.prefix, p.ident, p.vis, offset);
1263 let generics_str = if let Some(generics) = p.generics {
1264 let hi = context.snippet_provider.span_before(p.span, ";");
1268 context.config.brace_style(),
1271 // make a span that starts right after `struct Foo`
1272 mk_sp(p.ident.span.hi(), hi),
1273 last_line_width(&header_str),
1278 Some(format!("{}{};", header_str, generics_str))
1281 pub(crate) fn format_struct_struct(
1282 context: &RewriteContext<'_>,
1283 struct_parts: &StructParts<'_>,
1284 fields: &[ast::FieldDef],
1286 one_line_width: Option<usize>,
1287 ) -> Option<String> {
1288 let mut result = String::with_capacity(1024);
1289 let span = struct_parts.span;
1291 let header_str = struct_parts.format_header(context, offset);
1292 result.push_str(&header_str);
1294 let header_hi = struct_parts.ident.span.hi();
1295 let body_lo = context.snippet_provider.span_after(span, "{");
1297 let generics_str = match struct_parts.generics {
1298 Some(g) => format_generics(
1301 context.config.brace_style(),
1302 if fields.is_empty() {
1303 BracePos::ForceSameLine
1308 // make a span that starts right after `struct Foo`
1309 mk_sp(header_hi, body_lo),
1310 last_line_width(&result),
1313 // 3 = ` {}`, 2 = ` {`.
1314 let overhead = if fields.is_empty() { 3 } else { 2 };
1315 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1316 || context.config.max_width() < overhead + result.len()
1318 format!("\n{}{{", offset.block_only().to_string(context.config))
1325 let overhead = if fields.is_empty() { 1 } else { 0 };
1326 let total_width = result.len() + generics_str.len() + overhead;
1327 if !generics_str.is_empty()
1328 && !generics_str.contains('\n')
1329 && total_width > context.config.max_width()
1332 result.push_str(&offset.to_string(context.config));
1333 result.push_str(generics_str.trim_start());
1335 result.push_str(&generics_str);
1338 if fields.is_empty() {
1339 let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1340 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1341 return Some(result);
1345 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1346 let one_line_budget =
1347 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1349 let items_str = rewrite_with_alignment(
1352 Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
1353 mk_sp(body_lo, span.hi()),
1357 if !items_str.contains('\n')
1358 && !result.contains('\n')
1359 && items_str.len() <= one_line_budget
1360 && !last_line_contains_single_line_comment(&items_str)
1362 Some(format!("{} {} }}", result, items_str))
1368 .block_indent(context.config)
1369 .to_string(context.config),
1371 offset.to_string(context.config)
1376 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1378 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1379 _ => default_span.lo(),
1383 // Format tuple or struct without any fields. We need to make sure that the comments
1384 // inside the delimiters are preserved.
1385 fn format_empty_struct_or_tuple(
1386 context: &RewriteContext<'_>,
1389 result: &mut String,
1393 // 3 = " {}" or "();"
1394 let used_width = last_line_used_width(&result, offset.width()) + 3;
1395 if used_width > context.config.max_width() {
1396 result.push_str(&offset.to_string_with_newline(context.config))
1398 result.push_str(opener);
1399 match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1400 Some(ref s) if s.is_empty() => (),
1402 if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1403 let nested_indent_str = offset
1404 .block_indent(context.config)
1405 .to_string_with_newline(context.config);
1406 result.push_str(&nested_indent_str);
1409 if last_line_contains_single_line_comment(s) {
1410 result.push_str(&offset.to_string_with_newline(context.config));
1413 None => result.push_str(context.snippet(span)),
1415 result.push_str(closer);
1418 fn format_tuple_struct(
1419 context: &RewriteContext<'_>,
1420 struct_parts: &StructParts<'_>,
1421 fields: &[ast::FieldDef],
1423 ) -> Option<String> {
1424 let mut result = String::with_capacity(1024);
1425 let span = struct_parts.span;
1427 let header_str = struct_parts.format_header(context, offset);
1428 result.push_str(&header_str);
1430 let body_lo = if fields.is_empty() {
1431 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1434 .span_after(mk_sp(lo, span.hi()), "(")
1438 let body_hi = if fields.is_empty() {
1441 .span_after(mk_sp(body_lo, span.hi()), ")")
1443 // This is a dirty hack to work around a missing `)` from the span of the last field.
1444 let last_arg_span = fields[fields.len() - 1].span;
1447 .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1448 .unwrap_or_else(|| last_arg_span.hi())
1451 let where_clause_str = match struct_parts.generics {
1453 let budget = context.budget(last_line_width(&header_str));
1454 let shape = Shape::legacy(budget, offset);
1455 let generics_str = rewrite_generics(context, "", generics, shape)?;
1456 result.push_str(&generics_str);
1458 let where_budget = context.budget(last_line_width(&result));
1459 let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1460 rewrite_where_clause(
1462 &generics.where_clause,
1463 context.config.brace_style(),
1464 Shape::legacy(where_budget, offset.block_only()),
1472 None => "".to_owned(),
1475 if fields.is_empty() {
1476 let body_hi = context
1478 .span_before(mk_sp(body_lo, span.hi()), ")");
1479 let inner_span = mk_sp(body_lo, body_hi);
1480 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1482 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1483 let lo = if let Some(generics) = struct_parts.generics {
1486 struct_parts.ident.span.hi()
1488 result = overflow::rewrite_with_parens(
1493 mk_sp(lo, span.hi()),
1494 context.config.fn_call_width(),
1499 if !where_clause_str.is_empty()
1500 && !where_clause_str.contains('\n')
1501 && (result.contains('\n')
1502 || offset.block_indent + result.len() + where_clause_str.len() + 1
1503 > context.config.max_width())
1505 // We need to put the where-clause on a new line, but we didn't
1506 // know that earlier, so the where-clause will not be indented properly.
1509 &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1512 result.push_str(&where_clause_str);
1517 pub(crate) fn rewrite_type<R: Rewrite>(
1518 context: &RewriteContext<'_>,
1520 ident: symbol::Ident,
1521 vis: &ast::Visibility,
1522 generics: &ast::Generics,
1523 generic_bounds_opt: Option<&ast::GenericBounds>,
1526 ) -> Option<String> {
1527 let mut result = String::with_capacity(128);
1528 result.push_str(&format!("{}type ", format_visibility(context, vis)));
1529 let ident_str = rewrite_ident(context, ident);
1531 if generics.params.is_empty() {
1532 result.push_str(ident_str)
1535 let g_shape = Shape::indented(indent, context.config)
1536 .offset_left(result.len())?
1538 let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1539 result.push_str(&generics_str);
1542 if let Some(bounds) = generic_bounds_opt {
1543 if !bounds.is_empty() {
1545 let shape = Shape::indented(indent, context.config).offset_left(result.len() + 2)?;
1546 let type_bounds = bounds.rewrite(context, shape).map(|s| format!(": {}", s))?;
1547 result.push_str(&type_bounds);
1551 let where_budget = context.budget(last_line_width(&result));
1552 let mut option = WhereClauseOption::snuggled(&result);
1554 option.suppress_comma();
1556 let where_clause_str = rewrite_where_clause(
1558 &generics.where_clause,
1559 context.config.brace_style(),
1560 Shape::legacy(where_budget, indent),
1567 result.push_str(&where_clause_str);
1569 if let Some(ty) = rhs {
1570 // If there's a where clause, add a newline before the assignment. Otherwise just add a
1572 let has_where = !generics.where_clause.predicates.is_empty();
1574 result.push_str(&indent.to_string_with_newline(context.config));
1579 let comment_span = context
1581 .opt_span_before(span, "=")
1582 .map(|op_lo| mk_sp(generics.where_clause.span.hi(), op_lo));
1584 let lhs = match comment_span {
1586 if contains_comment(context.snippet_provider.span_to_snippet(comment_span)?) =>
1588 let comment_shape = if has_where {
1589 Shape::indented(indent, context.config)
1591 Shape::indented(indent, context.config)
1592 .block_left(context.config.tab_spaces())?
1595 combine_strs_with_missing_comments(
1604 _ => format!("{}=", result),
1608 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1609 rewrite_assign_rhs(context, lhs, &*ty, shape).map(|s| s + ";")
1611 Some(format!("{};", result))
1615 pub(crate) fn rewrite_opaque_type(
1616 context: &RewriteContext<'_>,
1618 ident: symbol::Ident,
1619 generic_bounds: &ast::GenericBounds,
1620 generics: &ast::Generics,
1621 vis: &ast::Visibility,
1623 ) -> Option<String> {
1624 let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
1631 Some(generic_bounds),
1632 Some(&opaque_type_bounds),
1637 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1639 if config.space_before_colon() { " " } else { "" },
1640 if config.space_after_colon() { " " } else { "" },
1644 pub(crate) fn rewrite_struct_field_prefix(
1645 context: &RewriteContext<'_>,
1646 field: &ast::FieldDef,
1647 ) -> Option<String> {
1648 let vis = format_visibility(context, &field.vis);
1649 let type_annotation_spacing = type_annotation_spacing(context.config);
1650 Some(match field.ident {
1651 Some(name) => format!(
1654 rewrite_ident(context, name),
1655 type_annotation_spacing.0
1657 None => vis.to_string(),
1661 impl Rewrite for ast::FieldDef {
1662 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1663 rewrite_struct_field(context, self, shape, 0)
1667 pub(crate) fn rewrite_struct_field(
1668 context: &RewriteContext<'_>,
1669 field: &ast::FieldDef,
1671 lhs_max_width: usize,
1672 ) -> Option<String> {
1673 if contains_skip(&field.attrs) {
1674 return Some(context.snippet(field.span()).to_owned());
1677 let type_annotation_spacing = type_annotation_spacing(context.config);
1678 let prefix = rewrite_struct_field_prefix(context, field)?;
1680 let attrs_str = field.attrs.rewrite(context, shape)?;
1681 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1682 let missing_span = if field.attrs.is_empty() {
1683 mk_sp(field.span.lo(), field.span.lo())
1685 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1687 let mut spacing = String::from(if field.ident.is_some() {
1688 type_annotation_spacing.1
1692 // Try to put everything on a single line.
1693 let attr_prefix = combine_strs_with_missing_comments(
1701 let overhead = trimmed_last_line_width(&attr_prefix);
1702 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1703 for _ in 0..lhs_offset {
1706 // In this extreme case we will be missing a space between an attribute and a field.
1707 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1711 .offset_left(overhead + spacing.len())
1712 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1713 if let Some(ref ty) = orig_ty {
1714 if !ty.contains('\n') {
1715 return Some(attr_prefix + &spacing + ty);
1719 let is_prefix_empty = prefix.is_empty();
1720 // We must use multiline. We are going to put attributes and a field on different lines.
1721 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1722 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1723 let field_str = if is_prefix_empty {
1724 field_str.trim_start()
1728 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1731 pub(crate) struct StaticParts<'a> {
1733 vis: &'a ast::Visibility,
1734 ident: symbol::Ident,
1736 mutability: ast::Mutability,
1737 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1738 defaultness: Option<ast::Defaultness>,
1742 impl<'a> StaticParts<'a> {
1743 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1744 let (defaultness, prefix, ty, mutability, expr) = match item.kind {
1745 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
1746 (None, "static", ty, mutability, expr)
1748 ast::ItemKind::Const(defaultness, ref ty, ref expr) => {
1749 (Some(defaultness), "const", ty, ast::Mutability::Not, expr)
1751 _ => unreachable!(),
1759 expr_opt: expr.as_ref(),
1765 pub(crate) fn from_trait_item(ti: &'a ast::AssocItem) -> Self {
1766 let (defaultness, ty, expr_opt) = match ti.kind {
1767 ast::AssocItemKind::Const(defaultness, ref ty, ref expr_opt) => {
1768 (defaultness, ty, expr_opt)
1770 _ => unreachable!(),
1777 mutability: ast::Mutability::Not,
1778 expr_opt: expr_opt.as_ref(),
1779 defaultness: Some(defaultness),
1784 pub(crate) fn from_impl_item(ii: &'a ast::AssocItem) -> Self {
1785 let (defaultness, ty, expr) = match ii.kind {
1786 ast::AssocItemKind::Const(defaultness, ref ty, ref expr) => (defaultness, ty, expr),
1787 _ => unreachable!(),
1794 mutability: ast::Mutability::Not,
1795 expr_opt: expr.as_ref(),
1796 defaultness: Some(defaultness),
1803 context: &RewriteContext<'_>,
1804 static_parts: &StaticParts<'_>,
1806 ) -> Option<String> {
1807 let colon = colon_spaces(context.config);
1808 let mut prefix = format!(
1810 format_visibility(context, static_parts.vis),
1811 static_parts.defaultness.map_or("", format_defaultness),
1812 static_parts.prefix,
1813 format_mutability(static_parts.mutability),
1814 rewrite_ident(context, static_parts.ident),
1819 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1820 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1821 Some(ty_str) => ty_str,
1823 if prefix.ends_with(' ') {
1826 let nested_indent = offset.block_indent(context.config);
1827 let nested_shape = Shape::indented(nested_indent, context.config);
1828 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1831 nested_indent.to_string_with_newline(context.config),
1837 if let Some(expr) = static_parts.expr_opt {
1838 let comments_lo = context.snippet_provider.span_after(static_parts.span, "=");
1839 let expr_lo = expr.span.lo();
1840 let comments_span = mk_sp(comments_lo, expr_lo);
1842 let lhs = format!("{}{} =", prefix, ty_str);
1845 let remaining_width = context.budget(offset.block_indent + 1);
1846 rewrite_assign_rhs_with_comments(
1850 Shape::legacy(remaining_width, offset.block_only()),
1851 RhsTactics::Default,
1855 .and_then(|res| recover_comment_removed(res, static_parts.span, context))
1856 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1858 Some(format!("{}{};", prefix, ty_str))
1861 struct OpaqueType<'a> {
1862 bounds: &'a ast::GenericBounds,
1865 impl<'a> Rewrite for OpaqueType<'a> {
1866 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1867 let shape = shape.offset_left(5)?; // `impl `
1869 .rewrite(context, shape)
1870 .map(|s| format!("impl {}", s))
1874 pub(crate) fn rewrite_impl_type(
1875 ident: symbol::Ident,
1876 vis: &ast::Visibility,
1877 defaultness: ast::Defaultness,
1878 ty_opt: Option<&ptr::P<ast::Ty>>,
1879 generics: &ast::Generics,
1880 context: &RewriteContext<'_>,
1883 ) -> Option<String> {
1885 let result = if let Some(rustc_ast::ast::Ty {
1886 kind: ast::TyKind::ImplTrait(_, ref bounds),
1888 }) = ty_opt.map(|t| &**t)
1894 &DEFAULT_VISIBILITY,
1897 Some(&OpaqueType { bounds }),
1901 rewrite_type(context, indent, ident, vis, generics, None, ty_opt, span)
1905 ast::Defaultness::Default(..) => Some(format!("default {}", result)),
1910 impl Rewrite for ast::FnRetTy {
1911 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1913 ast::FnRetTy::Default(_) => Some(String::new()),
1914 ast::FnRetTy::Ty(ref ty) => {
1915 if context.config.version() == Version::One
1916 || context.config.indent_style() == IndentStyle::Visual
1918 let inner_width = shape.width.checked_sub(3)?;
1920 .rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1921 .map(|r| format!("-> {}", r));
1924 ty.rewrite(context, shape.offset_left(3)?)
1925 .map(|s| format!("-> {}", s))
1931 fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
1933 ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
1938 /// Recover any missing comments between the param and the type.
1942 /// A 2-len tuple with the comment before the colon in first position, and the comment after the
1943 /// colon in second position.
1944 fn get_missing_param_comments(
1945 context: &RewriteContext<'_>,
1949 ) -> (String, String) {
1950 let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
1952 let span_before_colon = {
1953 let missing_comment_span_hi = context
1955 .span_before(missing_comment_span, ":");
1956 mk_sp(pat_span.hi(), missing_comment_span_hi)
1958 let span_after_colon = {
1959 let missing_comment_span_lo = context
1961 .span_after(missing_comment_span, ":");
1962 mk_sp(missing_comment_span_lo, ty_span.lo())
1965 let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
1966 .filter(|comment| !comment.is_empty())
1967 .map_or(String::new(), |comment| format!(" {}", comment));
1968 let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
1969 .filter(|comment| !comment.is_empty())
1970 .map_or(String::new(), |comment| format!("{} ", comment));
1971 (comment_before_colon, comment_after_colon)
1974 impl Rewrite for ast::Param {
1975 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1976 let param_attrs_result = self
1978 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1979 // N.B. Doc comments aren't typically valid syntax, but could appear
1980 // in the presence of certain macros - https://github.com/rust-lang/rustfmt/issues/4936
1981 let (span, has_multiple_attr_lines, has_doc_comments) = if !self.attrs.is_empty() {
1982 let num_attrs = self.attrs.len();
1984 mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
1985 param_attrs_result.contains('\n'),
1986 self.attrs.iter().any(|a| a.is_doc_comment()),
1989 (mk_sp(self.span.lo(), self.span.lo()), false, false)
1992 if let Some(ref explicit_self) = self.to_self() {
1993 rewrite_explicit_self(
1996 ¶m_attrs_result,
1999 has_multiple_attr_lines,
2001 } else if is_named_param(self) {
2002 let param_name = &self
2004 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
2005 let mut result = combine_strs_with_missing_comments(
2007 ¶m_attrs_result,
2011 !has_multiple_attr_lines && !has_doc_comments,
2014 if !is_empty_infer(&*self.ty, self.pat.span) {
2015 let (before_comment, after_comment) =
2016 get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
2017 result.push_str(&before_comment);
2018 result.push_str(colon_spaces(context.config));
2019 result.push_str(&after_comment);
2020 let overhead = last_line_width(&result);
2021 let max_width = shape.width.checked_sub(overhead)?;
2022 if let Some(ty_str) = self
2024 .rewrite(context, Shape::legacy(max_width, shape.indent))
2026 result.push_str(&ty_str);
2028 result = combine_strs_with_missing_comments(
2030 &(param_attrs_result + &shape.to_string_with_newline(context.config)),
2034 !has_multiple_attr_lines,
2036 result.push_str(&before_comment);
2037 result.push_str(colon_spaces(context.config));
2038 result.push_str(&after_comment);
2039 let overhead = last_line_width(&result);
2040 let max_width = shape.width.checked_sub(overhead)?;
2043 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
2044 result.push_str(&ty_str);
2050 self.ty.rewrite(context, shape)
2055 fn rewrite_explicit_self(
2056 context: &RewriteContext<'_>,
2057 explicit_self: &ast::ExplicitSelf,
2061 has_multiple_attr_lines: bool,
2062 ) -> Option<String> {
2063 match explicit_self.node {
2064 ast::SelfKind::Region(lt, m) => {
2065 let mut_str = format_mutability(m);
2068 let lifetime_str = l.rewrite(
2070 Shape::legacy(context.config.max_width(), Indent::empty()),
2072 Some(combine_strs_with_missing_comments(
2075 &format!("&{} {}self", lifetime_str, mut_str),
2078 !has_multiple_attr_lines,
2081 None => Some(combine_strs_with_missing_comments(
2084 &format!("&{}self", mut_str),
2087 !has_multiple_attr_lines,
2091 ast::SelfKind::Explicit(ref ty, mutability) => {
2092 let type_str = ty.rewrite(
2094 Shape::legacy(context.config.max_width(), Indent::empty()),
2097 Some(combine_strs_with_missing_comments(
2100 &format!("{}self: {}", format_mutability(mutability), type_str),
2103 !has_multiple_attr_lines,
2106 ast::SelfKind::Value(mutability) => Some(combine_strs_with_missing_comments(
2109 &format!("{}self", format_mutability(mutability)),
2112 !has_multiple_attr_lines,
2117 pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2118 if param.attrs.is_empty() {
2119 if is_named_param(param) {
2125 param.attrs[0].span.lo()
2129 pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2130 match param.ty.kind {
2131 ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2132 ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2133 _ => param.ty.span.hi(),
2137 pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2138 if let ast::PatKind::Ident(_, ident, _) = param.pat.kind {
2139 ident.name != symbol::kw::Empty
2145 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2146 pub(crate) enum FnBraceStyle {
2152 // Return type is (result, force_new_line_for_brace)
2154 context: &RewriteContext<'_>,
2156 ident: symbol::Ident,
2159 fn_brace_style: FnBraceStyle,
2160 ) -> Option<(String, bool, bool)> {
2161 let mut force_new_line_for_brace = false;
2163 let where_clause = &fn_sig.generics.where_clause;
2165 let mut result = String::with_capacity(1024);
2166 result.push_str(&fn_sig.to_str(context));
2169 result.push_str("fn ");
2172 let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2179 let used_width = last_line_used_width(&result, indent.width());
2180 let one_line_budget = context.budget(used_width + overhead);
2182 width: one_line_budget,
2186 let fd = fn_sig.decl;
2187 let generics_str = rewrite_generics(
2189 rewrite_ident(context, ident),
2193 result.push_str(&generics_str);
2195 let snuggle_angle_bracket = generics_str
2198 .map_or(false, |l| l.trim_start().len() == 1);
2200 // Note that the width and indent don't really matter, we'll re-layout the
2201 // return type later anyway.
2204 .rewrite(context, Shape::indented(indent, context.config))?;
2206 let multi_line_ret_str = ret_str.contains('\n');
2207 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2210 let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2220 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2221 one_line_budget, multi_line_budget, param_indent
2225 // Check if vertical layout was forced.
2226 if one_line_budget == 0
2227 && !snuggle_angle_bracket
2228 && context.config.indent_style() == IndentStyle::Visual
2230 result.push_str(¶m_indent.to_string_with_newline(context.config));
2233 // Skip `pub(crate)`.
2234 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
2235 // A conservative estimation, the goal is to be over all parens in generics
2236 let params_start = fn_sig
2240 .map_or(lo_after_visibility, |param| param.span().hi());
2241 let params_end = if fd.inputs.is_empty() {
2244 .span_after(mk_sp(params_start, span.hi()), ")")
2246 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2247 context.snippet_provider.span_after(last_span, ")")
2249 let params_span = mk_sp(
2252 .span_after(mk_sp(params_start, span.hi()), "("),
2255 let param_str = rewrite_params(
2266 let put_params_in_block = match context.config.indent_style() {
2267 IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2269 } && !fd.inputs.is_empty();
2271 let mut params_last_line_contains_comment = false;
2272 let mut no_params_and_over_max_width = false;
2274 if put_params_in_block {
2275 param_indent = indent.block_indent(context.config);
2276 result.push_str(¶m_indent.to_string_with_newline(context.config));
2277 result.push_str(¶m_str);
2278 result.push_str(&indent.to_string_with_newline(context.config));
2281 result.push_str(¶m_str);
2282 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2283 // Put the closing brace on the next line if it overflows the max width.
2285 let closing_paren_overflow_max_width =
2286 fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2287 // If the last line of params contains comment, we cannot put the closing paren
2288 // on the same line.
2289 params_last_line_contains_comment = param_str
2292 .map_or(false, |last_line| last_line.contains("//"));
2294 if context.config.version() == Version::Two {
2295 if closing_paren_overflow_max_width {
2297 result.push_str(&indent.to_string_with_newline(context.config));
2298 no_params_and_over_max_width = true;
2299 } else if params_last_line_contains_comment {
2300 result.push_str(&indent.to_string_with_newline(context.config));
2302 no_params_and_over_max_width = true;
2307 if closing_paren_overflow_max_width || params_last_line_contains_comment {
2308 result.push_str(&indent.to_string_with_newline(context.config));
2315 if let ast::FnRetTy::Ty(..) = fd.output {
2316 let ret_should_indent = match context.config.indent_style() {
2317 // If our params are block layout then we surely must have space.
2318 IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2319 _ if params_last_line_contains_comment => false,
2320 _ if result.contains('\n') || multi_line_ret_str => true,
2322 // If the return type would push over the max width, then put the return type on
2323 // a new line. With the +1 for the signature length an additional space between
2324 // the closing parenthesis of the param and the arrow '->' is considered.
2325 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2327 // If there is no where-clause, take into account the space after the return type
2329 if where_clause.predicates.is_empty() {
2333 sig_length > context.config.max_width()
2336 let ret_shape = if ret_should_indent {
2337 if context.config.version() == Version::One
2338 || context.config.indent_style() == IndentStyle::Visual
2340 let indent = if param_str.is_empty() {
2341 // Aligning with non-existent params looks silly.
2342 force_new_line_for_brace = true;
2345 // FIXME: we might want to check that using the param indent
2346 // doesn't blow our budget, and if it does, then fallback to
2347 // the where-clause indent.
2351 result.push_str(&indent.to_string_with_newline(context.config));
2352 Shape::indented(indent, context.config)
2354 let mut ret_shape = Shape::indented(indent, context.config);
2355 if param_str.is_empty() {
2356 // Aligning with non-existent params looks silly.
2357 force_new_line_for_brace = true;
2358 ret_shape = if context.use_block_indent() {
2359 ret_shape.offset_left(4).unwrap_or(ret_shape)
2361 ret_shape.indent = ret_shape.indent + 4;
2366 result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2370 if context.config.version() == Version::Two {
2371 if !param_str.is_empty() || !no_params_and_over_max_width {
2378 let ret_shape = Shape::indented(indent, context.config);
2380 .offset_left(last_line_width(&result))
2381 .unwrap_or(ret_shape)
2384 if multi_line_ret_str || ret_should_indent {
2385 // Now that we know the proper indent and width, we need to
2386 // re-layout the return type.
2387 let ret_str = fd.output.rewrite(context, ret_shape)?;
2388 result.push_str(&ret_str);
2390 result.push_str(&ret_str);
2393 // Comment between return type and the end of the decl.
2394 let snippet_lo = fd.output.span().hi();
2395 if where_clause.predicates.is_empty() {
2396 let snippet_hi = span.hi();
2397 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2398 // Try to preserve the layout of the original snippet.
2399 let original_starts_with_newline = snippet
2401 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2402 let original_ends_with_newline = snippet
2403 .rfind(|c| c != ' ')
2404 .map_or(false, |i| snippet[i..].ends_with('\n'));
2405 let snippet = snippet.trim();
2406 if !snippet.is_empty() {
2407 result.push(if original_starts_with_newline {
2412 result.push_str(snippet);
2413 if original_ends_with_newline {
2414 force_new_line_for_brace = true;
2420 let pos_before_where = match fd.output {
2421 ast::FnRetTy::Default(..) => params_span.hi(),
2422 ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
2425 let is_params_multi_lined = param_str.contains('\n');
2427 let space = if put_params_in_block && ret_str.is_empty() {
2428 WhereClauseSpace::Space
2430 WhereClauseSpace::Newline
2432 let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2433 if is_params_multi_lined {
2434 option.veto_single_line();
2436 let where_clause_str = rewrite_where_clause(
2439 context.config.brace_style(),
2440 Shape::indented(indent, context.config),
2447 // If there are neither where-clause nor return type, we may be missing comments between
2449 if where_clause_str.is_empty() {
2450 if let ast::FnRetTy::Default(ret_span) = fd.output {
2451 match recover_missing_comment_in_span(
2452 mk_sp(params_span.hi(), ret_span.hi()),
2455 last_line_width(&result),
2457 Some(ref missing_comment) if !missing_comment.is_empty() => {
2458 result.push_str(missing_comment);
2459 force_new_line_for_brace = true;
2466 result.push_str(&where_clause_str);
2468 let ends_with_comment = last_line_contains_single_line_comment(&result);
2469 force_new_line_for_brace |= ends_with_comment;
2470 force_new_line_for_brace |=
2471 is_params_multi_lined && context.config.where_single_line() && !where_clause_str.is_empty();
2472 Some((result, ends_with_comment, force_new_line_for_brace))
2475 /// Kind of spaces to put before `where`.
2476 #[derive(Copy, Clone)]
2477 enum WhereClauseSpace {
2486 #[derive(Copy, Clone)]
2487 struct WhereClauseOption {
2488 suppress_comma: bool, // Force no trailing comma
2489 snuggle: WhereClauseSpace,
2490 allow_single_line: bool, // Try single line where-clause instead of vertical layout
2491 veto_single_line: bool, // Disallow a single-line where-clause.
2494 impl WhereClauseOption {
2495 fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2499 allow_single_line: false,
2500 veto_single_line: false,
2504 fn snuggled(current: &str) -> WhereClauseOption {
2506 suppress_comma: false,
2507 snuggle: if last_line_width(current) == 1 {
2508 WhereClauseSpace::Space
2510 WhereClauseSpace::Newline
2512 allow_single_line: false,
2513 veto_single_line: false,
2517 fn suppress_comma(&mut self) {
2518 self.suppress_comma = true
2521 fn allow_single_line(&mut self) {
2522 self.allow_single_line = true
2525 fn snuggle(&mut self) {
2526 self.snuggle = WhereClauseSpace::Space
2529 fn veto_single_line(&mut self) {
2530 self.veto_single_line = true;
2535 context: &RewriteContext<'_>,
2536 params: &[ast::Param],
2537 one_line_budget: usize,
2538 multi_line_budget: usize,
2540 param_indent: Indent,
2543 ) -> Option<String> {
2544 if params.is_empty() {
2545 let comment = context
2549 span.hi() - BytePos(1),
2552 return Some(comment.to_owned());
2554 let param_items: Vec<_> = itemize_list(
2555 context.snippet_provider,
2559 |param| span_lo_for_param(param),
2560 |param| param.ty.span.hi(),
2563 .rewrite(context, Shape::legacy(multi_line_budget, param_indent))
2564 .or_else(|| Some(context.snippet(param.span()).to_owned()))
2572 let tactic = definitive_tactic(
2577 .to_list_tactic(param_items.len()),
2581 let budget = match tactic {
2582 DefinitiveListTactic::Horizontal => one_line_budget,
2583 _ => multi_line_budget,
2585 let indent = match context.config.indent_style() {
2586 IndentStyle::Block => indent.block_indent(context.config),
2587 IndentStyle::Visual => param_indent,
2589 let trailing_separator = if variadic {
2590 SeparatorTactic::Never
2592 match context.config.indent_style() {
2593 IndentStyle::Block => context.config.trailing_comma(),
2594 IndentStyle::Visual => SeparatorTactic::Never,
2597 let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2599 .trailing_separator(trailing_separator)
2600 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2601 .preserve_newline(true);
2602 write_list(¶m_items, &fmt)
2605 fn compute_budgets_for_params(
2606 context: &RewriteContext<'_>,
2610 fn_brace_style: FnBraceStyle,
2611 force_vertical_layout: bool,
2612 ) -> Option<(usize, usize, Indent)> {
2614 "compute_budgets_for_params {} {:?}, {}, {:?}",
2620 // Try keeping everything on the same line.
2621 if !result.contains('\n') && !force_vertical_layout {
2622 // 2 = `()`, 3 = `() `, space is before ret_string.
2623 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2624 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2625 match fn_brace_style {
2626 FnBraceStyle::None => used_space += 1, // 1 = `;`
2627 FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2628 FnBraceStyle::NextLine => (),
2630 let one_line_budget = context.budget(used_space);
2632 if one_line_budget > 0 {
2634 let (indent, multi_line_budget) = match context.config.indent_style() {
2635 IndentStyle::Block => {
2636 let indent = indent.block_indent(context.config);
2637 (indent, context.budget(indent.width() + 1))
2639 IndentStyle::Visual => {
2640 let indent = indent + result.len() + 1;
2641 let multi_line_overhead = match fn_brace_style {
2642 FnBraceStyle::SameLine => 4,
2645 (indent, context.budget(multi_line_overhead))
2649 return Some((one_line_budget, multi_line_budget, indent));
2653 // Didn't work. we must force vertical layout and put params on a newline.
2654 let new_indent = indent.block_indent(context.config);
2655 let used_space = match context.config.indent_style() {
2657 IndentStyle::Block => new_indent.width() + 1,
2658 // Account for `)` and possibly ` {`.
2659 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2661 Some((0, context.budget(used_space), new_indent))
2664 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2665 let predicate_count = where_clause.predicates.len();
2667 if config.where_single_line() && predicate_count == 1 {
2668 return FnBraceStyle::SameLine;
2670 let brace_style = config.brace_style();
2672 let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2673 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2675 FnBraceStyle::NextLine
2677 FnBraceStyle::SameLine
2681 fn rewrite_generics(
2682 context: &RewriteContext<'_>,
2684 generics: &ast::Generics,
2686 ) -> Option<String> {
2687 // FIXME: convert bounds to where-clauses where they get too big or if
2688 // there is a where-clause at all.
2690 if generics.params.is_empty() {
2691 return Some(ident.to_owned());
2694 let params = generics.params.iter();
2695 overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2698 fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2699 match config.indent_style() {
2700 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2701 IndentStyle::Block => {
2705 .block_indent(config.tab_spaces())
2706 .with_max_width(config)
2712 fn rewrite_where_clause_rfc_style(
2713 context: &RewriteContext<'_>,
2714 where_clause: &ast::WhereClause,
2717 span_end: Option<BytePos>,
2718 span_end_before_where: BytePos,
2719 where_clause_option: WhereClauseOption,
2720 ) -> Option<String> {
2721 let (where_keyword, allow_single_line) = rewrite_where_keyword(
2725 span_end_before_where,
2726 where_clause_option,
2730 let clause_shape = shape
2732 .with_max_width(context.config)
2733 .block_left(context.config.tab_spaces())?
2735 let force_single_line = context.config.where_single_line()
2736 && where_clause.predicates.len() == 1
2737 && !where_clause_option.veto_single_line;
2739 let preds_str = rewrite_bounds_on_where_clause(
2745 where_clause_option,
2751 if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
2752 || force_single_line
2756 clause_shape.indent.to_string_with_newline(context.config)
2759 Some(format!("{}{}{}", where_keyword, clause_sep, preds_str))
2762 /// Rewrite `where` and comment around it.
2763 fn rewrite_where_keyword(
2764 context: &RewriteContext<'_>,
2765 where_clause: &ast::WhereClause,
2767 span_end_before_where: BytePos,
2768 where_clause_option: WhereClauseOption,
2769 ) -> Option<(String, bool)> {
2770 let block_shape = shape.block().with_max_width(context.config);
2772 let clause_shape = block_shape
2773 .block_left(context.config.tab_spaces())?
2776 let comment_separator = |comment: &str, shape: Shape| {
2777 if comment.is_empty() {
2780 shape.indent.to_string_with_newline(context.config)
2784 let (span_before, span_after) =
2785 missing_span_before_after_where(span_end_before_where, where_clause);
2786 let (comment_before, comment_after) =
2787 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2789 let starting_newline = match where_clause_option.snuggle {
2790 WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
2791 WhereClauseSpace::None => Cow::from(""),
2792 _ => block_shape.indent.to_string_with_newline(context.config),
2795 let newline_before_where = comment_separator(&comment_before, shape);
2796 let newline_after_where = comment_separator(&comment_after, clause_shape);
2797 let result = format!(
2799 starting_newline, comment_before, newline_before_where, newline_after_where, comment_after
2801 let allow_single_line = where_clause_option.allow_single_line
2802 && comment_before.is_empty()
2803 && comment_after.is_empty();
2805 Some((result, allow_single_line))
2808 /// Rewrite bounds on a where clause.
2809 fn rewrite_bounds_on_where_clause(
2810 context: &RewriteContext<'_>,
2811 where_clause: &ast::WhereClause,
2814 span_end: Option<BytePos>,
2815 where_clause_option: WhereClauseOption,
2816 force_single_line: bool,
2817 ) -> Option<String> {
2818 let span_start = where_clause.predicates[0].span().lo();
2819 // If we don't have the start of the next span, then use the end of the
2820 // predicates, but that means we miss comments.
2821 let len = where_clause.predicates.len();
2822 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2823 let span_end = span_end.unwrap_or(end_of_preds);
2824 let items = itemize_list(
2825 context.snippet_provider,
2826 where_clause.predicates.iter(),
2829 |pred| pred.span().lo(),
2830 |pred| pred.span().hi(),
2831 |pred| pred.rewrite(context, shape),
2836 let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
2837 SeparatorTactic::Never
2839 context.config.trailing_comma()
2842 // shape should be vertical only and only if we have `force_single_line` option enabled
2843 // and the number of items of the where-clause is equal to 1
2844 let shape_tactic = if force_single_line {
2845 DefinitiveListTactic::Horizontal
2847 DefinitiveListTactic::Vertical
2850 let fmt = ListFormatting::new(shape, context.config)
2851 .tactic(shape_tactic)
2852 .trailing_separator(comma_tactic)
2853 .preserve_newline(true);
2854 write_list(&items.collect::<Vec<_>>(), &fmt)
2857 fn rewrite_where_clause(
2858 context: &RewriteContext<'_>,
2859 where_clause: &ast::WhereClause,
2860 brace_style: BraceStyle,
2864 span_end: Option<BytePos>,
2865 span_end_before_where: BytePos,
2866 where_clause_option: WhereClauseOption,
2867 ) -> Option<String> {
2868 if where_clause.predicates.is_empty() {
2869 return Some(String::new());
2872 if context.config.indent_style() == IndentStyle::Block {
2873 return rewrite_where_clause_rfc_style(
2879 span_end_before_where,
2880 where_clause_option,
2884 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2886 let offset = match context.config.indent_style() {
2887 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2888 // 6 = "where ".len()
2889 IndentStyle::Visual => shape.indent + extra_indent + 6,
2891 // FIXME: if indent_style != Visual, then the budgets below might
2892 // be out by a char or two.
2894 let budget = context.config.max_width() - offset.width();
2895 let span_start = where_clause.predicates[0].span().lo();
2896 // If we don't have the start of the next span, then use the end of the
2897 // predicates, but that means we miss comments.
2898 let len = where_clause.predicates.len();
2899 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2900 let span_end = span_end.unwrap_or(end_of_preds);
2901 let items = itemize_list(
2902 context.snippet_provider,
2903 where_clause.predicates.iter(),
2906 |pred| pred.span().lo(),
2907 |pred| pred.span().hi(),
2908 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2913 let item_vec = items.collect::<Vec<_>>();
2914 // FIXME: we don't need to collect here
2915 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2917 let mut comma_tactic = context.config.trailing_comma();
2918 // Kind of a hack because we don't usually have trailing commas in where-clauses.
2919 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2920 comma_tactic = SeparatorTactic::Never;
2923 let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
2925 .trailing_separator(comma_tactic)
2926 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2927 .preserve_newline(true);
2928 let preds_str = write_list(&item_vec, &fmt)?;
2930 let end_length = if terminator == "{" {
2931 // If the brace is on the next line we don't need to count it otherwise it needs two
2934 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2935 BraceStyle::PreferSameLine => 2,
2937 } else if terminator == "=" {
2943 || preds_str.contains('\n')
2944 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2948 (shape.indent + extra_indent).to_string(context.config),
2952 Some(format!(" where {}", preds_str))
2956 fn missing_span_before_after_where(
2957 before_item_span_end: BytePos,
2958 where_clause: &ast::WhereClause,
2960 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2962 let pos_after_where = where_clause.span.lo() + BytePos(5);
2963 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2964 (missing_span_before, missing_span_after)
2967 fn rewrite_comments_before_after_where(
2968 context: &RewriteContext<'_>,
2969 span_before_where: Span,
2970 span_after_where: Span,
2972 ) -> Option<(String, String)> {
2973 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2974 let after_comment = rewrite_missing_comment(
2976 shape.block_indent(context.config.tab_spaces()),
2979 Some((before_comment, after_comment))
2983 context: &RewriteContext<'_>,
2985 ident: symbol::Ident,
2986 vis: &ast::Visibility,
2989 let mut result = String::with_capacity(128);
2990 let shape = Shape::indented(offset, context.config);
2992 result.push_str(&format_visibility(context, vis).trim());
2994 // Check for a missing comment between the visibility and the item name.
2995 let after_vis = vis.span.hi();
2996 if let Some(before_item_name) = context
2998 .opt_span_before(mk_sp(vis.span.lo(), ident.span.hi()), item_name.trim())
3000 let missing_span = mk_sp(after_vis, before_item_name);
3001 if let Some(result_with_comment) = combine_strs_with_missing_comments(
3007 /* allow_extend */ true,
3009 result = result_with_comment;
3013 result.push_str(&rewrite_ident(context, ident));
3018 #[derive(PartialEq, Eq, Clone, Copy)]
3026 context: &RewriteContext<'_>,
3027 generics: &ast::Generics,
3028 brace_style: BraceStyle,
3029 brace_pos: BracePos,
3033 ) -> Option<String> {
3034 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
3035 let mut result = rewrite_generics(context, "", generics, shape)?;
3037 // If the generics are not parameterized then generics.span.hi() == 0,
3038 // so we use span.lo(), which is the position after `struct Foo`.
3039 let span_end_before_where = if !generics.params.is_empty() {
3044 let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
3045 let budget = context.budget(last_line_used_width(&result, offset.width()));
3046 let mut option = WhereClauseOption::snuggled(&result);
3047 if brace_pos == BracePos::None {
3048 option.suppress_comma = true;
3050 let where_clause_str = rewrite_where_clause(
3052 &generics.where_clause,
3054 Shape::legacy(budget, offset.block_only()),
3058 span_end_before_where,
3061 result.push_str(&where_clause_str);
3063 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
3064 // missed comments are taken care of in #rewrite_where_clause
3069 brace_pos == BracePos::ForceSameLine
3070 || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
3071 || brace_style != BraceStyle::AlwaysNextLine)
3072 || trimmed_last_line_width(&result) == 1,
3073 rewrite_missing_comment(
3075 span_end_before_where,
3076 if brace_pos == BracePos::None {
3079 context.snippet_provider.span_before(span, "{")
3087 // add missing comments
3088 let missed_line_comments = missed_comments
3089 .filter(|missed_comments| !missed_comments.is_empty())
3090 .map_or(false, |missed_comments| {
3091 let is_block = is_last_comment_block(&missed_comments);
3092 let sep = if is_block { " " } else { "\n" };
3093 result.push_str(sep);
3094 result.push_str(&missed_comments);
3097 if brace_pos == BracePos::None {
3098 return Some(result);
3100 let total_used_width = last_line_used_width(&result, used_width);
3101 let remaining_budget = context.budget(total_used_width);
3102 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
3103 // and hence we take the closer into account as well for one line budget.
3104 // We assume that the closer has the same length as the opener.
3105 let overhead = if brace_pos == BracePos::ForceSameLine {
3112 let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3113 if !forbid_same_line_brace && same_line_brace {
3117 result.push_str(&offset.block_only().to_string(context.config));
3124 impl Rewrite for ast::ForeignItem {
3125 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3126 let attrs_str = self.attrs.rewrite(context, shape)?;
3127 // Drop semicolon or it will be interpreted as comment.
3128 // FIXME: this may be a faulty span from libsyntax.
3129 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3131 let item_str = match self.kind {
3132 ast::ForeignItemKind::Fn(ref fn_kind) => {
3139 if let Some(ref body) = body {
3140 let mut visitor = FmtVisitor::from_context(context);
3141 visitor.block_indent = shape.indent;
3142 visitor.last_pos = self.span.lo();
3143 let inner_attrs = inner_attributes(&self.attrs);
3144 let fn_ctxt = visit::FnCtxt::Foreign;
3146 visit::FnKind::Fn(fn_ctxt, self.ident, &sig, &self.vis, Some(body)),
3153 Some(visitor.buffer.to_owned())
3159 &FnSig::from_method_sig(&sig, generics, &self.vis),
3163 .map(|(s, _, _)| format!("{};", s))
3166 ast::ForeignItemKind::Static(ref ty, mutability, _) => {
3167 // FIXME(#21): we're dropping potential comments in between the
3168 // function kw here.
3169 let vis = format_visibility(context, &self.vis);
3170 let mut_str = format_mutability(mutability);
3171 let prefix = format!(
3175 rewrite_ident(context, self.ident)
3178 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
3180 ast::ForeignItemKind::TyAlias(ref ty_alias_kind) => {
3186 } = **ty_alias_kind;
3198 ast::ForeignItemKind::MacCall(ref mac) => {
3199 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
3203 let missing_span = if self.attrs.is_empty() {
3204 mk_sp(self.span.lo(), self.span.lo())
3206 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3208 combine_strs_with_missing_comments(
3219 /// Rewrite the attributes of an item.
3221 context: &RewriteContext<'_>,
3225 ) -> Option<String> {
3226 let attrs = filter_inline_attrs(&item.attrs, item.span());
3227 let attrs_str = attrs.rewrite(context, shape)?;
3229 let missed_span = if attrs.is_empty() {
3230 mk_sp(item.span.lo(), item.span.lo())
3232 mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3235 let allow_extend = if attrs.len() == 1 {
3236 let line_len = attrs_str.len() + 1 + item_str.len();
3237 !attrs.first().unwrap().is_doc_comment()
3238 && context.config.inline_attribute_width() >= line_len
3243 combine_strs_with_missing_comments(
3253 /// Rewrite an inline mod.
3254 /// The given shape is used to format the mod's attributes.
3255 pub(crate) fn rewrite_mod(
3256 context: &RewriteContext<'_>,
3259 ) -> Option<String> {
3260 let mut result = String::with_capacity(32);
3261 result.push_str(&*format_visibility(context, &item.vis));
3262 result.push_str("mod ");
3263 result.push_str(rewrite_ident(context, item.ident));
3265 rewrite_attrs(context, item, &result, attrs_shape)
3268 /// Rewrite `extern crate foo;`.
3269 /// The given shape is used to format the extern crate's attributes.
3270 pub(crate) fn rewrite_extern_crate(
3271 context: &RewriteContext<'_>,
3274 ) -> Option<String> {
3275 assert!(is_extern_crate(item));
3276 let new_str = context.snippet(item.span);
3277 let item_str = if contains_comment(new_str) {
3280 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3281 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3283 rewrite_attrs(context, item, &item_str, attrs_shape)
3286 /// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3287 pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3290 ast::ItemKind::Mod(_, ast::ModKind::Loaded(_, ast::Inline::Yes, _))
3294 pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3295 matches!(item.kind, ast::ItemKind::Use(_))
3298 pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3299 matches!(item.kind, ast::ItemKind::ExternCrate(..))