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, RhsTactics,
22 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
23 use crate::macros::{rewrite_macro, MacroPosition};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::{Indent, Shape};
27 use crate::source_map::{LineRangeUtils, SpanUtils};
28 use crate::spanned::Spanned;
29 use crate::stmt::Stmt;
31 use crate::vertical::rewrite_with_alignment;
32 use crate::visitor::FmtVisitor;
34 const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
35 kind: ast::VisibilityKind::Inherited,
40 fn type_annotation_separator(config: &Config) -> &str {
44 // Statements of the form
45 // let pat: ty = init;
46 impl Rewrite for ast::Local {
47 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
49 "Local::rewrite {:?} {} {:?}",
50 self, shape.width, shape.indent
53 skip_out_of_file_lines_range!(context, self.span);
55 if contains_skip(&self.attrs) {
59 let attrs_str = self.attrs.rewrite(context, shape)?;
60 let mut result = if attrs_str.is_empty() {
63 combine_strs_with_missing_comments(
68 self.attrs.last().map(|a| a.span.hi()).unwrap(),
77 let pat_shape = shape.offset_left(4)?;
79 let pat_shape = pat_shape.sub_width(1)?;
80 let pat_str = self.pat.rewrite(context, pat_shape)?;
81 result.push_str(&pat_str);
83 // String that is placed within the assignment pattern and expression.
85 let mut infix = String::with_capacity(32);
87 if let Some(ref ty) = self.ty {
88 let separator = type_annotation_separator(context.config);
89 let ty_shape = if pat_str.contains('\n') {
90 shape.with_max_width(context.config)
94 .offset_left(last_line_width(&result) + separator.len())?
98 let rewrite = ty.rewrite(context, ty_shape)?;
100 infix.push_str(separator);
101 infix.push_str(&rewrite);
104 if self.init.is_some() {
105 infix.push_str(" =");
111 result.push_str(&infix);
113 if let Some(ref ex) = self.init {
114 // 1 = trailing semicolon;
115 let nested_shape = shape.sub_width(1)?;
117 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
125 // FIXME convert to using rewrite style rather than visitor
126 // FIXME format modules in this style
129 unsafety: ast::Unsafe,
130 abi: Cow<'static, str>,
131 vis: Option<&'a ast::Visibility>,
132 body: Vec<BodyElement<'a>>,
137 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
139 unsafety: fm.unsafety,
141 ast::Extern::from_abi(fm.abi),
142 config.force_explicit_abi(),
149 .map(|i| BodyElement::ForeignItem(i))
156 enum BodyElement<'a> {
157 // Stmt(&'a ast::Stmt),
158 // Field(&'a ast::Field),
159 // Variant(&'a ast::Variant),
160 // Item(&'a ast::Item),
161 ForeignItem(&'a ast::ForeignItem),
164 /// Represents a fn's signature.
165 pub(crate) struct FnSig<'a> {
166 decl: &'a ast::FnDecl,
167 generics: &'a ast::Generics,
169 is_async: Cow<'a, ast::Async>,
170 constness: ast::Const,
171 defaultness: ast::Defaultness,
172 unsafety: ast::Unsafe,
173 visibility: ast::Visibility,
178 decl: &'a ast::FnDecl,
179 generics: &'a ast::Generics,
180 vis: ast::Visibility,
185 ext: ast::Extern::None,
186 is_async: Cow::Owned(ast::Async::No),
187 constness: ast::Const::No,
188 defaultness: ast::Defaultness::Final,
189 unsafety: ast::Unsafe::No,
194 pub(crate) fn from_method_sig(
195 method_sig: &'a ast::FnSig,
196 generics: &'a ast::Generics,
199 unsafety: method_sig.header.unsafety,
200 is_async: Cow::Borrowed(&method_sig.header.asyncness),
201 constness: method_sig.header.constness,
202 defaultness: ast::Defaultness::Final,
203 ext: method_sig.header.ext,
204 decl: &*method_sig.decl,
206 visibility: DEFAULT_VISIBILITY,
210 pub(crate) fn from_fn_kind(
211 fn_kind: &'a visit::FnKind<'_>,
212 generics: &'a ast::Generics,
213 decl: &'a ast::FnDecl,
214 defaultness: ast::Defaultness,
217 visit::FnKind::Fn(fn_ctxt, _, fn_sig, vis, _) => match fn_ctxt {
218 visit::FnCtxt::Assoc(..) => {
219 let mut fn_sig = FnSig::from_method_sig(fn_sig, generics);
220 fn_sig.defaultness = defaultness;
221 fn_sig.visibility = vis.clone();
227 ext: fn_sig.header.ext,
228 constness: fn_sig.header.constness,
229 is_async: Cow::Borrowed(&fn_sig.header.asyncness),
231 unsafety: fn_sig.header.unsafety,
232 visibility: vis.clone(),
239 fn to_str(&self, context: &RewriteContext<'_>) -> String {
240 let mut result = String::with_capacity(128);
241 // Vis defaultness constness unsafety abi.
242 result.push_str(&*format_visibility(context, &self.visibility));
243 result.push_str(format_defaultness(self.defaultness));
244 result.push_str(format_constness(self.constness));
245 result.push_str(format_async(&self.is_async));
246 result.push_str(format_unsafety(self.unsafety));
247 result.push_str(&format_extern(
249 context.config.force_explicit_abi(),
256 impl<'a> FmtVisitor<'a> {
257 fn format_item(&mut self, item: &Item<'_>) {
258 self.buffer.push_str(format_unsafety(item.unsafety));
259 self.buffer.push_str(&item.abi);
261 let snippet = self.snippet(item.span);
262 let brace_pos = snippet.find_uncommented("{").unwrap();
265 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
266 // FIXME: this skips comments between the extern keyword and the opening
268 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
269 self.block_indent = self.block_indent.block_indent(self.config);
271 if !item.body.is_empty() {
272 for item in &item.body {
273 self.format_body_element(item);
277 self.format_missing_no_indent(item.span.hi() - BytePos(1));
278 self.block_indent = self.block_indent.block_unindent(self.config);
279 let indent_str = self.block_indent.to_string(self.config);
280 self.push_str(&indent_str);
284 self.last_pos = item.span.hi();
287 fn format_body_element(&mut self, element: &BodyElement<'_>) {
289 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
293 pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
294 let item = Item::from_foreign_mod(fm, span, self.config);
295 self.format_item(&item);
298 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
299 let rewrite = item.rewrite(&self.get_context(), self.shape());
300 let hi = item.span.hi();
301 let span = if item.attrs.is_empty() {
304 mk_sp(item.attrs[0].span.lo(), hi)
306 self.push_rewrite(span, rewrite);
310 pub(crate) fn rewrite_fn_before_block(
313 ident: symbol::Ident,
316 ) -> Option<(String, FnBraceStyle)> {
317 let context = self.get_context();
319 let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
320 let (result, force_newline_brace) =
321 rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style)?;
324 if self.config.brace_style() == BraceStyle::AlwaysNextLine
325 || force_newline_brace
326 || last_line_width(&result) + 2 > self.shape().width
328 fn_brace_style = FnBraceStyle::NextLine
331 Some((result, fn_brace_style))
334 pub(crate) fn rewrite_required_fn(
337 ident: symbol::Ident,
339 generics: &ast::Generics,
341 ) -> Option<String> {
342 // Drop semicolon or it will be interpreted as comment.
343 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
344 let context = self.get_context();
346 let (mut result, _) = rewrite_fn_base(
350 &FnSig::from_method_sig(sig, generics),
355 // Re-attach semicolon
361 pub(crate) fn single_line_fn(
365 inner_attrs: Option<&[ast::Attribute]>,
366 ) -> Option<String> {
367 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
371 let context = self.get_context();
373 if self.config.empty_item_single_line()
374 && is_empty_block(&context, block, None)
375 && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
376 && !last_line_contains_single_line_comment(fn_str)
378 return Some(format!("{} {{}}", fn_str));
381 if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) {
385 let res = Stmt::from_ast_node(block.stmts.first()?, true)
386 .rewrite(&self.get_context(), self.shape())?;
388 let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
389 if !res.contains('\n') && width <= self.config.max_width() {
390 Some(format!("{} {{ {} }}", fn_str, res))
396 pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
397 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
398 self.push_rewrite(static_parts.span, rewrite);
401 pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
402 let is_tuple = match struct_parts.def {
403 ast::VariantData::Tuple(..) => true,
406 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
407 .map(|s| if is_tuple { s + ";" } else { s });
408 self.push_rewrite(struct_parts.span, rewrite);
411 pub(crate) fn visit_enum(
413 ident: symbol::Ident,
414 vis: &ast::Visibility,
415 enum_def: &ast::EnumDef,
416 generics: &ast::Generics,
419 let enum_header = format_header(&self.get_context(), "enum ", ident, vis);
420 self.push_str(&enum_header);
422 let enum_snippet = self.snippet(span);
423 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
424 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
425 let generics_str = format_generics(
428 self.config.brace_style(),
429 if enum_def.variants.is_empty() {
430 BracePos::ForceSameLine
435 // make a span that starts right after `enum Foo`
436 mk_sp(ident.span.hi(), body_start),
437 last_line_width(&enum_header),
440 self.push_str(&generics_str);
442 self.last_pos = body_start;
444 match self.format_variant_list(enum_def, body_start, span.hi()) {
445 Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
447 self.push_rewrite(mk_sp(body_start, span.hi()), rw);
448 self.block_indent = self.block_indent.block_unindent(self.config);
453 // Format the body of an enum definition
454 fn format_variant_list(
456 enum_def: &ast::EnumDef,
459 ) -> Option<String> {
460 if enum_def.variants.is_empty() {
461 let mut buffer = String::with_capacity(128);
463 let span = mk_sp(body_lo, body_hi - BytePos(1));
464 format_empty_struct_or_tuple(
474 let mut result = String::with_capacity(1024);
475 let original_offset = self.block_indent;
476 self.block_indent = self.block_indent.block_indent(self.config);
478 // If enum variants have discriminants, try to vertically align those,
479 // provided the discrims are not shifted too much to the right
480 let align_threshold: usize = self.config.enum_discrim_align_threshold();
481 let discr_ident_lens: Vec<usize> = enum_def
484 .filter(|var| var.disr_expr.is_some())
485 .map(|var| rewrite_ident(&self.get_context(), var.ident).len())
487 // cut the list at the point of longest discrim shorter than the threshold
488 // All of the discrims under the threshold will get padded, and all above - left as is.
489 let pad_discrim_ident_to = *discr_ident_lens
491 .filter(|&l| *l <= align_threshold)
495 let itemize_list_with = |one_line_width: usize| {
497 self.snippet_provider,
498 enum_def.variants.iter(),
502 if !f.attrs.is_empty() {
509 |f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
516 let mut items: Vec<_> =
517 itemize_list_with(self.config.width_heuristics().struct_variant_width);
518 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
519 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
520 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
521 if has_multiline_variant && has_single_line_variant {
522 items = itemize_list_with(0);
525 let shape = self.shape().sub_width(2)?;
526 let fmt = ListFormatting::new(shape, self.config)
527 .trailing_separator(self.config.trailing_comma())
528 .preserve_newline(true);
530 let list = write_list(&items, &fmt)?;
531 result.push_str(&list);
532 result.push_str(&original_offset.to_string_with_newline(self.config));
537 // Variant of an enum.
540 field: &ast::Variant,
541 one_line_width: usize,
542 pad_discrim_ident_to: usize,
543 ) -> Option<String> {
544 if contains_skip(&field.attrs) {
545 let lo = field.attrs[0].span.lo();
546 let span = mk_sp(lo, field.span.hi());
547 return Some(self.snippet(span).to_owned());
550 let context = self.get_context();
552 let shape = self.shape().sub_width(1)?;
553 let attrs_str = field.attrs.rewrite(&context, shape)?;
557 .map_or(field.span.lo(), |attr| attr.span.hi());
558 let span = mk_sp(lo, field.span.lo());
560 let variant_body = match field.data {
561 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
563 &StructParts::from_variant(field),
565 Some(one_line_width),
567 ast::VariantData::Unit(..) => rewrite_ident(&context, field.ident).to_owned(),
570 let variant_body = if let Some(ref expr) = field.disr_expr {
571 let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to);
572 rewrite_assign_rhs_with(
577 RhsTactics::AllowOverflow,
583 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
586 fn visit_impl_items(&mut self, items: &[ptr::P<ast::AssocItem>]) {
587 if self.get_context().config.reorder_impl_items() {
588 // Create visitor for each items, then reorder them.
589 let mut buffer = vec![];
591 self.visit_impl_item(item);
592 buffer.push((self.buffer.clone(), item.clone()));
596 fn is_type(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
597 if let Some(lty) = ty {
598 if let ast::TyKind::ImplTrait(..) = lty.kind {
605 fn is_opaque(ty: &Option<rustc_ast::ptr::P<ast::Ty>>) -> bool {
610 a: &Option<rustc_ast::ptr::P<ast::Ty>>,
611 b: &Option<rustc_ast::ptr::P<ast::Ty>>,
613 is_type(a) && is_type(b)
617 a: &Option<rustc_ast::ptr::P<ast::Ty>>,
618 b: &Option<rustc_ast::ptr::P<ast::Ty>>,
620 is_opaque(a) && is_opaque(b)
623 // In rustc-ap-v638 the `OpaqueTy` AssocItemKind variant was removed but
624 // we still need to differentiate to maintain sorting order.
626 // type -> opaque -> const -> macro -> method
627 use crate::ast::AssocItemKind::*;
628 fn need_empty_line(a: &ast::AssocItemKind, b: &ast::AssocItemKind) -> bool {
630 (TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
631 if both_type(lty, rty) || both_opaque(lty, rty) =>
635 (Const(..), Const(..)) => false,
640 buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
641 (TyAlias(_, _, _, ref lty), TyAlias(_, _, _, ref rty))
642 if both_type(lty, rty) || both_opaque(lty, rty) =>
644 a.ident.as_str().cmp(&b.ident.as_str())
646 (Const(..), Const(..)) | (MacCall(..), MacCall(..)) => {
647 a.ident.as_str().cmp(&b.ident.as_str())
649 (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()),
650 (TyAlias(_, _, _, ref ty), _) if is_type(ty) => Ordering::Less,
651 (_, TyAlias(_, _, _, ref ty)) if is_type(ty) => Ordering::Greater,
652 (TyAlias(..), _) => Ordering::Less,
653 (_, TyAlias(..)) => Ordering::Greater,
654 (Const(..), _) => Ordering::Less,
655 (_, Const(..)) => Ordering::Greater,
656 (MacCall(..), _) => Ordering::Less,
657 (_, MacCall(..)) => Ordering::Greater,
659 let mut prev_kind = None;
660 for (buf, item) in buffer {
661 // Make sure that there are at least a single empty line between
662 // different impl items.
665 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.kind))
669 let indent_str = self.block_indent.to_string_with_newline(self.config);
670 self.push_str(&indent_str);
671 self.push_str(buf.trim());
672 prev_kind = Some(item.kind.clone());
676 self.visit_impl_item(item);
682 pub(crate) fn format_impl(
683 context: &RewriteContext<'_>,
686 ) -> Option<String> {
687 if let ast::ItemKind::Impl {
694 let mut result = String::with_capacity(128);
695 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
696 let sep = offset.to_string_with_newline(context.config);
697 result.push_str(&ref_and_type);
699 let where_budget = if result.contains('\n') {
700 context.config.max_width()
702 context.budget(last_line_width(&result))
705 let mut option = WhereClauseOption::snuggled(&ref_and_type);
706 let snippet = context.snippet(item.span);
707 let open_pos = snippet.find_uncommented("{")? + 1;
708 if !contains_comment(&snippet[open_pos..])
710 && generics.where_clause.predicates.len() == 1
711 && !result.contains('\n')
713 option.suppress_comma();
715 option.allow_single_line();
718 let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
719 let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
720 let where_clause_str = rewrite_where_clause(
722 &generics.where_clause,
723 context.config.brace_style(),
724 Shape::legacy(where_budget, offset.block_only()),
732 // If there is no where-clause, we may have missing comments between the trait name and
733 // the opening brace.
734 if generics.where_clause.predicates.is_empty() {
735 if let Some(hi) = where_span_end {
736 match recover_missing_comment_in_span(
737 mk_sp(self_ty.span.hi(), hi),
738 Shape::indented(offset, context.config),
740 last_line_width(&result),
742 Some(ref missing_comment) if !missing_comment.is_empty() => {
743 result.push_str(missing_comment);
750 if is_impl_single_line(context, items.as_slice(), &result, &where_clause_str, item)? {
751 result.push_str(&where_clause_str);
752 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
753 // if the where_clause contains extra comments AND
754 // there is only one where-clause predicate
755 // recover the suppressed comma in single line where_clause formatting
756 if generics.where_clause.predicates.len() == 1 {
757 result.push_str(",");
759 result.push_str(&format!("{}{{{}}}", sep, sep));
761 result.push_str(" {}");
766 result.push_str(&where_clause_str);
768 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
769 match context.config.brace_style() {
770 _ if need_newline => result.push_str(&sep),
771 BraceStyle::AlwaysNextLine => result.push_str(&sep),
772 BraceStyle::PreferSameLine => result.push(' '),
773 BraceStyle::SameLineWhere => {
774 if !where_clause_str.is_empty() {
775 result.push_str(&sep);
783 // this is an impl body snippet(impl SampleImpl { /* here */ })
784 let lo = max(self_ty.span.hi(), generics.where_clause.span.hi());
785 let snippet = context.snippet(mk_sp(lo, item.span.hi()));
786 let open_pos = snippet.find_uncommented("{")? + 1;
788 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
789 let mut visitor = FmtVisitor::from_context(context);
790 let item_indent = offset.block_only().block_indent(context.config);
791 visitor.block_indent = item_indent;
792 visitor.last_pos = lo + BytePos(open_pos as u32);
794 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
795 visitor.visit_impl_items(items);
797 visitor.format_missing(item.span.hi() - BytePos(1));
799 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
800 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
802 result.push_str(&inner_indent_str);
803 result.push_str(visitor.buffer.trim());
804 result.push_str(&outer_indent_str);
805 } else if need_newline || !context.config.empty_item_single_line() {
806 result.push_str(&sep);
817 fn is_impl_single_line(
818 context: &RewriteContext<'_>,
819 items: &[ptr::P<ast::AssocItem>],
821 where_clause_str: &str,
824 let snippet = context.snippet(item.span);
825 let open_pos = snippet.find_uncommented("{")? + 1;
828 context.config.empty_item_single_line()
830 && !result.contains('\n')
831 && result.len() + where_clause_str.len() <= context.config.max_width()
832 && !contains_comment(&snippet[open_pos..]),
836 fn format_impl_ref_and_type(
837 context: &RewriteContext<'_>,
840 ) -> Option<String> {
841 if let ast::ItemKind::Impl {
846 of_trait: ref trait_ref,
851 let mut result = String::with_capacity(128);
853 result.push_str(&format_visibility(context, &item.vis));
854 result.push_str(format_defaultness(defaultness));
855 result.push_str(format_unsafety(unsafety));
857 let shape = if context.config.version() == Version::Two {
858 Shape::indented(offset + last_line_width(&result), context.config)
860 generics_shape_from_config(
862 Shape::indented(offset + last_line_width(&result), context.config),
866 let generics_str = rewrite_generics(context, "impl", generics, shape)?;
867 result.push_str(&generics_str);
869 let polarity_str = match polarity {
870 ast::ImplPolarity::Negative(_) => "!",
871 ast::ImplPolarity::Positive => "",
874 if let Some(ref trait_ref) = *trait_ref {
875 let result_len = last_line_width(&result);
876 result.push_str(&rewrite_trait_ref(
885 // Try to put the self type in a single line.
887 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
888 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
889 // If there is no where-clause adapt budget for type formatting to take space and curly
890 // brace into account.
891 match context.config.brace_style() {
892 BraceStyle::AlwaysNextLine => 0,
898 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
899 // 1 = space before the type.
900 let budget = context.budget(used_space + 1);
901 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
902 if !self_ty_str.contains('\n') {
903 if trait_ref.is_some() {
904 result.push_str(" for ");
908 result.push_str(&self_ty_str);
913 // Couldn't fit the self type on a single line, put it on a new line.
915 // Add indentation of one additional tab.
916 let new_line_offset = offset.block_indent(context.config);
917 result.push_str(&new_line_offset.to_string(context.config));
918 if trait_ref.is_some() {
919 result.push_str("for ");
921 let budget = context.budget(last_line_width(&result));
922 let type_offset = match context.config.indent_style() {
923 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
924 IndentStyle::Block => new_line_offset,
926 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
933 fn rewrite_trait_ref(
934 context: &RewriteContext<'_>,
935 trait_ref: &ast::TraitRef,
939 ) -> Option<String> {
940 // 1 = space between generics and trait_ref
941 let used_space = 1 + polarity_str.len() + result_len;
942 let shape = Shape::indented(offset + used_space, context.config);
943 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
944 if !trait_ref_str.contains('\n') {
945 return Some(format!(" {}{}", polarity_str, trait_ref_str));
948 // We could not make enough space for trait_ref, so put it on new line.
949 let offset = offset.block_indent(context.config);
950 let shape = Shape::indented(offset, context.config);
951 let trait_ref_str = trait_ref.rewrite(context, shape)?;
954 offset.to_string_with_newline(context.config),
960 pub(crate) struct StructParts<'a> {
962 ident: symbol::Ident,
963 vis: &'a ast::Visibility,
964 def: &'a ast::VariantData,
965 generics: Option<&'a ast::Generics>,
969 impl<'a> StructParts<'a> {
970 fn format_header(&self, context: &RewriteContext<'_>) -> String {
971 format_header(context, self.prefix, self.ident, self.vis)
974 fn from_variant(variant: &'a ast::Variant) -> Self {
977 ident: variant.ident,
978 vis: &DEFAULT_VISIBILITY,
985 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
986 let (prefix, def, generics) = match item.kind {
987 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
988 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
996 generics: Some(generics),
1003 context: &RewriteContext<'_>,
1004 struct_parts: &StructParts<'_>,
1006 one_line_width: Option<usize>,
1007 ) -> Option<String> {
1008 match *struct_parts.def {
1009 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
1010 ast::VariantData::Tuple(ref fields, _) => {
1011 format_tuple_struct(context, struct_parts, fields, offset)
1013 ast::VariantData::Struct(ref fields, _) => {
1014 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
1019 pub(crate) fn format_trait(
1020 context: &RewriteContext<'_>,
1023 ) -> Option<String> {
1024 if let ast::ItemKind::Trait(
1032 let mut result = String::with_capacity(128);
1033 let header = format!(
1035 format_visibility(context, &item.vis),
1036 format_unsafety(unsafety),
1037 format_auto(is_auto),
1039 result.push_str(&header);
1041 let body_lo = context.snippet_provider.span_after(item.span, "{");
1043 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
1045 rewrite_generics(context, rewrite_ident(context, item.ident), generics, shape)?;
1046 result.push_str(&generics_str);
1048 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
1049 if !generic_bounds.is_empty() {
1050 let ident_hi = context
1052 .span_after(item.span, &item.ident.as_str());
1053 let bound_hi = generic_bounds.last().unwrap().span().hi();
1054 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1055 if contains_comment(snippet) {
1059 result = rewrite_assign_rhs_with(
1064 RhsTactics::ForceNextLineWithoutIndent,
1068 // Rewrite where-clause.
1069 if !generics.where_clause.predicates.is_empty() {
1070 let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1072 let where_budget = context.budget(last_line_width(&result));
1073 let pos_before_where = if generic_bounds.is_empty() {
1074 generics.where_clause.span.lo()
1076 generic_bounds[generic_bounds.len() - 1].span().hi()
1078 let option = WhereClauseOption::snuggled(&generics_str);
1079 let where_clause_str = rewrite_where_clause(
1081 &generics.where_clause,
1082 context.config.brace_style(),
1083 Shape::legacy(where_budget, offset.block_only()),
1090 // If the where-clause cannot fit on the same line,
1091 // put the where-clause on a new line
1092 if !where_clause_str.contains('\n')
1093 && last_line_width(&result) + where_clause_str.len() + offset.width()
1094 > context.config.comment_width()
1096 let width = offset.block_indent + context.config.tab_spaces() - 1;
1097 let where_indent = Indent::new(0, width);
1098 result.push_str(&where_indent.to_string_with_newline(context.config));
1100 result.push_str(&where_clause_str);
1102 let item_snippet = context.snippet(item.span);
1103 if let Some(lo) = item_snippet.find('/') {
1105 let comment_hi = body_lo - BytePos(1);
1106 let comment_lo = item.span.lo() + BytePos(lo as u32);
1107 if comment_lo < comment_hi {
1108 match recover_missing_comment_in_span(
1109 mk_sp(comment_lo, comment_hi),
1110 Shape::indented(offset, context.config),
1112 last_line_width(&result),
1114 Some(ref missing_comment) if !missing_comment.is_empty() => {
1115 result.push_str(missing_comment);
1123 match context.config.brace_style() {
1124 _ if last_line_contains_single_line_comment(&result)
1125 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1127 result.push_str(&offset.to_string_with_newline(context.config));
1129 BraceStyle::AlwaysNextLine => {
1130 result.push_str(&offset.to_string_with_newline(context.config));
1132 BraceStyle::PreferSameLine => result.push(' '),
1133 BraceStyle::SameLineWhere => {
1134 if result.contains('\n')
1135 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1137 result.push_str(&offset.to_string_with_newline(context.config));
1145 let snippet = context.snippet(item.span);
1146 let open_pos = snippet.find_uncommented("{")? + 1;
1147 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1149 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1150 let mut visitor = FmtVisitor::from_context(context);
1151 visitor.block_indent = offset.block_only().block_indent(context.config);
1152 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1154 for item in trait_items {
1155 visitor.visit_trait_item(item);
1158 visitor.format_missing(item.span.hi() - BytePos(1));
1160 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1162 result.push_str(&inner_indent_str);
1163 result.push_str(visitor.buffer.trim());
1164 result.push_str(&outer_indent_str);
1165 } else if result.contains('\n') {
1166 result.push_str(&outer_indent_str);
1176 struct OpaqueTypeBounds<'a> {
1177 generic_bounds: &'a ast::GenericBounds,
1180 impl<'a> Rewrite for OpaqueTypeBounds<'a> {
1181 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1183 .rewrite(context, shape)
1184 .map(|s| format!("impl {}", s))
1188 pub(crate) struct TraitAliasBounds<'a> {
1189 generic_bounds: &'a ast::GenericBounds,
1190 generics: &'a ast::Generics,
1193 impl<'a> Rewrite for TraitAliasBounds<'a> {
1194 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1195 let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
1197 let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1198 option.allow_single_line();
1200 let where_str = rewrite_where_clause(
1202 &self.generics.where_clause,
1203 context.config.brace_style(),
1208 self.generics.where_clause.span.lo(),
1212 let fits_single_line = !generic_bounds_str.contains('\n')
1213 && !where_str.contains('\n')
1214 && generic_bounds_str.len() + where_str.len() + 1 <= shape.width;
1215 let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1217 } else if fits_single_line {
1220 shape.indent.to_string_with_newline(&context.config)
1223 Some(format!("{}{}{}", generic_bounds_str, space, where_str))
1227 pub(crate) fn format_trait_alias(
1228 context: &RewriteContext<'_>,
1229 ident: symbol::Ident,
1230 vis: &ast::Visibility,
1231 generics: &ast::Generics,
1232 generic_bounds: &ast::GenericBounds,
1234 ) -> Option<String> {
1235 let alias = rewrite_ident(context, ident);
1236 // 6 = "trait ", 2 = " ="
1237 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1238 let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
1239 let vis_str = format_visibility(context, vis);
1240 let lhs = format!("{}trait {} =", vis_str, generics_str);
1242 let trait_alias_bounds = TraitAliasBounds {
1246 rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";")
1249 fn format_unit_struct(
1250 context: &RewriteContext<'_>,
1251 p: &StructParts<'_>,
1253 ) -> Option<String> {
1254 let header_str = format_header(context, p.prefix, p.ident, p.vis);
1255 let generics_str = if let Some(generics) = p.generics {
1256 let hi = context.snippet_provider.span_before(p.span, ";");
1260 context.config.brace_style(),
1263 // make a span that starts right after `struct Foo`
1264 mk_sp(p.ident.span.hi(), hi),
1265 last_line_width(&header_str),
1270 Some(format!("{}{};", header_str, generics_str))
1273 pub(crate) fn format_struct_struct(
1274 context: &RewriteContext<'_>,
1275 struct_parts: &StructParts<'_>,
1276 fields: &[ast::StructField],
1278 one_line_width: Option<usize>,
1279 ) -> Option<String> {
1280 let mut result = String::with_capacity(1024);
1281 let span = struct_parts.span;
1283 let header_str = struct_parts.format_header(context);
1284 result.push_str(&header_str);
1286 let header_hi = struct_parts.ident.span.hi();
1287 let body_lo = context.snippet_provider.span_after(span, "{");
1289 let generics_str = match struct_parts.generics {
1290 Some(g) => format_generics(
1293 context.config.brace_style(),
1294 if fields.is_empty() {
1295 BracePos::ForceSameLine
1300 // make a span that starts right after `struct Foo`
1301 mk_sp(header_hi, body_lo),
1302 last_line_width(&result),
1305 // 3 = ` {}`, 2 = ` {`.
1306 let overhead = if fields.is_empty() { 3 } else { 2 };
1307 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1308 || context.config.max_width() < overhead + result.len()
1310 format!("\n{}{{", offset.block_only().to_string(context.config))
1317 let overhead = if fields.is_empty() { 1 } else { 0 };
1318 let total_width = result.len() + generics_str.len() + overhead;
1319 if !generics_str.is_empty()
1320 && !generics_str.contains('\n')
1321 && total_width > context.config.max_width()
1324 result.push_str(&offset.to_string(context.config));
1325 result.push_str(generics_str.trim_start());
1327 result.push_str(&generics_str);
1330 if fields.is_empty() {
1331 let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1332 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1333 return Some(result);
1337 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1338 let one_line_budget =
1339 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1341 let items_str = rewrite_with_alignment(
1344 Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
1345 mk_sp(body_lo, span.hi()),
1349 if !items_str.contains('\n')
1350 && !result.contains('\n')
1351 && items_str.len() <= one_line_budget
1352 && !last_line_contains_single_line_comment(&items_str)
1354 Some(format!("{} {} }}", result, items_str))
1360 .block_indent(context.config)
1361 .to_string(context.config),
1363 offset.to_string(context.config)
1368 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1370 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1371 _ => default_span.lo(),
1375 // Format tuple or struct without any fields. We need to make sure that the comments
1376 // inside the delimiters are preserved.
1377 fn format_empty_struct_or_tuple(
1378 context: &RewriteContext<'_>,
1381 result: &mut String,
1385 // 3 = " {}" or "();"
1386 let used_width = last_line_used_width(&result, offset.width()) + 3;
1387 if used_width > context.config.max_width() {
1388 result.push_str(&offset.to_string_with_newline(context.config))
1390 result.push_str(opener);
1391 match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1392 Some(ref s) if s.is_empty() => (),
1394 if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1395 let nested_indent_str = offset
1396 .block_indent(context.config)
1397 .to_string_with_newline(context.config);
1398 result.push_str(&nested_indent_str);
1401 if last_line_contains_single_line_comment(s) {
1402 result.push_str(&offset.to_string_with_newline(context.config));
1405 None => result.push_str(context.snippet(span)),
1407 result.push_str(closer);
1410 fn format_tuple_struct(
1411 context: &RewriteContext<'_>,
1412 struct_parts: &StructParts<'_>,
1413 fields: &[ast::StructField],
1415 ) -> Option<String> {
1416 let mut result = String::with_capacity(1024);
1417 let span = struct_parts.span;
1419 let header_str = struct_parts.format_header(context);
1420 result.push_str(&header_str);
1422 let body_lo = if fields.is_empty() {
1423 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1426 .span_after(mk_sp(lo, span.hi()), "(")
1430 let body_hi = if fields.is_empty() {
1433 .span_after(mk_sp(body_lo, span.hi()), ")")
1435 // This is a dirty hack to work around a missing `)` from the span of the last field.
1436 let last_arg_span = fields[fields.len() - 1].span;
1439 .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1440 .unwrap_or_else(|| last_arg_span.hi())
1443 let where_clause_str = match struct_parts.generics {
1445 let budget = context.budget(last_line_width(&header_str));
1446 let shape = Shape::legacy(budget, offset);
1447 let generics_str = rewrite_generics(context, "", generics, shape)?;
1448 result.push_str(&generics_str);
1450 let where_budget = context.budget(last_line_width(&result));
1451 let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1452 rewrite_where_clause(
1454 &generics.where_clause,
1455 context.config.brace_style(),
1456 Shape::legacy(where_budget, offset.block_only()),
1464 None => "".to_owned(),
1467 if fields.is_empty() {
1468 let body_hi = context
1470 .span_before(mk_sp(body_lo, span.hi()), ")");
1471 let inner_span = mk_sp(body_lo, body_hi);
1472 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1474 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1475 result = overflow::rewrite_with_parens(
1481 context.config.width_heuristics().fn_call_width,
1486 if !where_clause_str.is_empty()
1487 && !where_clause_str.contains('\n')
1488 && (result.contains('\n')
1489 || offset.block_indent + result.len() + where_clause_str.len() + 1
1490 > context.config.max_width())
1492 // We need to put the where-clause on a new line, but we didn't
1493 // know that earlier, so the where-clause will not be indented properly.
1496 &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1499 result.push_str(&where_clause_str);
1504 fn rewrite_type<R: Rewrite>(
1505 context: &RewriteContext<'_>,
1507 ident: symbol::Ident,
1508 vis: &ast::Visibility,
1509 generics: &ast::Generics,
1510 generic_bounds_opt: Option<&ast::GenericBounds>,
1512 ) -> Option<String> {
1513 let mut result = String::with_capacity(128);
1514 result.push_str(&format!("{}type ", format_visibility(context, vis)));
1515 let ident_str = rewrite_ident(context, ident);
1517 if generics.params.is_empty() {
1518 result.push_str(ident_str)
1521 let g_shape = Shape::indented(indent, context.config)
1522 .offset_left(result.len())?
1524 let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1525 result.push_str(&generics_str);
1528 if let Some(bounds) = generic_bounds_opt {
1529 if !bounds.is_empty() {
1531 let shape = Shape::indented(indent, context.config).offset_left(result.len() + 2)?;
1532 let type_bounds = bounds.rewrite(context, shape).map(|s| format!(": {}", s))?;
1533 result.push_str(&type_bounds);
1537 let where_budget = context.budget(last_line_width(&result));
1538 let mut option = WhereClauseOption::snuggled(&result);
1540 option.suppress_comma();
1542 let where_clause_str = rewrite_where_clause(
1544 &generics.where_clause,
1545 context.config.brace_style(),
1546 Shape::legacy(where_budget, indent),
1553 result.push_str(&where_clause_str);
1555 if let Some(ty) = rhs {
1556 // If there's a where clause, add a newline before the assignment. Otherwise just add a
1558 if !generics.where_clause.predicates.is_empty() {
1559 result.push_str(&indent.to_string_with_newline(context.config));
1563 let lhs = format!("{}=", result);
1566 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1567 rewrite_assign_rhs(context, lhs, &*ty, shape).map(|s| s + ";")
1569 Some(format!("{};", result))
1573 pub(crate) fn rewrite_opaque_type(
1574 context: &RewriteContext<'_>,
1576 ident: symbol::Ident,
1577 generic_bounds: &ast::GenericBounds,
1578 generics: &ast::Generics,
1579 vis: &ast::Visibility,
1580 ) -> Option<String> {
1581 let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
1588 Some(generic_bounds),
1589 Some(&opaque_type_bounds),
1593 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1595 if config.space_before_colon() { " " } else { "" },
1596 if config.space_after_colon() { " " } else { "" },
1600 pub(crate) fn rewrite_struct_field_prefix(
1601 context: &RewriteContext<'_>,
1602 field: &ast::StructField,
1603 ) -> Option<String> {
1604 let vis = format_visibility(context, &field.vis);
1605 let type_annotation_spacing = type_annotation_spacing(context.config);
1606 Some(match field.ident {
1607 Some(name) => format!(
1610 rewrite_ident(context, name),
1611 type_annotation_spacing.0
1613 None => vis.to_string(),
1617 impl Rewrite for ast::StructField {
1618 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1619 rewrite_struct_field(context, self, shape, 0)
1623 pub(crate) fn rewrite_struct_field(
1624 context: &RewriteContext<'_>,
1625 field: &ast::StructField,
1627 lhs_max_width: usize,
1628 ) -> Option<String> {
1629 if contains_skip(&field.attrs) {
1630 return Some(context.snippet(field.span()).to_owned());
1633 let type_annotation_spacing = type_annotation_spacing(context.config);
1634 let prefix = rewrite_struct_field_prefix(context, field)?;
1636 let attrs_str = field.attrs.rewrite(context, shape)?;
1637 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1638 let missing_span = if field.attrs.is_empty() {
1639 mk_sp(field.span.lo(), field.span.lo())
1641 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1643 let mut spacing = String::from(if field.ident.is_some() {
1644 type_annotation_spacing.1
1648 // Try to put everything on a single line.
1649 let attr_prefix = combine_strs_with_missing_comments(
1657 let overhead = trimmed_last_line_width(&attr_prefix);
1658 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1659 for _ in 0..lhs_offset {
1662 // In this extreme case we will be missing a space between an attribute and a field.
1663 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1667 .offset_left(overhead + spacing.len())
1668 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1669 if let Some(ref ty) = orig_ty {
1670 if !ty.contains('\n') {
1671 return Some(attr_prefix + &spacing + ty);
1675 let is_prefix_empty = prefix.is_empty();
1676 // We must use multiline. We are going to put attributes and a field on different lines.
1677 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1678 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1679 let field_str = if is_prefix_empty {
1680 field_str.trim_start()
1684 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1687 pub(crate) struct StaticParts<'a> {
1689 vis: &'a ast::Visibility,
1690 ident: symbol::Ident,
1692 mutability: ast::Mutability,
1693 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1694 defaultness: Option<ast::Defaultness>,
1698 impl<'a> StaticParts<'a> {
1699 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1700 let (defaultness, prefix, ty, mutability, expr) = match item.kind {
1701 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
1702 (None, "static", ty, mutability, expr)
1704 ast::ItemKind::Const(defaultness, ref ty, ref expr) => {
1705 (Some(defaultness), "const", ty, ast::Mutability::Not, expr)
1707 _ => unreachable!(),
1715 expr_opt: expr.as_ref(),
1721 pub(crate) fn from_trait_item(ti: &'a ast::AssocItem) -> Self {
1722 let (defaultness, ty, expr_opt) = match ti.kind {
1723 ast::AssocItemKind::Const(defaultness, ref ty, ref expr_opt) => {
1724 (defaultness, ty, expr_opt)
1726 _ => unreachable!(),
1730 vis: &DEFAULT_VISIBILITY,
1733 mutability: ast::Mutability::Not,
1734 expr_opt: expr_opt.as_ref(),
1735 defaultness: Some(defaultness),
1740 pub(crate) fn from_impl_item(ii: &'a ast::AssocItem) -> Self {
1741 let (defaultness, ty, expr) = match ii.kind {
1742 ast::AssocItemKind::Const(defaultness, ref ty, ref expr) => (defaultness, ty, expr),
1743 _ => unreachable!(),
1750 mutability: ast::Mutability::Not,
1751 expr_opt: expr.as_ref(),
1752 defaultness: Some(defaultness),
1759 context: &RewriteContext<'_>,
1760 static_parts: &StaticParts<'_>,
1762 ) -> Option<String> {
1763 let colon = colon_spaces(context.config);
1764 let mut prefix = format!(
1766 format_visibility(context, static_parts.vis),
1767 static_parts.defaultness.map_or("", format_defaultness),
1768 static_parts.prefix,
1769 format_mutability(static_parts.mutability),
1770 rewrite_ident(context, static_parts.ident),
1775 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1776 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1777 Some(ty_str) => ty_str,
1779 if prefix.ends_with(' ') {
1782 let nested_indent = offset.block_indent(context.config);
1783 let nested_shape = Shape::indented(nested_indent, context.config);
1784 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1787 nested_indent.to_string_with_newline(context.config),
1793 if let Some(expr) = static_parts.expr_opt {
1794 let lhs = format!("{}{} =", prefix, ty_str);
1796 let remaining_width = context.budget(offset.block_indent + 1);
1801 Shape::legacy(remaining_width, offset.block_only()),
1803 .and_then(|res| recover_comment_removed(res, static_parts.span, context))
1804 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1806 Some(format!("{}{};", prefix, ty_str))
1810 pub(crate) fn rewrite_type_alias(
1811 ident: symbol::Ident,
1812 ty_opt: Option<&ptr::P<ast::Ty>>,
1813 generics: &ast::Generics,
1814 generic_bounds_opt: Option<&ast::GenericBounds>,
1815 context: &RewriteContext<'_>,
1817 vis: &ast::Visibility,
1818 ) -> Option<String> {
1830 struct OpaqueType<'a> {
1831 bounds: &'a ast::GenericBounds,
1834 impl<'a> Rewrite for OpaqueType<'a> {
1835 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1836 let shape = shape.offset_left(5)?; // `impl `
1838 .rewrite(context, shape)
1839 .map(|s| format!("impl {}", s))
1843 pub(crate) fn rewrite_opaque_impl_type(
1844 context: &RewriteContext<'_>,
1845 ident: symbol::Ident,
1846 generics: &ast::Generics,
1847 generic_bounds: &ast::GenericBounds,
1849 ) -> Option<String> {
1850 let ident_str = rewrite_ident(context, ident);
1852 let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
1853 let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
1854 let prefix = format!("type {} =", generics_str);
1855 let rhs = OpaqueType {
1856 bounds: generic_bounds,
1863 Shape::indented(indent, context.config).sub_width(1)?,
1868 pub(crate) fn rewrite_associated_impl_type(
1869 ident: symbol::Ident,
1870 vis: &ast::Visibility,
1871 defaultness: ast::Defaultness,
1872 ty_opt: Option<&ptr::P<ast::Ty>>,
1873 generics: &ast::Generics,
1874 context: &RewriteContext<'_>,
1876 ) -> Option<String> {
1877 let result = rewrite_type_alias(ident, ty_opt, generics, None, context, indent, vis)?;
1880 ast::Defaultness::Default(..) => Some(format!("default {}", result)),
1885 impl Rewrite for ast::FnRetTy {
1886 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1888 ast::FnRetTy::Default(_) => Some(String::new()),
1889 ast::FnRetTy::Ty(ref ty) => {
1890 if context.config.version() == Version::One
1891 || context.config.indent_style() == IndentStyle::Visual
1893 let inner_width = shape.width.checked_sub(3)?;
1895 .rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1896 .map(|r| format!("-> {}", r));
1899 ty.rewrite(context, shape.offset_left(3)?)
1900 .map(|s| format!("-> {}", s))
1906 fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
1908 ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
1913 /// Recover any missing comments between the param and the type.
1917 /// A 2-len tuple with the comment before the colon in first position, and the comment after the
1918 /// colon in second position.
1919 fn get_missing_param_comments(
1920 context: &RewriteContext<'_>,
1924 ) -> (String, String) {
1925 let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
1927 let span_before_colon = {
1928 let missing_comment_span_hi = context
1930 .span_before(missing_comment_span, ":");
1931 mk_sp(pat_span.hi(), missing_comment_span_hi)
1933 let span_after_colon = {
1934 let missing_comment_span_lo = context
1936 .span_after(missing_comment_span, ":");
1937 mk_sp(missing_comment_span_lo, ty_span.lo())
1940 let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
1941 .filter(|comment| !comment.is_empty())
1942 .map_or(String::new(), |comment| format!(" {}", comment));
1943 let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
1944 .filter(|comment| !comment.is_empty())
1945 .map_or(String::new(), |comment| format!("{} ", comment));
1946 (comment_before_colon, comment_after_colon)
1949 impl Rewrite for ast::Param {
1950 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1951 let param_attrs_result = self
1953 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1954 let (span, has_multiple_attr_lines) = if !self.attrs.is_empty() {
1955 let num_attrs = self.attrs.len();
1957 mk_sp(self.attrs[num_attrs - 1].span.hi(), self.pat.span.lo()),
1958 param_attrs_result.contains("\n"),
1961 (mk_sp(self.span.lo(), self.span.lo()), false)
1964 if let Some(ref explicit_self) = self.to_self() {
1965 rewrite_explicit_self(
1968 ¶m_attrs_result,
1971 has_multiple_attr_lines,
1973 } else if is_named_param(self) {
1974 let mut result = combine_strs_with_missing_comments(
1976 ¶m_attrs_result,
1979 .rewrite(context, Shape::legacy(shape.width, shape.indent))?,
1982 !has_multiple_attr_lines,
1985 if !is_empty_infer(&*self.ty, self.pat.span) {
1986 let (before_comment, after_comment) =
1987 get_missing_param_comments(context, self.pat.span, self.ty.span, shape);
1988 result.push_str(&before_comment);
1989 result.push_str(colon_spaces(context.config));
1990 result.push_str(&after_comment);
1991 let overhead = last_line_width(&result);
1992 let max_width = shape.width.checked_sub(overhead)?;
1995 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1996 result.push_str(&ty_str);
2001 self.ty.rewrite(context, shape)
2006 fn rewrite_explicit_self(
2007 context: &RewriteContext<'_>,
2008 explicit_self: &ast::ExplicitSelf,
2012 has_multiple_attr_lines: bool,
2013 ) -> Option<String> {
2014 match explicit_self.node {
2015 ast::SelfKind::Region(lt, m) => {
2016 let mut_str = format_mutability(m);
2019 let lifetime_str = l.rewrite(
2021 Shape::legacy(context.config.max_width(), Indent::empty()),
2023 Some(combine_strs_with_missing_comments(
2026 &format!("&{} {}self", lifetime_str, mut_str),
2029 !has_multiple_attr_lines,
2032 None => Some(combine_strs_with_missing_comments(
2035 &format!("&{}self", mut_str),
2038 !has_multiple_attr_lines,
2042 ast::SelfKind::Explicit(ref ty, mutability) => {
2043 let type_str = ty.rewrite(
2045 Shape::legacy(context.config.max_width(), Indent::empty()),
2048 Some(combine_strs_with_missing_comments(
2051 &format!("{}self: {}", format_mutability(mutability), type_str),
2054 !has_multiple_attr_lines,
2057 ast::SelfKind::Value(mutability) => Some(combine_strs_with_missing_comments(
2060 &format!("{}self", format_mutability(mutability)),
2063 !has_multiple_attr_lines,
2068 pub(crate) fn span_lo_for_param(param: &ast::Param) -> BytePos {
2069 if param.attrs.is_empty() {
2070 if is_named_param(param) {
2076 param.attrs[0].span.lo()
2080 pub(crate) fn span_hi_for_param(context: &RewriteContext<'_>, param: &ast::Param) -> BytePos {
2081 match param.ty.kind {
2082 ast::TyKind::Infer if context.snippet(param.ty.span) == "_" => param.ty.span.hi(),
2083 ast::TyKind::Infer if is_named_param(param) => param.pat.span.hi(),
2084 _ => param.ty.span.hi(),
2088 pub(crate) fn is_named_param(param: &ast::Param) -> bool {
2089 if let ast::PatKind::Ident(_, ident, _) = param.pat.kind {
2090 ident.name != symbol::kw::Invalid
2096 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
2097 pub(crate) enum FnBraceStyle {
2103 // Return type is (result, force_new_line_for_brace)
2105 context: &RewriteContext<'_>,
2107 ident: symbol::Ident,
2110 fn_brace_style: FnBraceStyle,
2111 ) -> Option<(String, bool)> {
2112 let mut force_new_line_for_brace = false;
2114 let where_clause = &fn_sig.generics.where_clause;
2116 let mut result = String::with_capacity(1024);
2117 result.push_str(&fn_sig.to_str(context));
2120 result.push_str("fn ");
2123 let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
2130 let used_width = last_line_used_width(&result, indent.width());
2131 let one_line_budget = context.budget(used_width + overhead);
2133 width: one_line_budget,
2137 let fd = fn_sig.decl;
2138 let generics_str = rewrite_generics(
2140 rewrite_ident(context, ident),
2144 result.push_str(&generics_str);
2146 let snuggle_angle_bracket = generics_str
2149 .map_or(false, |l| l.trim_start().len() == 1);
2151 // Note that the width and indent don't really matter, we'll re-layout the
2152 // return type later anyway.
2155 .rewrite(context, Shape::indented(indent, context.config))?;
2157 let multi_line_ret_str = ret_str.contains('\n');
2158 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2161 let (one_line_budget, multi_line_budget, mut param_indent) = compute_budgets_for_params(
2171 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, param_indent: {:?}",
2172 one_line_budget, multi_line_budget, param_indent
2176 // Check if vertical layout was forced.
2177 if one_line_budget == 0
2178 && !snuggle_angle_bracket
2179 && context.config.indent_style() == IndentStyle::Visual
2181 result.push_str(¶m_indent.to_string_with_newline(context.config));
2184 // Skip `pub(crate)`.
2185 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
2186 // A conservative estimation, to goal is to be over all parens in generics
2187 let params_start = fn_sig
2192 .map_or(lo_after_visibility, |param| param.span().hi());
2193 let params_end = if fd.inputs.is_empty() {
2196 .span_after(mk_sp(params_start, span.hi()), ")")
2198 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2199 context.snippet_provider.span_after(last_span, ")")
2201 let params_span = mk_sp(
2204 .span_after(mk_sp(params_start, span.hi()), "("),
2207 let param_str = rewrite_params(
2218 let put_params_in_block = match context.config.indent_style() {
2219 IndentStyle::Block => param_str.contains('\n') || param_str.len() > one_line_budget,
2221 } && !fd.inputs.is_empty();
2223 let mut params_last_line_contains_comment = false;
2224 let mut no_params_and_over_max_width = false;
2226 if put_params_in_block {
2227 param_indent = indent.block_indent(context.config);
2228 result.push_str(¶m_indent.to_string_with_newline(context.config));
2229 result.push_str(¶m_str);
2230 result.push_str(&indent.to_string_with_newline(context.config));
2233 result.push_str(¶m_str);
2234 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2235 // Put the closing brace on the next line if it overflows the max width.
2237 let closing_paren_overflow_max_width =
2238 fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2239 // If the last line of params contains comment, we cannot put the closing paren
2240 // on the same line.
2241 params_last_line_contains_comment = param_str
2244 .map_or(false, |last_line| last_line.contains("//"));
2246 if context.config.version() == Version::Two {
2247 if closing_paren_overflow_max_width {
2249 result.push_str(&indent.to_string_with_newline(context.config));
2250 no_params_and_over_max_width = true;
2251 } else if params_last_line_contains_comment {
2252 result.push_str(&indent.to_string_with_newline(context.config));
2254 no_params_and_over_max_width = true;
2259 if closing_paren_overflow_max_width || params_last_line_contains_comment {
2260 result.push_str(&indent.to_string_with_newline(context.config));
2267 if let ast::FnRetTy::Ty(..) = fd.output {
2268 let ret_should_indent = match context.config.indent_style() {
2269 // If our params are block layout then we surely must have space.
2270 IndentStyle::Block if put_params_in_block || fd.inputs.is_empty() => false,
2271 _ if params_last_line_contains_comment => false,
2272 _ if result.contains('\n') || multi_line_ret_str => true,
2274 // If the return type would push over the max width, then put the return type on
2275 // a new line. With the +1 for the signature length an additional space between
2276 // the closing parenthesis of the param and the arrow '->' is considered.
2277 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2279 // If there is no where-clause, take into account the space after the return type
2281 if where_clause.predicates.is_empty() {
2285 sig_length > context.config.max_width()
2288 let ret_shape = if ret_should_indent {
2289 if context.config.version() == Version::One
2290 || context.config.indent_style() == IndentStyle::Visual
2292 let indent = if param_str.is_empty() {
2293 // Aligning with non-existent params looks silly.
2294 force_new_line_for_brace = true;
2297 // FIXME: we might want to check that using the param indent
2298 // doesn't blow our budget, and if it does, then fallback to
2299 // the where-clause indent.
2303 result.push_str(&indent.to_string_with_newline(context.config));
2304 Shape::indented(indent, context.config)
2306 let mut ret_shape = Shape::indented(indent, context.config);
2307 if param_str.is_empty() {
2308 // Aligning with non-existent params looks silly.
2309 force_new_line_for_brace = true;
2310 ret_shape = if context.use_block_indent() {
2311 ret_shape.offset_left(4).unwrap_or(ret_shape)
2313 ret_shape.indent = ret_shape.indent + 4;
2318 result.push_str(&ret_shape.indent.to_string_with_newline(context.config));
2322 if context.config.version() == Version::Two {
2323 if !param_str.is_empty() || !no_params_and_over_max_width {
2330 let ret_shape = Shape::indented(indent, context.config);
2332 .offset_left(last_line_width(&result))
2333 .unwrap_or(ret_shape)
2336 if multi_line_ret_str || ret_should_indent {
2337 // Now that we know the proper indent and width, we need to
2338 // re-layout the return type.
2339 let ret_str = fd.output.rewrite(context, ret_shape)?;
2340 result.push_str(&ret_str);
2342 result.push_str(&ret_str);
2345 // Comment between return type and the end of the decl.
2346 let snippet_lo = fd.output.span().hi();
2347 if where_clause.predicates.is_empty() {
2348 let snippet_hi = span.hi();
2349 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2350 // Try to preserve the layout of the original snippet.
2351 let original_starts_with_newline = snippet
2353 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2354 let original_ends_with_newline = snippet
2355 .rfind(|c| c != ' ')
2356 .map_or(false, |i| snippet[i..].ends_with('\n'));
2357 let snippet = snippet.trim();
2358 if !snippet.is_empty() {
2359 result.push(if original_starts_with_newline {
2364 result.push_str(snippet);
2365 if original_ends_with_newline {
2366 force_new_line_for_brace = true;
2372 let pos_before_where = match fd.output {
2373 ast::FnRetTy::Default(..) => params_span.hi(),
2374 ast::FnRetTy::Ty(ref ty) => ty.span.hi(),
2377 let is_params_multi_lined = param_str.contains('\n');
2379 let space = if put_params_in_block && ret_str.is_empty() {
2380 WhereClauseSpace::Space
2382 WhereClauseSpace::Newline
2384 let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2385 if is_params_multi_lined {
2386 option.veto_single_line();
2388 let where_clause_str = rewrite_where_clause(
2391 context.config.brace_style(),
2392 Shape::indented(indent, context.config),
2399 // If there are neither where-clause nor return type, we may be missing comments between
2401 if where_clause_str.is_empty() {
2402 if let ast::FnRetTy::Default(ret_span) = fd.output {
2403 match recover_missing_comment_in_span(
2404 mk_sp(params_span.hi(), ret_span.hi()),
2407 last_line_width(&result),
2409 Some(ref missing_comment) if !missing_comment.is_empty() => {
2410 result.push_str(missing_comment);
2411 force_new_line_for_brace = true;
2418 result.push_str(&where_clause_str);
2420 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2421 force_new_line_for_brace |= is_params_multi_lined && context.config.where_single_line();
2422 Some((result, force_new_line_for_brace))
2425 /// Kind of spaces to put before `where`.
2426 #[derive(Copy, Clone)]
2427 enum WhereClauseSpace {
2436 #[derive(Copy, Clone)]
2437 struct WhereClauseOption {
2438 suppress_comma: bool, // Force no trailing comma
2439 snuggle: WhereClauseSpace,
2440 allow_single_line: bool, // Try single line where-clause instead of vertical layout
2441 veto_single_line: bool, // Disallow a single-line where-clause.
2444 impl WhereClauseOption {
2445 fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2449 allow_single_line: false,
2450 veto_single_line: false,
2454 fn snuggled(current: &str) -> WhereClauseOption {
2456 suppress_comma: false,
2457 snuggle: if last_line_width(current) == 1 {
2458 WhereClauseSpace::Space
2460 WhereClauseSpace::Newline
2462 allow_single_line: false,
2463 veto_single_line: false,
2467 fn suppress_comma(&mut self) {
2468 self.suppress_comma = true
2471 fn allow_single_line(&mut self) {
2472 self.allow_single_line = true
2475 fn snuggle(&mut self) {
2476 self.snuggle = WhereClauseSpace::Space
2479 fn veto_single_line(&mut self) {
2480 self.veto_single_line = true;
2485 context: &RewriteContext<'_>,
2486 params: &[ast::Param],
2487 one_line_budget: usize,
2488 multi_line_budget: usize,
2490 param_indent: Indent,
2493 ) -> Option<String> {
2494 if params.is_empty() {
2495 let comment = context
2499 span.hi() - BytePos(1),
2502 return Some(comment.to_owned());
2504 let param_items: Vec<_> = itemize_list(
2505 context.snippet_provider,
2509 |param| span_lo_for_param(param),
2510 |param| param.ty.span.hi(),
2513 .rewrite(context, Shape::legacy(multi_line_budget, param_indent))
2514 .or_else(|| Some(context.snippet(param.span()).to_owned()))
2522 let tactic = definitive_tactic(
2527 .to_list_tactic(param_items.len()),
2531 let budget = match tactic {
2532 DefinitiveListTactic::Horizontal => one_line_budget,
2533 _ => multi_line_budget,
2535 let indent = match context.config.indent_style() {
2536 IndentStyle::Block => indent.block_indent(context.config),
2537 IndentStyle::Visual => param_indent,
2539 let trailing_separator = if variadic {
2540 SeparatorTactic::Never
2542 match context.config.indent_style() {
2543 IndentStyle::Block => context.config.trailing_comma(),
2544 IndentStyle::Visual => SeparatorTactic::Never,
2547 let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2549 .trailing_separator(trailing_separator)
2550 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2551 .preserve_newline(true);
2552 write_list(¶m_items, &fmt)
2555 fn compute_budgets_for_params(
2556 context: &RewriteContext<'_>,
2560 fn_brace_style: FnBraceStyle,
2561 force_vertical_layout: bool,
2562 ) -> Option<(usize, usize, Indent)> {
2564 "compute_budgets_for_params {} {:?}, {}, {:?}",
2570 // Try keeping everything on the same line.
2571 if !result.contains('\n') && !force_vertical_layout {
2572 // 2 = `()`, 3 = `() `, space is before ret_string.
2573 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2574 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2575 match fn_brace_style {
2576 FnBraceStyle::None => used_space += 1, // 1 = `;`
2577 FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2578 FnBraceStyle::NextLine => (),
2580 let one_line_budget = context.budget(used_space);
2582 if one_line_budget > 0 {
2584 let (indent, multi_line_budget) = match context.config.indent_style() {
2585 IndentStyle::Block => {
2586 let indent = indent.block_indent(context.config);
2587 (indent, context.budget(indent.width() + 1))
2589 IndentStyle::Visual => {
2590 let indent = indent + result.len() + 1;
2591 let multi_line_overhead = match fn_brace_style {
2592 FnBraceStyle::SameLine => 4,
2595 (indent, context.budget(multi_line_overhead))
2599 return Some((one_line_budget, multi_line_budget, indent));
2603 // Didn't work. we must force vertical layout and put params on a newline.
2604 let new_indent = indent.block_indent(context.config);
2605 let used_space = match context.config.indent_style() {
2607 IndentStyle::Block => new_indent.width() + 1,
2608 // Account for `)` and possibly ` {`.
2609 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2611 Some((0, context.budget(used_space), new_indent))
2614 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2615 let predicate_count = where_clause.predicates.len();
2617 if config.where_single_line() && predicate_count == 1 {
2618 return FnBraceStyle::SameLine;
2620 let brace_style = config.brace_style();
2622 let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2623 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2625 FnBraceStyle::NextLine
2627 FnBraceStyle::SameLine
2631 fn rewrite_generics(
2632 context: &RewriteContext<'_>,
2634 generics: &ast::Generics,
2636 ) -> Option<String> {
2637 // FIXME: convert bounds to where-clauses where they get too big or if
2638 // there is a where-clause at all.
2640 if generics.params.is_empty() {
2641 return Some(ident.to_owned());
2644 let params = generics.params.iter();
2645 overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2648 fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2649 match config.indent_style() {
2650 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2651 IndentStyle::Block => {
2655 .block_indent(config.tab_spaces())
2656 .with_max_width(config)
2662 fn rewrite_where_clause_rfc_style(
2663 context: &RewriteContext<'_>,
2664 where_clause: &ast::WhereClause,
2667 span_end: Option<BytePos>,
2668 span_end_before_where: BytePos,
2669 where_clause_option: WhereClauseOption,
2670 ) -> Option<String> {
2671 let (where_keyword, allow_single_line) = rewrite_where_keyword(
2675 span_end_before_where,
2676 where_clause_option,
2680 let clause_shape = shape
2682 .with_max_width(context.config)
2683 .block_left(context.config.tab_spaces())?
2685 let force_single_line = context.config.where_single_line()
2686 && where_clause.predicates.len() == 1
2687 && !where_clause_option.veto_single_line;
2689 let preds_str = rewrite_bounds_on_where_clause(
2695 where_clause_option,
2701 if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
2702 || force_single_line
2706 clause_shape.indent.to_string_with_newline(context.config)
2709 Some(format!("{}{}{}", where_keyword, clause_sep, preds_str))
2712 /// Rewrite `where` and comment around it.
2713 fn rewrite_where_keyword(
2714 context: &RewriteContext<'_>,
2715 where_clause: &ast::WhereClause,
2717 span_end_before_where: BytePos,
2718 where_clause_option: WhereClauseOption,
2719 ) -> Option<(String, bool)> {
2720 let block_shape = shape.block().with_max_width(context.config);
2722 let clause_shape = block_shape
2723 .block_left(context.config.tab_spaces())?
2726 let comment_separator = |comment: &str, shape: Shape| {
2727 if comment.is_empty() {
2730 shape.indent.to_string_with_newline(context.config)
2734 let (span_before, span_after) =
2735 missing_span_before_after_where(span_end_before_where, where_clause);
2736 let (comment_before, comment_after) =
2737 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2739 let starting_newline = match where_clause_option.snuggle {
2740 WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
2741 WhereClauseSpace::None => Cow::from(""),
2742 _ => block_shape.indent.to_string_with_newline(context.config),
2745 let newline_before_where = comment_separator(&comment_before, shape);
2746 let newline_after_where = comment_separator(&comment_after, clause_shape);
2747 let result = format!(
2749 starting_newline, comment_before, newline_before_where, newline_after_where, comment_after
2751 let allow_single_line = where_clause_option.allow_single_line
2752 && comment_before.is_empty()
2753 && comment_after.is_empty();
2755 Some((result, allow_single_line))
2758 /// Rewrite bounds on a where clause.
2759 fn rewrite_bounds_on_where_clause(
2760 context: &RewriteContext<'_>,
2761 where_clause: &ast::WhereClause,
2764 span_end: Option<BytePos>,
2765 where_clause_option: WhereClauseOption,
2766 force_single_line: bool,
2767 ) -> Option<String> {
2768 let span_start = where_clause.predicates[0].span().lo();
2769 // If we don't have the start of the next span, then use the end of the
2770 // predicates, but that means we miss comments.
2771 let len = where_clause.predicates.len();
2772 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2773 let span_end = span_end.unwrap_or(end_of_preds);
2774 let items = itemize_list(
2775 context.snippet_provider,
2776 where_clause.predicates.iter(),
2779 |pred| pred.span().lo(),
2780 |pred| pred.span().hi(),
2781 |pred| pred.rewrite(context, shape),
2786 let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
2787 SeparatorTactic::Never
2789 context.config.trailing_comma()
2792 // shape should be vertical only and only if we have `force_single_line` option enabled
2793 // and the number of items of the where-clause is equal to 1
2794 let shape_tactic = if force_single_line {
2795 DefinitiveListTactic::Horizontal
2797 DefinitiveListTactic::Vertical
2800 let fmt = ListFormatting::new(shape, context.config)
2801 .tactic(shape_tactic)
2802 .trailing_separator(comma_tactic)
2803 .preserve_newline(true);
2804 write_list(&items.collect::<Vec<_>>(), &fmt)
2807 fn rewrite_where_clause(
2808 context: &RewriteContext<'_>,
2809 where_clause: &ast::WhereClause,
2810 brace_style: BraceStyle,
2814 span_end: Option<BytePos>,
2815 span_end_before_where: BytePos,
2816 where_clause_option: WhereClauseOption,
2817 ) -> Option<String> {
2818 if where_clause.predicates.is_empty() {
2819 return Some(String::new());
2822 if context.config.indent_style() == IndentStyle::Block {
2823 return rewrite_where_clause_rfc_style(
2829 span_end_before_where,
2830 where_clause_option,
2834 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2836 let offset = match context.config.indent_style() {
2837 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2838 // 6 = "where ".len()
2839 IndentStyle::Visual => shape.indent + extra_indent + 6,
2841 // FIXME: if indent_style != Visual, then the budgets below might
2842 // be out by a char or two.
2844 let budget = context.config.max_width() - offset.width();
2845 let span_start = where_clause.predicates[0].span().lo();
2846 // If we don't have the start of the next span, then use the end of the
2847 // predicates, but that means we miss comments.
2848 let len = where_clause.predicates.len();
2849 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2850 let span_end = span_end.unwrap_or(end_of_preds);
2851 let items = itemize_list(
2852 context.snippet_provider,
2853 where_clause.predicates.iter(),
2856 |pred| pred.span().lo(),
2857 |pred| pred.span().hi(),
2858 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2863 let item_vec = items.collect::<Vec<_>>();
2864 // FIXME: we don't need to collect here
2865 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2867 let mut comma_tactic = context.config.trailing_comma();
2868 // Kind of a hack because we don't usually have trailing commas in where-clauses.
2869 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2870 comma_tactic = SeparatorTactic::Never;
2873 let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
2875 .trailing_separator(comma_tactic)
2876 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2877 .preserve_newline(true);
2878 let preds_str = write_list(&item_vec, &fmt)?;
2880 let end_length = if terminator == "{" {
2881 // If the brace is on the next line we don't need to count it otherwise it needs two
2884 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2885 BraceStyle::PreferSameLine => 2,
2887 } else if terminator == "=" {
2893 || preds_str.contains('\n')
2894 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2898 (shape.indent + extra_indent).to_string(context.config),
2902 Some(format!(" where {}", preds_str))
2906 fn missing_span_before_after_where(
2907 before_item_span_end: BytePos,
2908 where_clause: &ast::WhereClause,
2910 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2912 let pos_after_where = where_clause.span.lo() + BytePos(5);
2913 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2914 (missing_span_before, missing_span_after)
2917 fn rewrite_comments_before_after_where(
2918 context: &RewriteContext<'_>,
2919 span_before_where: Span,
2920 span_after_where: Span,
2922 ) -> Option<(String, String)> {
2923 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2924 let after_comment = rewrite_missing_comment(
2926 shape.block_indent(context.config.tab_spaces()),
2929 Some((before_comment, after_comment))
2933 context: &RewriteContext<'_>,
2935 ident: symbol::Ident,
2936 vis: &ast::Visibility,
2940 format_visibility(context, vis),
2942 rewrite_ident(context, ident)
2946 #[derive(PartialEq, Eq, Clone, Copy)]
2954 context: &RewriteContext<'_>,
2955 generics: &ast::Generics,
2956 brace_style: BraceStyle,
2957 brace_pos: BracePos,
2961 ) -> Option<String> {
2962 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2963 let mut result = rewrite_generics(context, "", generics, shape)?;
2965 // If the generics are not parameterized then generics.span.hi() == 0,
2966 // so we use span.lo(), which is the position after `struct Foo`.
2967 let span_end_before_where = if !generics.params.is_empty() {
2972 let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
2973 let budget = context.budget(last_line_used_width(&result, offset.width()));
2974 let mut option = WhereClauseOption::snuggled(&result);
2975 if brace_pos == BracePos::None {
2976 option.suppress_comma = true;
2978 let where_clause_str = rewrite_where_clause(
2980 &generics.where_clause,
2982 Shape::legacy(budget, offset.block_only()),
2986 span_end_before_where,
2989 result.push_str(&where_clause_str);
2991 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
2992 // missed comments are taken care of in #rewrite_where_clause
2997 brace_pos == BracePos::ForceSameLine
2998 || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
2999 || brace_style != BraceStyle::AlwaysNextLine)
3000 || trimmed_last_line_width(&result) == 1,
3001 rewrite_missing_comment(
3003 span_end_before_where,
3004 if brace_pos == BracePos::None {
3007 context.snippet_provider.span_before(span, "{")
3015 // add missing comments
3016 let missed_line_comments = missed_comments
3017 .filter(|missed_comments| !missed_comments.is_empty())
3018 .map_or(false, |missed_comments| {
3019 let is_block = is_last_comment_block(&missed_comments);
3020 let sep = if is_block { " " } else { "\n" };
3021 result.push_str(sep);
3022 result.push_str(&missed_comments);
3025 if brace_pos == BracePos::None {
3026 return Some(result);
3028 let total_used_width = last_line_used_width(&result, used_width);
3029 let remaining_budget = context.budget(total_used_width);
3030 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
3031 // and hence we take the closer into account as well for one line budget.
3032 // We assume that the closer has the same length as the opener.
3033 let overhead = if brace_pos == BracePos::ForceSameLine {
3040 let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
3041 if !forbid_same_line_brace && same_line_brace {
3045 result.push_str(&offset.block_only().to_string(context.config));
3052 impl Rewrite for ast::ForeignItem {
3053 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
3054 let attrs_str = self.attrs.rewrite(context, shape)?;
3055 // Drop semicolon or it will be interpreted as comment.
3056 // FIXME: this may be a faulty span from libsyntax.
3057 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
3059 let item_str = match self.kind {
3060 ast::ForeignItemKind::Fn(_, ref fn_sig, ref generics, _) => rewrite_fn_base(
3064 &FnSig::new(&fn_sig.decl, generics, self.vis.clone()),
3068 .map(|(s, _)| format!("{};", s)),
3069 ast::ForeignItemKind::Static(ref ty, mutability, _) => {
3070 // FIXME(#21): we're dropping potential comments in between the
3071 // function kw here.
3072 let vis = format_visibility(context, &self.vis);
3073 let mut_str = format_mutability(mutability);
3074 let prefix = format!(
3078 rewrite_ident(context, self.ident)
3081 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
3083 ast::ForeignItemKind::TyAlias(
3088 ) => rewrite_type_alias(
3090 type_default.as_ref(),
3092 Some(generic_bounds),
3097 ast::ForeignItemKind::MacCall(ref mac) => {
3098 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
3102 let missing_span = if self.attrs.is_empty() {
3103 mk_sp(self.span.lo(), self.span.lo())
3105 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
3107 combine_strs_with_missing_comments(
3118 /// Rewrite the attributes of an item.
3120 context: &RewriteContext<'_>,
3124 ) -> Option<String> {
3125 let attrs = filter_inline_attrs(&item.attrs, item.span());
3126 let attrs_str = attrs.rewrite(context, shape)?;
3128 let missed_span = if attrs.is_empty() {
3129 mk_sp(item.span.lo(), item.span.lo())
3131 mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
3134 let allow_extend = if attrs.len() == 1 {
3135 let line_len = attrs_str.len() + 1 + item_str.len();
3136 !attrs.first().unwrap().is_doc_comment()
3137 && context.config.inline_attribute_width() >= line_len
3142 combine_strs_with_missing_comments(
3152 /// Rewrite an inline mod.
3153 /// The given shape is used to format the mod's attributes.
3154 pub(crate) fn rewrite_mod(
3155 context: &RewriteContext<'_>,
3158 ) -> Option<String> {
3159 let mut result = String::with_capacity(32);
3160 result.push_str(&*format_visibility(context, &item.vis));
3161 result.push_str("mod ");
3162 result.push_str(rewrite_ident(context, item.ident));
3164 rewrite_attrs(context, item, &result, attrs_shape)
3167 /// Rewrite `extern crate foo;`.
3168 /// The given shape is used to format the extern crate's attributes.
3169 pub(crate) fn rewrite_extern_crate(
3170 context: &RewriteContext<'_>,
3173 ) -> Option<String> {
3174 assert!(is_extern_crate(item));
3175 let new_str = context.snippet(item.span);
3176 let item_str = if contains_comment(new_str) {
3179 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3180 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3182 rewrite_attrs(context, item, &item_str, attrs_shape)
3185 /// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3186 pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3188 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
3193 pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3195 ast::ItemKind::Use(_) => true,
3200 pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3202 ast::ItemKind::ExternCrate(..) => true,