1 // Formatting top-level items - functions, structs, enums, traits, impls.
4 use std::cmp::{min, Ordering};
7 use rustc_target::spec::abi;
8 use syntax::source_map::{self, BytePos, Span};
10 use syntax::{ast, ptr, symbol};
12 use crate::attr::filter_inline_attrs;
14 combine_strs_with_missing_comments, contains_comment, is_last_comment_block,
15 recover_comment_removed, recover_missing_comment_in_span, rewrite_missing_comment,
18 use crate::config::lists::*;
19 use crate::config::{BraceStyle, Config, IndentStyle, Version};
21 is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with, 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 = source_map::Spanned {
36 node: ast::VisibilityKind::Inherited,
37 span: source_map::DUMMY_SP,
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 keyword: &'static str,
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> {
140 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
145 .map(|i| BodyElement::ForeignItem(i))
152 enum BodyElement<'a> {
153 // Stmt(&'a ast::Stmt),
154 // Field(&'a ast::Field),
155 // Variant(&'a ast::Variant),
156 // Item(&'a ast::Item),
157 ForeignItem(&'a ast::ForeignItem),
160 /// Represents a fn's signature.
161 pub(crate) struct FnSig<'a> {
162 decl: &'a ast::FnDecl,
163 generics: &'a ast::Generics,
165 is_async: Cow<'a, ast::IsAsync>,
166 constness: ast::Constness,
167 defaultness: ast::Defaultness,
168 unsafety: ast::Unsafety,
169 visibility: ast::Visibility,
174 decl: &'a ast::FnDecl,
175 generics: &'a ast::Generics,
176 vis: ast::Visibility,
182 is_async: Cow::Owned(ast::IsAsync::NotAsync),
183 constness: ast::Constness::NotConst,
184 defaultness: ast::Defaultness::Final,
185 unsafety: ast::Unsafety::Normal,
190 pub(crate) fn from_method_sig(
191 method_sig: &'a ast::MethodSig,
192 generics: &'a ast::Generics,
195 unsafety: method_sig.header.unsafety,
196 is_async: Cow::Borrowed(&method_sig.header.asyncness.node),
197 constness: method_sig.header.constness.node,
198 defaultness: ast::Defaultness::Final,
199 abi: method_sig.header.abi,
200 decl: &*method_sig.decl,
202 visibility: DEFAULT_VISIBILITY,
206 pub(crate) fn from_fn_kind(
207 fn_kind: &'a visit::FnKind<'_>,
208 generics: &'a ast::Generics,
209 decl: &'a ast::FnDecl,
210 defaultness: ast::Defaultness,
213 visit::FnKind::ItemFn(_, fn_header, visibility, _) => FnSig {
217 constness: fn_header.constness.node,
218 is_async: Cow::Borrowed(&fn_header.asyncness.node),
220 unsafety: fn_header.unsafety,
221 visibility: visibility.clone(),
223 visit::FnKind::Method(_, method_sig, vis, _) => {
224 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
225 fn_sig.defaultness = defaultness;
226 if let Some(vis) = vis {
227 fn_sig.visibility = vis.clone();
235 fn to_str(&self, context: &RewriteContext<'_>) -> String {
236 let mut result = String::with_capacity(128);
237 // Vis defaultness constness unsafety abi.
238 result.push_str(&*format_visibility(context, &self.visibility));
239 result.push_str(format_defaultness(self.defaultness));
240 result.push_str(format_constness(self.constness));
241 result.push_str(format_async(&self.is_async));
242 result.push_str(format_unsafety(self.unsafety));
243 result.push_str(&format_abi(
245 context.config.force_explicit_abi(),
252 impl<'a> FmtVisitor<'a> {
253 fn format_item(&mut self, item: &Item<'_>) {
254 self.buffer.push_str(&item.abi);
256 let snippet = self.snippet(item.span);
257 let brace_pos = snippet.find_uncommented("{").unwrap();
260 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
261 // FIXME: this skips comments between the extern keyword and the opening
263 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
264 self.block_indent = self.block_indent.block_indent(self.config);
266 if item.body.is_empty() {
267 self.format_missing_no_indent(item.span.hi() - BytePos(1));
268 self.block_indent = self.block_indent.block_unindent(self.config);
269 let indent_str = self.block_indent.to_string(self.config);
270 self.push_str(&indent_str);
272 for item in &item.body {
273 self.format_body_element(item);
276 self.block_indent = self.block_indent.block_unindent(self.config);
277 self.format_missing_with_indent(item.span.hi() - BytePos(1));
282 self.last_pos = item.span.hi();
285 fn format_body_element(&mut self, element: &BodyElement<'_>) {
287 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
291 pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
292 let item = Item::from_foreign_mod(fm, span, self.config);
293 self.format_item(&item);
296 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
297 let rewrite = item.rewrite(&self.get_context(), self.shape());
298 self.push_rewrite(item.span(), rewrite);
299 self.last_pos = item.span.hi();
302 pub(crate) fn rewrite_fn_before_block(
308 ) -> Option<(String, FnBraceStyle)> {
309 let context = self.get_context();
311 let mut fn_brace_style = newline_for_brace(self.config, &fn_sig.generics.where_clause);
312 let (result, force_newline_brace) =
313 rewrite_fn_base(&context, indent, ident, fn_sig, span, fn_brace_style)?;
316 if self.config.brace_style() == BraceStyle::AlwaysNextLine
317 || force_newline_brace
318 || last_line_width(&result) + 2 > self.shape().width
320 fn_brace_style = FnBraceStyle::NextLine
323 Some((result, fn_brace_style))
326 pub(crate) fn rewrite_required_fn(
330 sig: &ast::MethodSig,
331 generics: &ast::Generics,
333 ) -> Option<String> {
334 // Drop semicolon or it will be interpreted as comment.
335 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
336 let context = self.get_context();
338 let (mut result, _) = rewrite_fn_base(
342 &FnSig::from_method_sig(sig, generics),
347 // Re-attach semicolon
353 pub(crate) fn single_line_fn(
357 inner_attrs: Option<&[ast::Attribute]>,
358 ) -> Option<String> {
359 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
363 let source_map = self.get_context().source_map;
365 if self.config.empty_item_single_line()
366 && is_empty_block(block, None, source_map)
367 && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width()
368 && !last_line_contains_single_line_comment(fn_str)
370 return Some(format!("{} {{}}", fn_str));
373 if !self.config.fn_single_line() || !is_simple_block_stmt(block, None, source_map) {
377 let res = Stmt::from_ast_node(block.stmts.first()?, true)
378 .rewrite(&self.get_context(), self.shape())?;
380 let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
381 if !res.contains('\n') && width <= self.config.max_width() {
382 Some(format!("{} {{ {} }}", fn_str, res))
388 pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) {
389 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
390 self.push_rewrite(static_parts.span, rewrite);
393 pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) {
394 let is_tuple = match struct_parts.def {
395 ast::VariantData::Tuple(..) => true,
398 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
399 .map(|s| if is_tuple { s + ";" } else { s });
400 self.push_rewrite(struct_parts.span, rewrite);
403 pub(crate) fn visit_enum(
406 vis: &ast::Visibility,
407 enum_def: &ast::EnumDef,
408 generics: &ast::Generics,
411 let enum_header = format_header(&self.get_context(), "enum ", ident, vis);
412 self.push_str(&enum_header);
414 let enum_snippet = self.snippet(span);
415 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
416 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
417 let generics_str = format_generics(
420 self.config.brace_style(),
421 if enum_def.variants.is_empty() {
422 BracePos::ForceSameLine
427 // make a span that starts right after `enum Foo`
428 mk_sp(ident.span.hi(), body_start),
429 last_line_width(&enum_header),
432 self.push_str(&generics_str);
434 self.last_pos = body_start;
436 match self.format_variant_list(enum_def, body_start, span.hi()) {
437 Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
439 self.push_rewrite(mk_sp(body_start, span.hi()), rw);
440 self.block_indent = self.block_indent.block_unindent(self.config);
445 // Format the body of an enum definition
446 fn format_variant_list(
448 enum_def: &ast::EnumDef,
451 ) -> Option<String> {
452 if enum_def.variants.is_empty() {
453 let mut buffer = String::with_capacity(128);
455 let span = mk_sp(body_lo, body_hi - BytePos(1));
456 format_empty_struct_or_tuple(
466 let mut result = String::with_capacity(1024);
467 let original_offset = self.block_indent;
468 self.block_indent = self.block_indent.block_indent(self.config);
470 // If enum variants have discriminants, try to vertically align those,
471 // provided the discrims are not shifted too much to the right
472 let align_threshold: usize = self.config.enum_discrim_align_threshold();
473 let discr_ident_lens: Vec<usize> = enum_def
476 .filter(|var| var.node.disr_expr.is_some())
477 .map(|var| rewrite_ident(&self.get_context(), var.node.ident).len())
479 // cut the list at the point of longest discrim shorter than the threshold
480 // All of the discrims under the threshold will get padded, and all above - left as is.
481 let pad_discrim_ident_to = *discr_ident_lens
483 .filter(|&l| *l <= align_threshold)
487 let itemize_list_with = |one_line_width: usize| {
489 self.snippet_provider,
490 enum_def.variants.iter(),
494 if !f.node.attrs.is_empty() {
495 f.node.attrs[0].span.lo()
501 |f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
508 let mut items: Vec<_> =
509 itemize_list_with(self.config.width_heuristics().struct_variant_width);
510 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
511 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
512 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
513 if has_multiline_variant && has_single_line_variant {
514 items = itemize_list_with(0);
517 let shape = self.shape().sub_width(2)?;
518 let fmt = ListFormatting::new(shape, self.config)
519 .trailing_separator(self.config.trailing_comma())
520 .preserve_newline(true);
522 let list = write_list(&items, &fmt)?;
523 result.push_str(&list);
524 result.push_str(&original_offset.to_string_with_newline(self.config));
529 // Variant of an enum.
532 field: &ast::Variant,
533 one_line_width: usize,
534 pad_discrim_ident_to: usize,
535 ) -> Option<String> {
536 if contains_skip(&field.node.attrs) {
537 let lo = field.node.attrs[0].span.lo();
538 let span = mk_sp(lo, field.span.hi());
539 return Some(self.snippet(span).to_owned());
542 let context = self.get_context();
544 let shape = self.shape().sub_width(1)?;
545 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
550 .map_or(field.span.lo(), |attr| attr.span.hi());
551 let span = mk_sp(lo, field.span.lo());
553 let variant_body = match field.node.data {
554 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
556 &StructParts::from_variant(field),
558 Some(one_line_width),
560 ast::VariantData::Unit(..) => {
561 if let Some(ref expr) = field.node.disr_expr {
564 rewrite_ident(&context, field.node.ident),
567 rewrite_assign_rhs_with(
572 RhsTactics::AllowOverflow,
575 rewrite_ident(&context, field.node.ident).to_owned()
580 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
583 fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
584 if self.get_context().config.reorder_impl_items() {
585 // Create visitor for each items, then reorder them.
586 let mut buffer = vec![];
588 self.visit_impl_item(item);
589 buffer.push((self.buffer.clone(), item.clone()));
592 // type -> existential -> const -> macro -> method
593 use crate::ast::ImplItemKind::*;
594 fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
597 | (Const(..), Const(..))
598 | (Existential(..), Existential(..)) => false,
603 buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
605 | (Const(..), Const(..))
606 | (Macro(..), Macro(..))
607 | (Existential(..), Existential(..)) => a.ident.as_str().cmp(&b.ident.as_str()),
608 (Method(..), Method(..)) => a.span.lo().cmp(&b.span.lo()),
609 (Type(..), _) => Ordering::Less,
610 (_, Type(..)) => Ordering::Greater,
611 (Existential(..), _) => Ordering::Less,
612 (_, Existential(..)) => Ordering::Greater,
613 (Const(..), _) => Ordering::Less,
614 (_, Const(..)) => Ordering::Greater,
615 (Macro(..), _) => Ordering::Less,
616 (_, Macro(..)) => Ordering::Greater,
618 let mut prev_kind = None;
619 for (buf, item) in buffer {
620 // Make sure that there are at least a single empty line between
621 // different impl items.
624 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
628 let indent_str = self.block_indent.to_string_with_newline(self.config);
629 self.push_str(&indent_str);
630 self.push_str(buf.trim());
631 prev_kind = Some(item.node.clone());
635 self.visit_impl_item(item);
641 pub(crate) fn format_impl(
642 context: &RewriteContext<'_>,
645 ) -> Option<String> {
646 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
647 let mut result = String::with_capacity(128);
648 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
649 let sep = offset.to_string_with_newline(context.config);
650 result.push_str(&ref_and_type);
652 let where_budget = if result.contains('\n') {
653 context.config.max_width()
655 context.budget(last_line_width(&result))
658 let mut option = WhereClauseOption::snuggled(&ref_and_type);
659 let snippet = context.snippet(item.span);
660 let open_pos = snippet.find_uncommented("{")? + 1;
661 if !contains_comment(&snippet[open_pos..])
663 && generics.where_clause.predicates.len() == 1
664 && !result.contains('\n')
666 option.suppress_comma();
668 option.allow_single_line();
671 let missing_span = mk_sp(self_ty.span.hi(), item.span.hi());
672 let where_span_end = context.snippet_provider.opt_span_before(missing_span, "{");
673 let where_clause_str = rewrite_where_clause(
675 &generics.where_clause,
676 context.config.brace_style(),
677 Shape::legacy(where_budget, offset.block_only()),
685 // If there is no where-clause, we may have missing comments between the trait name and
686 // the opening brace.
687 if generics.where_clause.predicates.is_empty() {
688 if let Some(hi) = where_span_end {
689 match recover_missing_comment_in_span(
690 mk_sp(self_ty.span.hi(), hi),
691 Shape::indented(offset, context.config),
693 last_line_width(&result),
695 Some(ref missing_comment) if !missing_comment.is_empty() => {
696 result.push_str(missing_comment);
703 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
704 result.push_str(&where_clause_str);
705 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
706 // if the where_clause contains extra comments AND
707 // there is only one where-clause predicate
708 // recover the suppressed comma in single line where_clause formatting
709 if generics.where_clause.predicates.len() == 1 {
710 result.push_str(",");
712 result.push_str(&format!("{}{{{}}}", sep, sep));
714 result.push_str(" {}");
719 result.push_str(&where_clause_str);
721 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
722 match context.config.brace_style() {
723 _ if need_newline => result.push_str(&sep),
724 BraceStyle::AlwaysNextLine => result.push_str(&sep),
725 BraceStyle::PreferSameLine => result.push(' '),
726 BraceStyle::SameLineWhere => {
727 if !where_clause_str.is_empty() {
728 result.push_str(&sep);
736 // this is an impl body snippet(impl SampleImple { /* here */ })
737 let snippet = context.snippet(mk_sp(item.span.hi(), self_ty.span.hi()));
738 let open_pos = snippet.find_uncommented("{")? + 1;
740 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
741 let mut visitor = FmtVisitor::from_context(context);
742 let item_indent = offset.block_only().block_indent(context.config);
743 visitor.block_indent = item_indent;
744 visitor.last_pos = self_ty.span.hi() + BytePos(open_pos as u32);
746 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
747 visitor.visit_impl_items(items);
749 visitor.format_missing(item.span.hi() - BytePos(1));
751 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
752 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
754 result.push_str(&inner_indent_str);
755 result.push_str(visitor.buffer.trim());
756 result.push_str(&outer_indent_str);
757 } else if need_newline || !context.config.empty_item_single_line() {
758 result.push_str(&sep);
769 fn is_impl_single_line(
770 context: &RewriteContext<'_>,
771 items: &[ast::ImplItem],
773 where_clause_str: &str,
776 let snippet = context.snippet(item.span);
777 let open_pos = snippet.find_uncommented("{")? + 1;
780 context.config.empty_item_single_line()
782 && !result.contains('\n')
783 && result.len() + where_clause_str.len() <= context.config.max_width()
784 && !contains_comment(&snippet[open_pos..]),
788 fn format_impl_ref_and_type(
789 context: &RewriteContext<'_>,
792 ) -> Option<String> {
793 if let ast::ItemKind::Impl(
803 let mut result = String::with_capacity(128);
805 result.push_str(&format_visibility(context, &item.vis));
806 result.push_str(format_defaultness(defaultness));
807 result.push_str(format_unsafety(unsafety));
809 let shape = generics_shape_from_config(
811 Shape::indented(offset + last_line_width(&result), context.config),
814 let generics_str = rewrite_generics(context, "impl", generics, shape)?;
815 result.push_str(&generics_str);
817 let polarity_str = if polarity == ast::ImplPolarity::Negative {
823 if let Some(ref trait_ref) = *trait_ref {
824 let result_len = last_line_width(&result);
825 result.push_str(&rewrite_trait_ref(
834 // Try to put the self type in a single line.
836 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
837 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
838 // If there is no where-clause adapt budget for type formatting to take space and curly
839 // brace into account.
840 match context.config.brace_style() {
841 BraceStyle::AlwaysNextLine => 0,
847 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
848 // 1 = space before the type.
849 let budget = context.budget(used_space + 1);
850 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
851 if !self_ty_str.contains('\n') {
852 if trait_ref.is_some() {
853 result.push_str(" for ");
857 result.push_str(&self_ty_str);
862 // Couldn't fit the self type on a single line, put it on a new line.
864 // Add indentation of one additional tab.
865 let new_line_offset = offset.block_indent(context.config);
866 result.push_str(&new_line_offset.to_string(context.config));
867 if trait_ref.is_some() {
868 result.push_str("for ");
870 let budget = context.budget(last_line_width(&result));
871 let type_offset = match context.config.indent_style() {
872 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
873 IndentStyle::Block => new_line_offset,
875 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
882 fn rewrite_trait_ref(
883 context: &RewriteContext<'_>,
884 trait_ref: &ast::TraitRef,
888 ) -> Option<String> {
889 // 1 = space between generics and trait_ref
890 let used_space = 1 + polarity_str.len() + result_len;
891 let shape = Shape::indented(offset + used_space, context.config);
892 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
893 if !trait_ref_str.contains('\n') {
894 return Some(format!(" {}{}", polarity_str, trait_ref_str));
897 // We could not make enough space for trait_ref, so put it on new line.
898 let offset = offset.block_indent(context.config);
899 let shape = Shape::indented(offset, context.config);
900 let trait_ref_str = trait_ref.rewrite(context, shape)?;
903 offset.to_string_with_newline(context.config),
909 pub(crate) struct StructParts<'a> {
912 vis: &'a ast::Visibility,
913 def: &'a ast::VariantData,
914 generics: Option<&'a ast::Generics>,
918 impl<'a> StructParts<'a> {
919 fn format_header(&self, context: &RewriteContext<'_>) -> String {
920 format_header(context, self.prefix, self.ident, self.vis)
923 fn from_variant(variant: &'a ast::Variant) -> Self {
926 ident: variant.node.ident,
927 vis: &DEFAULT_VISIBILITY,
928 def: &variant.node.data,
934 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
935 let (prefix, def, generics) = match item.node {
936 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
937 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
945 generics: Some(generics),
952 context: &RewriteContext<'_>,
953 struct_parts: &StructParts<'_>,
955 one_line_width: Option<usize>,
956 ) -> Option<String> {
957 match *struct_parts.def {
958 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
959 ast::VariantData::Tuple(ref fields, _) => {
960 format_tuple_struct(context, struct_parts, fields, offset)
962 ast::VariantData::Struct(ref fields, _) => {
963 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
968 pub(crate) fn format_trait(
969 context: &RewriteContext<'_>,
972 ) -> Option<String> {
973 if let ast::ItemKind::Trait(
981 let mut result = String::with_capacity(128);
982 let header = format!(
984 format_visibility(context, &item.vis),
985 format_unsafety(unsafety),
986 format_auto(is_auto),
988 result.push_str(&header);
990 let body_lo = context.snippet_provider.span_after(item.span, "{");
992 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
994 rewrite_generics(context, rewrite_ident(context, item.ident), generics, shape)?;
995 result.push_str(&generics_str);
997 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
998 if !generic_bounds.is_empty() {
999 let ident_hi = context
1001 .span_after(item.span, &item.ident.as_str());
1002 let bound_hi = generic_bounds.last().unwrap().span().hi();
1003 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1004 if contains_comment(snippet) {
1008 result = rewrite_assign_rhs_with(
1013 RhsTactics::ForceNextLineWithoutIndent,
1017 // Rewrite where-clause.
1018 if !generics.where_clause.predicates.is_empty() {
1019 let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
1021 let where_budget = context.budget(last_line_width(&result));
1022 let pos_before_where = if generic_bounds.is_empty() {
1023 generics.where_clause.span.lo()
1025 generic_bounds[generic_bounds.len() - 1].span().hi()
1027 let option = WhereClauseOption::snuggled(&generics_str);
1028 let where_clause_str = rewrite_where_clause(
1030 &generics.where_clause,
1031 context.config.brace_style(),
1032 Shape::legacy(where_budget, offset.block_only()),
1039 // If the where-clause cannot fit on the same line,
1040 // put the where-clause on a new line
1041 if !where_clause_str.contains('\n')
1042 && last_line_width(&result) + where_clause_str.len() + offset.width()
1043 > context.config.comment_width()
1045 let width = offset.block_indent + context.config.tab_spaces() - 1;
1046 let where_indent = Indent::new(0, width);
1047 result.push_str(&where_indent.to_string_with_newline(context.config));
1049 result.push_str(&where_clause_str);
1051 let item_snippet = context.snippet(item.span);
1052 if let Some(lo) = item_snippet.find('/') {
1054 let comment_hi = body_lo - BytePos(1);
1055 let comment_lo = item.span.lo() + BytePos(lo as u32);
1056 if comment_lo < comment_hi {
1057 match recover_missing_comment_in_span(
1058 mk_sp(comment_lo, comment_hi),
1059 Shape::indented(offset, context.config),
1061 last_line_width(&result),
1063 Some(ref missing_comment) if !missing_comment.is_empty() => {
1064 result.push_str(missing_comment);
1072 match context.config.brace_style() {
1073 _ if last_line_contains_single_line_comment(&result)
1074 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1076 result.push_str(&offset.to_string_with_newline(context.config));
1078 BraceStyle::AlwaysNextLine => {
1079 result.push_str(&offset.to_string_with_newline(context.config));
1081 BraceStyle::PreferSameLine => result.push(' '),
1082 BraceStyle::SameLineWhere => {
1083 if result.contains('\n')
1084 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1086 result.push_str(&offset.to_string_with_newline(context.config));
1094 let snippet = context.snippet(item.span);
1095 let open_pos = snippet.find_uncommented("{")? + 1;
1096 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1098 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1099 let mut visitor = FmtVisitor::from_context(context);
1100 visitor.block_indent = offset.block_only().block_indent(context.config);
1101 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1103 for item in trait_items {
1104 visitor.visit_trait_item(item);
1107 visitor.format_missing(item.span.hi() - BytePos(1));
1109 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1111 result.push_str(&inner_indent_str);
1112 result.push_str(visitor.buffer.trim());
1113 result.push_str(&outer_indent_str);
1114 } else if result.contains('\n') {
1115 result.push_str(&outer_indent_str);
1125 pub(crate) struct TraitAliasBounds<'a> {
1126 generic_bounds: &'a ast::GenericBounds,
1127 generics: &'a ast::Generics,
1130 impl<'a> Rewrite for TraitAliasBounds<'a> {
1131 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1132 let generic_bounds_str = self.generic_bounds.rewrite(context, shape)?;
1134 let mut option = WhereClauseOption::new(true, WhereClauseSpace::None);
1135 option.allow_single_line();
1137 let where_str = rewrite_where_clause(
1139 &self.generics.where_clause,
1140 context.config.brace_style(),
1145 self.generics.where_clause.span.lo(),
1149 let fits_single_line = !generic_bounds_str.contains('\n')
1150 && !where_str.contains('\n')
1151 && generic_bounds_str.len() + where_str.len() + 1 <= shape.width;
1152 let space = if generic_bounds_str.is_empty() || where_str.is_empty() {
1154 } else if fits_single_line {
1157 shape.indent.to_string_with_newline(&context.config)
1160 Some(format!("{}{}{}", generic_bounds_str, space, where_str))
1164 pub(crate) fn format_trait_alias(
1165 context: &RewriteContext<'_>,
1167 vis: &ast::Visibility,
1168 generics: &ast::Generics,
1169 generic_bounds: &ast::GenericBounds,
1171 ) -> Option<String> {
1172 let alias = rewrite_ident(context, ident);
1173 // 6 = "trait ", 2 = " ="
1174 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1175 let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
1176 let vis_str = format_visibility(context, vis);
1177 let lhs = format!("{}trait {} =", vis_str, generics_str);
1179 let trait_alias_bounds = TraitAliasBounds {
1183 rewrite_assign_rhs(context, lhs, &trait_alias_bounds, shape.sub_width(1)?).map(|s| s + ";")
1186 fn format_unit_struct(
1187 context: &RewriteContext<'_>,
1188 p: &StructParts<'_>,
1190 ) -> Option<String> {
1191 let header_str = format_header(context, p.prefix, p.ident, p.vis);
1192 let generics_str = if let Some(generics) = p.generics {
1193 let hi = context.snippet_provider.span_before(p.span, ";");
1197 context.config.brace_style(),
1200 // make a span that starts right after `struct Foo`
1201 mk_sp(p.ident.span.hi(), hi),
1202 last_line_width(&header_str),
1207 Some(format!("{}{};", header_str, generics_str))
1210 pub(crate) fn format_struct_struct(
1211 context: &RewriteContext<'_>,
1212 struct_parts: &StructParts<'_>,
1213 fields: &[ast::StructField],
1215 one_line_width: Option<usize>,
1216 ) -> Option<String> {
1217 let mut result = String::with_capacity(1024);
1218 let span = struct_parts.span;
1220 let header_str = struct_parts.format_header(context);
1221 result.push_str(&header_str);
1223 let header_hi = struct_parts.ident.span.hi();
1224 let body_lo = context.snippet_provider.span_after(span, "{");
1226 let generics_str = match struct_parts.generics {
1227 Some(g) => format_generics(
1230 context.config.brace_style(),
1231 if fields.is_empty() {
1232 BracePos::ForceSameLine
1237 // make a span that starts right after `struct Foo`
1238 mk_sp(header_hi, body_lo),
1239 last_line_width(&result),
1242 // 3 = ` {}`, 2 = ` {`.
1243 let overhead = if fields.is_empty() { 3 } else { 2 };
1244 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1245 || context.config.max_width() < overhead + result.len()
1247 format!("\n{}{{", offset.block_only().to_string(context.config))
1254 let overhead = if fields.is_empty() { 1 } else { 0 };
1255 let total_width = result.len() + generics_str.len() + overhead;
1256 if !generics_str.is_empty()
1257 && !generics_str.contains('\n')
1258 && total_width > context.config.max_width()
1261 result.push_str(&offset.to_string(context.config));
1262 result.push_str(generics_str.trim_start());
1264 result.push_str(&generics_str);
1267 if fields.is_empty() {
1268 let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1269 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1270 return Some(result);
1274 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1275 let one_line_budget =
1276 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1278 let items_str = rewrite_with_alignment(
1281 Shape::indented(offset.block_indent(context.config), context.config).sub_width(1)?,
1282 mk_sp(body_lo, span.hi()),
1286 if !items_str.contains('\n')
1287 && !result.contains('\n')
1288 && items_str.len() <= one_line_budget
1289 && !last_line_contains_single_line_comment(&items_str)
1291 Some(format!("{} {} }}", result, items_str))
1297 .block_indent(context.config)
1298 .to_string(context.config),
1300 offset.to_string(context.config)
1305 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1307 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1308 _ => default_span.lo(),
1312 // Format tuple or struct without any fields. We need to make sure that the comments
1313 // inside the delimiters are preserved.
1314 fn format_empty_struct_or_tuple(
1315 context: &RewriteContext<'_>,
1318 result: &mut String,
1322 // 3 = " {}" or "();"
1323 let used_width = last_line_used_width(&result, offset.width()) + 3;
1324 if used_width > context.config.max_width() {
1325 result.push_str(&offset.to_string_with_newline(context.config))
1327 result.push_str(opener);
1328 match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1329 Some(ref s) if s.is_empty() => (),
1331 if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1332 let nested_indent_str = offset
1333 .block_indent(context.config)
1334 .to_string_with_newline(context.config);
1335 result.push_str(&nested_indent_str);
1338 if last_line_contains_single_line_comment(s) {
1339 result.push_str(&offset.to_string_with_newline(context.config));
1342 None => result.push_str(context.snippet(span)),
1344 result.push_str(closer);
1347 fn format_tuple_struct(
1348 context: &RewriteContext<'_>,
1349 struct_parts: &StructParts<'_>,
1350 fields: &[ast::StructField],
1352 ) -> Option<String> {
1353 let mut result = String::with_capacity(1024);
1354 let span = struct_parts.span;
1356 let header_str = struct_parts.format_header(context);
1357 result.push_str(&header_str);
1359 let body_lo = if fields.is_empty() {
1360 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1363 .span_after(mk_sp(lo, span.hi()), "(")
1367 let body_hi = if fields.is_empty() {
1370 .span_after(mk_sp(body_lo, span.hi()), ")")
1372 // This is a dirty hack to work around a missing `)` from the span of the last field.
1373 let last_arg_span = fields[fields.len() - 1].span;
1376 .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1377 .unwrap_or_else(|| last_arg_span.hi())
1380 let where_clause_str = match struct_parts.generics {
1382 let budget = context.budget(last_line_width(&header_str));
1383 let shape = Shape::legacy(budget, offset);
1384 let generics_str = rewrite_generics(context, "", generics, shape)?;
1385 result.push_str(&generics_str);
1387 let where_budget = context.budget(last_line_width(&result));
1388 let option = WhereClauseOption::new(true, WhereClauseSpace::Newline);
1389 rewrite_where_clause(
1391 &generics.where_clause,
1392 context.config.brace_style(),
1393 Shape::legacy(where_budget, offset.block_only()),
1401 None => "".to_owned(),
1404 if fields.is_empty() {
1405 let body_hi = context
1407 .span_before(mk_sp(body_lo, span.hi()), ")");
1408 let inner_span = mk_sp(body_lo, body_hi);
1409 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1411 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1412 result = overflow::rewrite_with_parens(
1418 context.config.width_heuristics().fn_call_width,
1423 if !where_clause_str.is_empty()
1424 && !where_clause_str.contains('\n')
1425 && (result.contains('\n')
1426 || offset.block_indent + result.len() + where_clause_str.len() + 1
1427 > context.config.max_width())
1429 // We need to put the where-clause on a new line, but we didn't
1430 // know that earlier, so the where-clause will not be indented properly.
1433 &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1436 result.push_str(&where_clause_str);
1441 fn rewrite_type_prefix(
1442 context: &RewriteContext<'_>,
1446 generics: &ast::Generics,
1447 ) -> Option<String> {
1448 let mut result = String::with_capacity(128);
1449 result.push_str(prefix);
1450 let ident_str = rewrite_ident(context, ident);
1453 if generics.params.is_empty() {
1454 result.push_str(ident_str)
1456 let g_shape = Shape::indented(indent, context.config)
1457 .offset_left(result.len())?
1459 let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1460 result.push_str(&generics_str);
1463 let where_budget = context.budget(last_line_width(&result));
1464 let option = WhereClauseOption::snuggled(&result);
1465 let where_clause_str = rewrite_where_clause(
1467 &generics.where_clause,
1468 context.config.brace_style(),
1469 Shape::legacy(where_budget, indent),
1476 result.push_str(&where_clause_str);
1481 fn rewrite_type_item<R: Rewrite>(
1482 context: &RewriteContext<'_>,
1488 generics: &ast::Generics,
1489 vis: &ast::Visibility,
1490 ) -> Option<String> {
1491 let mut result = String::with_capacity(128);
1492 result.push_str(&rewrite_type_prefix(
1495 &format!("{}{} ", format_visibility(context, vis), prefix),
1500 if generics.where_clause.predicates.is_empty() {
1501 result.push_str(suffix);
1503 result.push_str(&indent.to_string_with_newline(context.config));
1504 result.push_str(suffix.trim_start());
1508 let rhs_shape = Shape::indented(indent, context.config).sub_width(1)?;
1509 rewrite_assign_rhs(context, result, rhs, rhs_shape).map(|s| s + ";")
1512 pub(crate) fn rewrite_type_alias(
1513 context: &RewriteContext<'_>,
1517 generics: &ast::Generics,
1518 vis: &ast::Visibility,
1519 ) -> Option<String> {
1520 rewrite_type_item(context, indent, "type", " =", ident, ty, generics, vis)
1523 pub(crate) fn rewrite_existential_type(
1524 context: &RewriteContext<'_>,
1527 generic_bounds: &ast::GenericBounds,
1528 generics: &ast::Generics,
1529 vis: &ast::Visibility,
1530 ) -> Option<String> {
1543 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1545 if config.space_before_colon() { " " } else { "" },
1546 if config.space_after_colon() { " " } else { "" },
1550 pub(crate) fn rewrite_struct_field_prefix(
1551 context: &RewriteContext<'_>,
1552 field: &ast::StructField,
1553 ) -> Option<String> {
1554 let vis = format_visibility(context, &field.vis);
1555 let type_annotation_spacing = type_annotation_spacing(context.config);
1556 Some(match field.ident {
1557 Some(name) => format!(
1560 rewrite_ident(context, name),
1561 type_annotation_spacing.0
1563 None => vis.to_string(),
1567 impl Rewrite for ast::StructField {
1568 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1569 rewrite_struct_field(context, self, shape, 0)
1573 pub(crate) fn rewrite_struct_field(
1574 context: &RewriteContext<'_>,
1575 field: &ast::StructField,
1577 lhs_max_width: usize,
1578 ) -> Option<String> {
1579 if contains_skip(&field.attrs) {
1580 return Some(context.snippet(field.span()).to_owned());
1583 let type_annotation_spacing = type_annotation_spacing(context.config);
1584 let prefix = rewrite_struct_field_prefix(context, field)?;
1586 let attrs_str = field.attrs.rewrite(context, shape)?;
1587 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1588 let missing_span = if field.attrs.is_empty() {
1589 mk_sp(field.span.lo(), field.span.lo())
1591 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1593 let mut spacing = String::from(if field.ident.is_some() {
1594 type_annotation_spacing.1
1598 // Try to put everything on a single line.
1599 let attr_prefix = combine_strs_with_missing_comments(
1607 let overhead = last_line_width(&attr_prefix);
1608 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1609 for _ in 0..lhs_offset {
1612 // In this extreme case we will be missing a space between an attribute and a field.
1613 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1617 .offset_left(overhead + spacing.len())
1618 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1619 if let Some(ref ty) = orig_ty {
1620 if !ty.contains('\n') {
1621 return Some(attr_prefix + &spacing + ty);
1625 let is_prefix_empty = prefix.is_empty();
1626 // We must use multiline. We are going to put attributes and a field on different lines.
1627 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1628 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1629 let field_str = if is_prefix_empty {
1630 field_str.trim_start()
1634 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1637 pub(crate) struct StaticParts<'a> {
1639 vis: &'a ast::Visibility,
1642 mutability: ast::Mutability,
1643 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1644 defaultness: Option<ast::Defaultness>,
1648 impl<'a> StaticParts<'a> {
1649 pub(crate) fn from_item(item: &'a ast::Item) -> Self {
1650 let (prefix, ty, mutability, expr) = match item.node {
1651 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1652 ast::ItemKind::Const(ref ty, ref expr) => {
1653 ("const", ty, ast::Mutability::Immutable, expr)
1655 _ => unreachable!(),
1663 expr_opt: Some(expr),
1669 pub(crate) fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1670 let (ty, expr_opt) = match ti.node {
1671 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1672 _ => unreachable!(),
1676 vis: &DEFAULT_VISIBILITY,
1679 mutability: ast::Mutability::Immutable,
1680 expr_opt: expr_opt.as_ref(),
1686 pub(crate) fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1687 let (ty, expr) = match ii.node {
1688 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1689 _ => unreachable!(),
1696 mutability: ast::Mutability::Immutable,
1697 expr_opt: Some(expr),
1698 defaultness: Some(ii.defaultness),
1705 context: &RewriteContext<'_>,
1706 static_parts: &StaticParts<'_>,
1708 ) -> Option<String> {
1709 let colon = colon_spaces(context.config);
1710 let mut prefix = format!(
1712 format_visibility(context, static_parts.vis),
1713 static_parts.defaultness.map_or("", format_defaultness),
1714 static_parts.prefix,
1715 format_mutability(static_parts.mutability),
1721 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1722 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1723 Some(ty_str) => ty_str,
1725 if prefix.ends_with(' ') {
1728 let nested_indent = offset.block_indent(context.config);
1729 let nested_shape = Shape::indented(nested_indent, context.config);
1730 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1733 nested_indent.to_string_with_newline(context.config),
1739 if let Some(expr) = static_parts.expr_opt {
1740 let lhs = format!("{}{} =", prefix, ty_str);
1742 let remaining_width = context.budget(offset.block_indent + 1);
1747 Shape::legacy(remaining_width, offset.block_only()),
1749 .and_then(|res| recover_comment_removed(res, static_parts.span, context))
1750 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1752 Some(format!("{}{};", prefix, ty_str))
1756 pub(crate) fn rewrite_associated_type(
1758 ty_opt: Option<&ptr::P<ast::Ty>>,
1759 generics: &ast::Generics,
1760 generic_bounds_opt: Option<&ast::GenericBounds>,
1761 context: &RewriteContext<'_>,
1763 ) -> Option<String> {
1764 let ident_str = rewrite_ident(context, ident);
1766 let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
1767 let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
1768 let prefix = format!("type {}", generics_str);
1770 let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
1771 if bounds.is_empty() {
1775 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1776 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1782 if let Some(ty) = ty_opt {
1784 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1785 let lhs = format!("{}{} =", prefix, type_bounds_str);
1786 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1788 Some(format!("{}{};", prefix, type_bounds_str))
1792 pub(crate) fn rewrite_existential_impl_type(
1793 context: &RewriteContext<'_>,
1795 generics: &ast::Generics,
1796 generic_bounds: &ast::GenericBounds,
1798 ) -> Option<String> {
1799 rewrite_associated_type(ident, None, generics, Some(generic_bounds), context, indent)
1800 .map(|s| format!("existential {}", s))
1803 pub(crate) fn rewrite_associated_impl_type(
1805 defaultness: ast::Defaultness,
1806 ty_opt: Option<&ptr::P<ast::Ty>>,
1807 generics: &ast::Generics,
1808 context: &RewriteContext<'_>,
1810 ) -> Option<String> {
1811 let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
1814 ast::Defaultness::Default => Some(format!("default {}", result)),
1819 impl Rewrite for ast::FunctionRetTy {
1820 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1822 ast::FunctionRetTy::Default(_) => Some(String::new()),
1823 ast::FunctionRetTy::Ty(ref ty) => {
1824 let inner_width = shape.width.checked_sub(3)?;
1825 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1826 .map(|r| format!("-> {}", r))
1832 fn is_empty_infer(ty: &ast::Ty, pat_span: Span) -> bool {
1834 ast::TyKind::Infer => ty.span.hi() == pat_span.hi(),
1839 /// Recover any missing comments between the argument and the type.
1843 /// A 2-len tuple with the comment before the colon in first position, and the comment after the
1844 /// colon in second position.
1845 fn get_missing_arg_comments(
1846 context: &RewriteContext<'_>,
1850 ) -> (String, String) {
1851 let missing_comment_span = mk_sp(pat_span.hi(), ty_span.lo());
1853 let span_before_colon = {
1854 let missing_comment_span_hi = context
1856 .span_before(missing_comment_span, ":");
1857 mk_sp(pat_span.hi(), missing_comment_span_hi)
1859 let span_after_colon = {
1860 let missing_comment_span_lo = context
1862 .span_after(missing_comment_span, ":");
1863 mk_sp(missing_comment_span_lo, ty_span.lo())
1866 let comment_before_colon = rewrite_missing_comment(span_before_colon, shape, context)
1867 .filter(|comment| !comment.is_empty())
1868 .map_or(String::new(), |comment| format!(" {}", comment));
1869 let comment_after_colon = rewrite_missing_comment(span_after_colon, shape, context)
1870 .filter(|comment| !comment.is_empty())
1871 .map_or(String::new(), |comment| format!("{} ", comment));
1872 (comment_before_colon, comment_after_colon)
1875 impl Rewrite for ast::Arg {
1876 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
1877 if let Some(ref explicit_self) = self.to_self() {
1878 rewrite_explicit_self(context, explicit_self)
1879 } else if is_named_arg(self) {
1880 let mut result = self
1882 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1884 if !is_empty_infer(&*self.ty, self.pat.span) {
1885 let (before_comment, after_comment) =
1886 get_missing_arg_comments(context, self.pat.span, self.ty.span, shape);
1887 result.push_str(&before_comment);
1888 result.push_str(colon_spaces(context.config));
1889 result.push_str(&after_comment);
1890 let overhead = last_line_width(&result);
1891 let max_width = shape.width.checked_sub(overhead)?;
1894 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1895 result.push_str(&ty_str);
1900 self.ty.rewrite(context, shape)
1905 fn rewrite_explicit_self(
1906 context: &RewriteContext<'_>,
1907 explicit_self: &ast::ExplicitSelf,
1908 ) -> Option<String> {
1909 match explicit_self.node {
1910 ast::SelfKind::Region(lt, m) => {
1911 let mut_str = format_mutability(m);
1914 let lifetime_str = l.rewrite(
1916 Shape::legacy(context.config.max_width(), Indent::empty()),
1918 Some(format!("&{} {}self", lifetime_str, mut_str))
1920 None => Some(format!("&{}self", mut_str)),
1923 ast::SelfKind::Explicit(ref ty, mutability) => {
1924 let type_str = ty.rewrite(
1926 Shape::legacy(context.config.max_width(), Indent::empty()),
1931 format_mutability(mutability),
1935 ast::SelfKind::Value(mutability) => Some(format!("{}self", format_mutability(mutability))),
1939 pub(crate) fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1940 if is_named_arg(arg) {
1947 pub(crate) fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos {
1949 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1950 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1951 _ => arg.ty.span.hi(),
1955 pub(crate) fn is_named_arg(arg: &ast::Arg) -> bool {
1956 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1957 ident.name != symbol::kw::Invalid
1963 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1964 pub(crate) enum FnBraceStyle {
1970 // Return type is (result, force_new_line_for_brace)
1972 context: &RewriteContext<'_>,
1977 fn_brace_style: FnBraceStyle,
1978 ) -> Option<(String, bool)> {
1979 let mut force_new_line_for_brace = false;
1981 let where_clause = &fn_sig.generics.where_clause;
1983 let mut result = String::with_capacity(1024);
1984 result.push_str(&fn_sig.to_str(context));
1987 result.push_str("fn ");
1990 let overhead = if let FnBraceStyle::SameLine = fn_brace_style {
1997 let used_width = last_line_used_width(&result, indent.width());
1998 let one_line_budget = context.budget(used_width + overhead);
2000 width: one_line_budget,
2004 let fd = fn_sig.decl;
2005 let generics_str = rewrite_generics(
2007 rewrite_ident(context, ident),
2011 result.push_str(&generics_str);
2013 let snuggle_angle_bracket = generics_str
2016 .map_or(false, |l| l.trim_start().len() == 1);
2018 // Note that the width and indent don't really matter, we'll re-layout the
2019 // return type later anyway.
2022 .rewrite(context, Shape::indented(indent, context.config))?;
2024 let multi_line_ret_str = ret_str.contains('\n');
2025 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
2028 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
2038 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
2039 one_line_budget, multi_line_budget, arg_indent
2043 // Check if vertical layout was forced.
2044 if one_line_budget == 0
2045 && !snuggle_angle_bracket
2046 && context.config.indent_style() == IndentStyle::Visual
2048 result.push_str(&arg_indent.to_string_with_newline(context.config));
2051 // Skip `pub(crate)`.
2052 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
2053 // A conservative estimation, to goal is to be over all parens in generics
2054 let args_start = fn_sig
2059 .map_or(lo_after_visibility, |param| param.span().hi());
2060 let args_end = if fd.inputs.is_empty() {
2063 .span_after(mk_sp(args_start, span.hi()), ")")
2065 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2066 context.snippet_provider.span_after(last_span, ")")
2068 let args_span = mk_sp(
2071 .span_after(mk_sp(args_start, span.hi()), "("),
2074 let arg_str = rewrite_args(
2085 let put_args_in_block = match context.config.indent_style() {
2086 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
2088 } && !fd.inputs.is_empty();
2090 let mut args_last_line_contains_comment = false;
2091 let mut no_args_and_over_max_width = false;
2093 if put_args_in_block {
2094 arg_indent = indent.block_indent(context.config);
2095 result.push_str(&arg_indent.to_string_with_newline(context.config));
2096 result.push_str(&arg_str);
2097 result.push_str(&indent.to_string_with_newline(context.config));
2100 result.push_str(&arg_str);
2101 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2102 // Put the closing brace on the next line if it overflows the max width.
2104 let closing_paren_overflow_max_width =
2105 fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2106 // If the last line of args contains comment, we cannot put the closing paren
2107 // on the same line.
2108 args_last_line_contains_comment = arg_str
2111 .map_or(false, |last_line| last_line.contains("//"));
2113 if context.config.version() == Version::Two {
2115 if closing_paren_overflow_max_width || args_last_line_contains_comment {
2116 result.push_str(&indent.to_string_with_newline(context.config));
2117 no_args_and_over_max_width = true;
2120 if closing_paren_overflow_max_width || args_last_line_contains_comment {
2121 result.push_str(&indent.to_string_with_newline(context.config));
2128 if let ast::FunctionRetTy::Ty(..) = fd.output {
2129 let ret_should_indent = match context.config.indent_style() {
2130 // If our args are block layout then we surely must have space.
2131 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
2132 _ if args_last_line_contains_comment => false,
2133 _ if result.contains('\n') || multi_line_ret_str => true,
2135 // If the return type would push over the max width, then put the return type on
2136 // a new line. With the +1 for the signature length an additional space between
2137 // the closing parenthesis of the argument and the arrow '->' is considered.
2138 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2140 // If there is no where-clause, take into account the space after the return type
2142 if where_clause.predicates.is_empty() {
2146 sig_length > context.config.max_width()
2149 let ret_indent = if ret_should_indent {
2150 let indent = if arg_str.is_empty() {
2151 // Aligning with non-existent args looks silly.
2152 force_new_line_for_brace = true;
2155 // FIXME: we might want to check that using the arg indent
2156 // doesn't blow our budget, and if it does, then fallback to
2157 // the where-clause indent.
2161 result.push_str(&indent.to_string_with_newline(context.config));
2164 if context.config.version() == Version::Two {
2165 if !arg_str.is_empty() || !no_args_and_over_max_width {
2172 Indent::new(indent.block_indent, last_line_width(&result))
2175 if multi_line_ret_str || ret_should_indent {
2176 // Now that we know the proper indent and width, we need to
2177 // re-layout the return type.
2180 .rewrite(context, Shape::indented(ret_indent, context.config))?;
2181 result.push_str(&ret_str);
2183 result.push_str(&ret_str);
2186 // Comment between return type and the end of the decl.
2187 let snippet_lo = fd.output.span().hi();
2188 if where_clause.predicates.is_empty() {
2189 let snippet_hi = span.hi();
2190 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2191 // Try to preserve the layout of the original snippet.
2192 let original_starts_with_newline = snippet
2194 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2195 let original_ends_with_newline = snippet
2196 .rfind(|c| c != ' ')
2197 .map_or(false, |i| snippet[i..].ends_with('\n'));
2198 let snippet = snippet.trim();
2199 if !snippet.is_empty() {
2200 result.push(if original_starts_with_newline {
2205 result.push_str(snippet);
2206 if original_ends_with_newline {
2207 force_new_line_for_brace = true;
2213 let pos_before_where = match fd.output {
2214 ast::FunctionRetTy::Default(..) => args_span.hi(),
2215 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2218 let is_args_multi_lined = arg_str.contains('\n');
2220 let space = if put_args_in_block && ret_str.is_empty() {
2221 WhereClauseSpace::Space
2223 WhereClauseSpace::Newline
2225 let mut option = WhereClauseOption::new(fn_brace_style == FnBraceStyle::None, space);
2226 if is_args_multi_lined {
2227 option.veto_single_line();
2229 let where_clause_str = rewrite_where_clause(
2232 context.config.brace_style(),
2233 Shape::indented(indent, context.config),
2240 // If there are neither where-clause nor return type, we may be missing comments between
2242 if where_clause_str.is_empty() {
2243 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2244 match recover_missing_comment_in_span(
2245 mk_sp(args_span.hi(), ret_span.hi()),
2248 last_line_width(&result),
2250 Some(ref missing_comment) if !missing_comment.is_empty() => {
2251 result.push_str(missing_comment);
2252 force_new_line_for_brace = true;
2259 result.push_str(&where_clause_str);
2261 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2262 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2263 Some((result, force_new_line_for_brace))
2266 /// Kind of spaces to put before `where`.
2267 #[derive(Copy, Clone)]
2268 enum WhereClauseSpace {
2277 #[derive(Copy, Clone)]
2278 struct WhereClauseOption {
2279 suppress_comma: bool, // Force no trailing comma
2280 snuggle: WhereClauseSpace,
2281 allow_single_line: bool, // Try single line where-clause instead of vertical layout
2282 veto_single_line: bool, // Disallow a single-line where-clause.
2285 impl WhereClauseOption {
2286 fn new(suppress_comma: bool, snuggle: WhereClauseSpace) -> WhereClauseOption {
2290 allow_single_line: false,
2291 veto_single_line: false,
2295 fn snuggled(current: &str) -> WhereClauseOption {
2297 suppress_comma: false,
2298 snuggle: if last_line_width(current) == 1 {
2299 WhereClauseSpace::Space
2301 WhereClauseSpace::Newline
2303 allow_single_line: false,
2304 veto_single_line: false,
2308 fn suppress_comma(&mut self) {
2309 self.suppress_comma = true
2312 fn allow_single_line(&mut self) {
2313 self.allow_single_line = true
2316 fn snuggle(&mut self) {
2317 self.snuggle = WhereClauseSpace::Space
2320 fn veto_single_line(&mut self) {
2321 self.veto_single_line = true;
2326 context: &RewriteContext<'_>,
2328 one_line_budget: usize,
2329 multi_line_budget: usize,
2334 ) -> Option<String> {
2335 if args.is_empty() {
2336 let comment = context
2340 span.hi() - BytePos(1),
2343 return Some(comment.to_owned());
2345 let arg_items: Vec<_> = itemize_list(
2346 context.snippet_provider,
2350 |arg| span_lo_for_arg(arg),
2351 |arg| arg.ty.span.hi(),
2353 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2354 .or_else(|| Some(context.snippet(arg.span()).to_owned()))
2362 let tactic = definitive_tactic(
2367 .to_list_tactic(arg_items.len()),
2371 let budget = match tactic {
2372 DefinitiveListTactic::Horizontal => one_line_budget,
2373 _ => multi_line_budget,
2375 let indent = match context.config.indent_style() {
2376 IndentStyle::Block => indent.block_indent(context.config),
2377 IndentStyle::Visual => arg_indent,
2379 let trailing_separator = if variadic {
2380 SeparatorTactic::Never
2382 match context.config.indent_style() {
2383 IndentStyle::Block => context.config.trailing_comma(),
2384 IndentStyle::Visual => SeparatorTactic::Never,
2387 let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2389 .trailing_separator(trailing_separator)
2390 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2391 .preserve_newline(true);
2392 write_list(&arg_items, &fmt)
2395 fn compute_budgets_for_args(
2396 context: &RewriteContext<'_>,
2400 fn_brace_style: FnBraceStyle,
2401 force_vertical_layout: bool,
2402 ) -> Option<((usize, usize, Indent))> {
2404 "compute_budgets_for_args {} {:?}, {}, {:?}",
2410 // Try keeping everything on the same line.
2411 if !result.contains('\n') && !force_vertical_layout {
2412 // 2 = `()`, 3 = `() `, space is before ret_string.
2413 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2414 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2415 match fn_brace_style {
2416 FnBraceStyle::None => used_space += 1, // 1 = `;`
2417 FnBraceStyle::SameLine => used_space += 2, // 2 = `{}`
2418 FnBraceStyle::NextLine => (),
2420 let one_line_budget = context.budget(used_space);
2422 if one_line_budget > 0 {
2424 let (indent, multi_line_budget) = match context.config.indent_style() {
2425 IndentStyle::Block => {
2426 let indent = indent.block_indent(context.config);
2427 (indent, context.budget(indent.width() + 1))
2429 IndentStyle::Visual => {
2430 let indent = indent + result.len() + 1;
2431 let multi_line_overhead = match fn_brace_style {
2432 FnBraceStyle::SameLine => 4,
2435 (indent, context.budget(multi_line_overhead))
2439 return Some((one_line_budget, multi_line_budget, indent));
2443 // Didn't work. we must force vertical layout and put args on a newline.
2444 let new_indent = indent.block_indent(context.config);
2445 let used_space = match context.config.indent_style() {
2447 IndentStyle::Block => new_indent.width() + 1,
2448 // Account for `)` and possibly ` {`.
2449 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2451 Some((0, context.budget(used_space), new_indent))
2454 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> FnBraceStyle {
2455 let predicate_count = where_clause.predicates.len();
2457 if config.where_single_line() && predicate_count == 1 {
2458 return FnBraceStyle::SameLine;
2460 let brace_style = config.brace_style();
2462 let use_next_line = brace_style == BraceStyle::AlwaysNextLine
2463 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0);
2465 FnBraceStyle::NextLine
2467 FnBraceStyle::SameLine
2471 fn rewrite_generics(
2472 context: &RewriteContext<'_>,
2474 generics: &ast::Generics,
2476 ) -> Option<String> {
2477 // FIXME: convert bounds to where-clauses where they get too big or if
2478 // there is a where-clause at all.
2480 if generics.params.is_empty() {
2481 return Some(ident.to_owned());
2484 let params = generics.params.iter();
2485 overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2488 pub(crate) fn generics_shape_from_config(
2492 ) -> Option<Shape> {
2493 match config.indent_style() {
2494 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2495 IndentStyle::Block => {
2499 .block_indent(config.tab_spaces())
2500 .with_max_width(config)
2506 fn rewrite_where_clause_rfc_style(
2507 context: &RewriteContext<'_>,
2508 where_clause: &ast::WhereClause,
2511 span_end: Option<BytePos>,
2512 span_end_before_where: BytePos,
2513 where_clause_option: WhereClauseOption,
2514 ) -> Option<String> {
2515 let (where_keyword, allow_single_line) = rewrite_where_keyword(
2519 span_end_before_where,
2520 where_clause_option,
2524 let clause_shape = shape
2526 .with_max_width(context.config)
2527 .block_left(context.config.tab_spaces())?
2529 let force_single_line = context.config.where_single_line()
2530 && where_clause.predicates.len() == 1
2531 && !where_clause_option.veto_single_line;
2533 let preds_str = rewrite_bounds_on_where_clause(
2539 where_clause_option,
2545 if allow_single_line && !preds_str.contains('\n') && 6 + preds_str.len() <= shape.width
2546 || force_single_line
2550 clause_shape.indent.to_string_with_newline(context.config)
2553 Some(format!("{}{}{}", where_keyword, clause_sep, preds_str))
2556 /// Rewrite `where` and comment around it.
2557 fn rewrite_where_keyword(
2558 context: &RewriteContext<'_>,
2559 where_clause: &ast::WhereClause,
2561 span_end_before_where: BytePos,
2562 where_clause_option: WhereClauseOption,
2563 ) -> Option<(String, bool)> {
2564 let block_shape = shape.block().with_max_width(context.config);
2566 let clause_shape = block_shape
2567 .block_left(context.config.tab_spaces())?
2570 let comment_separator = |comment: &str, shape: Shape| {
2571 if comment.is_empty() {
2574 shape.indent.to_string_with_newline(context.config)
2578 let (span_before, span_after) =
2579 missing_span_before_after_where(span_end_before_where, where_clause);
2580 let (comment_before, comment_after) =
2581 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2583 let starting_newline = match where_clause_option.snuggle {
2584 WhereClauseSpace::Space if comment_before.is_empty() => Cow::from(" "),
2585 WhereClauseSpace::None => Cow::from(""),
2586 _ => block_shape.indent.to_string_with_newline(context.config),
2589 let newline_before_where = comment_separator(&comment_before, shape);
2590 let newline_after_where = comment_separator(&comment_after, clause_shape);
2591 let result = format!(
2593 starting_newline, comment_before, newline_before_where, newline_after_where, comment_after
2595 let allow_single_line = where_clause_option.allow_single_line
2596 && comment_before.is_empty()
2597 && comment_after.is_empty();
2599 Some((result, allow_single_line))
2602 /// Rewrite bounds on a where clause.
2603 fn rewrite_bounds_on_where_clause(
2604 context: &RewriteContext<'_>,
2605 where_clause: &ast::WhereClause,
2608 span_end: Option<BytePos>,
2609 where_clause_option: WhereClauseOption,
2610 force_single_line: bool,
2611 ) -> Option<String> {
2612 let span_start = where_clause.predicates[0].span().lo();
2613 // If we don't have the start of the next span, then use the end of the
2614 // predicates, but that means we miss comments.
2615 let len = where_clause.predicates.len();
2616 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2617 let span_end = span_end.unwrap_or(end_of_preds);
2618 let items = itemize_list(
2619 context.snippet_provider,
2620 where_clause.predicates.iter(),
2623 |pred| pred.span().lo(),
2624 |pred| pred.span().hi(),
2625 |pred| pred.rewrite(context, shape),
2630 let comma_tactic = if where_clause_option.suppress_comma || force_single_line {
2631 SeparatorTactic::Never
2633 context.config.trailing_comma()
2636 // shape should be vertical only and only if we have `force_single_line` option enabled
2637 // and the number of items of the where-clause is equal to 1
2638 let shape_tactic = if force_single_line {
2639 DefinitiveListTactic::Horizontal
2641 DefinitiveListTactic::Vertical
2644 let fmt = ListFormatting::new(shape, context.config)
2645 .tactic(shape_tactic)
2646 .trailing_separator(comma_tactic)
2647 .preserve_newline(true);
2648 write_list(&items.collect::<Vec<_>>(), &fmt)
2651 fn rewrite_where_clause(
2652 context: &RewriteContext<'_>,
2653 where_clause: &ast::WhereClause,
2654 brace_style: BraceStyle,
2658 span_end: Option<BytePos>,
2659 span_end_before_where: BytePos,
2660 where_clause_option: WhereClauseOption,
2661 ) -> Option<String> {
2662 if where_clause.predicates.is_empty() {
2663 return Some(String::new());
2666 if context.config.indent_style() == IndentStyle::Block {
2667 return rewrite_where_clause_rfc_style(
2673 span_end_before_where,
2674 where_clause_option,
2678 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2680 let offset = match context.config.indent_style() {
2681 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2682 // 6 = "where ".len()
2683 IndentStyle::Visual => shape.indent + extra_indent + 6,
2685 // FIXME: if indent_style != Visual, then the budgets below might
2686 // be out by a char or two.
2688 let budget = context.config.max_width() - offset.width();
2689 let span_start = where_clause.predicates[0].span().lo();
2690 // If we don't have the start of the next span, then use the end of the
2691 // predicates, but that means we miss comments.
2692 let len = where_clause.predicates.len();
2693 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2694 let span_end = span_end.unwrap_or(end_of_preds);
2695 let items = itemize_list(
2696 context.snippet_provider,
2697 where_clause.predicates.iter(),
2700 |pred| pred.span().lo(),
2701 |pred| pred.span().hi(),
2702 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2707 let item_vec = items.collect::<Vec<_>>();
2708 // FIXME: we don't need to collect here
2709 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2711 let mut comma_tactic = context.config.trailing_comma();
2712 // Kind of a hack because we don't usually have trailing commas in where-clauses.
2713 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2714 comma_tactic = SeparatorTactic::Never;
2717 let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
2719 .trailing_separator(comma_tactic)
2720 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2721 .preserve_newline(true);
2722 let preds_str = write_list(&item_vec, &fmt)?;
2724 let end_length = if terminator == "{" {
2725 // If the brace is on the next line we don't need to count it otherwise it needs two
2728 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2729 BraceStyle::PreferSameLine => 2,
2731 } else if terminator == "=" {
2737 || preds_str.contains('\n')
2738 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2742 (shape.indent + extra_indent).to_string(context.config),
2746 Some(format!(" where {}", preds_str))
2750 fn missing_span_before_after_where(
2751 before_item_span_end: BytePos,
2752 where_clause: &ast::WhereClause,
2754 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2756 let pos_after_where = where_clause.span.lo() + BytePos(5);
2757 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2758 (missing_span_before, missing_span_after)
2761 fn rewrite_comments_before_after_where(
2762 context: &RewriteContext<'_>,
2763 span_before_where: Span,
2764 span_after_where: Span,
2766 ) -> Option<(String, String)> {
2767 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2768 let after_comment = rewrite_missing_comment(
2770 shape.block_indent(context.config.tab_spaces()),
2773 Some((before_comment, after_comment))
2777 context: &RewriteContext<'_>,
2780 vis: &ast::Visibility,
2784 format_visibility(context, vis),
2786 rewrite_ident(context, ident)
2790 #[derive(PartialEq, Eq, Clone, Copy)]
2798 context: &RewriteContext<'_>,
2799 generics: &ast::Generics,
2800 brace_style: BraceStyle,
2801 brace_pos: BracePos,
2805 ) -> Option<String> {
2806 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2807 let mut result = rewrite_generics(context, "", generics, shape)?;
2809 // If the generics are not parameterized then generics.span.hi() == 0,
2810 // so we use span.lo(), which is the position after `struct Foo`.
2811 let span_end_before_where = if !generics.params.is_empty() {
2816 let (same_line_brace, missed_comments) = if !generics.where_clause.predicates.is_empty() {
2817 let budget = context.budget(last_line_used_width(&result, offset.width()));
2818 let mut option = WhereClauseOption::snuggled(&result);
2819 if brace_pos == BracePos::None {
2820 option.suppress_comma = true;
2822 let where_clause_str = rewrite_where_clause(
2824 &generics.where_clause,
2826 Shape::legacy(budget, offset.block_only()),
2830 span_end_before_where,
2833 result.push_str(&where_clause_str);
2835 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine,
2836 // missed comments are taken care of in #rewrite_where_clause
2841 brace_pos == BracePos::ForceSameLine
2842 || (result.contains('\n') && brace_style == BraceStyle::PreferSameLine
2843 || brace_style != BraceStyle::AlwaysNextLine)
2844 || trimmed_last_line_width(&result) == 1,
2845 rewrite_missing_comment(
2847 span_end_before_where,
2848 if brace_pos == BracePos::None {
2851 context.snippet_provider.span_before(span, "{")
2859 // add missing comments
2860 let missed_line_comments = missed_comments
2861 .filter(|missed_comments| !missed_comments.is_empty())
2862 .map_or(false, |missed_comments| {
2863 let is_block = is_last_comment_block(&missed_comments);
2864 let sep = if is_block { " " } else { "\n" };
2865 result.push_str(sep);
2866 result.push_str(&missed_comments);
2869 if brace_pos == BracePos::None {
2870 return Some(result);
2872 let total_used_width = last_line_used_width(&result, used_width);
2873 let remaining_budget = context.budget(total_used_width);
2874 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2875 // and hence we take the closer into account as well for one line budget.
2876 // We assume that the closer has the same length as the opener.
2877 let overhead = if brace_pos == BracePos::ForceSameLine {
2884 let forbid_same_line_brace = missed_line_comments || overhead > remaining_budget;
2885 if !forbid_same_line_brace && same_line_brace {
2889 result.push_str(&offset.block_only().to_string(context.config));
2896 impl Rewrite for ast::ForeignItem {
2897 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
2898 let attrs_str = self.attrs.rewrite(context, shape)?;
2899 // Drop semicolon or it will be interpreted as comment.
2900 // FIXME: this may be a faulty span from libsyntax.
2901 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2903 let item_str = match self.node {
2904 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2908 &FnSig::new(fn_decl, generics, self.vis.clone()),
2912 .map(|(s, _)| format!("{};", s)),
2913 ast::ForeignItemKind::Static(ref ty, mutability) => {
2914 // FIXME(#21): we're dropping potential comments in between the
2915 // function kw here.
2916 let vis = format_visibility(context, &self.vis);
2917 let mut_str = format_mutability(mutability);
2918 let prefix = format!(
2922 rewrite_ident(context, self.ident)
2925 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
2927 ast::ForeignItemKind::Ty => {
2928 let vis = format_visibility(context, &self.vis);
2932 rewrite_ident(context, self.ident)
2935 ast::ForeignItemKind::Macro(ref mac) => {
2936 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
2940 let missing_span = if self.attrs.is_empty() {
2941 mk_sp(self.span.lo(), self.span.lo())
2943 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2945 combine_strs_with_missing_comments(
2956 /// Rewrite the attributes of an item.
2958 context: &RewriteContext<'_>,
2962 ) -> Option<String> {
2963 let attrs = filter_inline_attrs(&item.attrs, item.span());
2964 let attrs_str = attrs.rewrite(context, shape)?;
2966 let missed_span = if attrs.is_empty() {
2967 mk_sp(item.span.lo(), item.span.lo())
2969 mk_sp(attrs[attrs.len() - 1].span.hi(), item.span.lo())
2972 let allow_extend = if attrs.len() == 1 {
2973 let line_len = attrs_str.len() + 1 + item_str.len();
2974 !attrs.first().unwrap().is_sugared_doc
2975 && context.config.inline_attribute_width() >= line_len
2980 combine_strs_with_missing_comments(
2990 /// Rewrite an inline mod.
2991 /// The given shape is used to format the mod's attributes.
2992 pub(crate) fn rewrite_mod(
2993 context: &RewriteContext<'_>,
2996 ) -> Option<String> {
2997 let mut result = String::with_capacity(32);
2998 result.push_str(&*format_visibility(context, &item.vis));
2999 result.push_str("mod ");
3000 result.push_str(rewrite_ident(context, item.ident));
3002 rewrite_attrs(context, item, &result, attrs_shape)
3005 /// Rewrite `extern crate foo;`.
3006 /// The given shape is used to format the extern crate's attributes.
3007 pub(crate) fn rewrite_extern_crate(
3008 context: &RewriteContext<'_>,
3011 ) -> Option<String> {
3012 assert!(is_extern_crate(item));
3013 let new_str = context.snippet(item.span);
3014 let item_str = if contains_comment(new_str) {
3017 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
3018 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
3020 rewrite_attrs(context, item, &item_str, attrs_shape)
3023 /// Returns `true` for `mod foo;`, false for `mod foo { .. }`.
3024 pub(crate) fn is_mod_decl(item: &ast::Item) -> bool {
3026 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
3031 pub(crate) fn is_use_item(item: &ast::Item) -> bool {
3033 ast::ItemKind::Use(_) => true,
3038 pub(crate) fn is_extern_crate(item: &ast::Item) -> bool {
3040 ast::ItemKind::ExternCrate(..) => true,