1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use std::cmp::{min, Ordering};
18 use rustc_target::spec::abi;
19 use syntax::codemap::{self, BytePos, Span};
21 use syntax::{ast, ptr, symbol};
23 use codemap::{LineRangeUtils, SpanUtils};
25 combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
26 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented,
28 use config::{BraceStyle, Config, Density, IndentStyle};
30 format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
33 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
34 use macros::{rewrite_macro, MacroPosition};
36 use rewrite::{Rewrite, RewriteContext};
37 use shape::{Indent, Shape};
40 use vertical::rewrite_with_alignment;
41 use visitor::FmtVisitor;
43 const DEFAULT_VISIBILITY: ast::Visibility = codemap::Spanned {
44 node: ast::VisibilityKind::Inherited,
45 span: codemap::DUMMY_SP,
48 fn type_annotation_separator(config: &Config) -> &str {
49 colon_spaces(config.space_before_colon(), config.space_after_colon())
52 // Statements of the form
53 // let pat: ty = init;
54 impl Rewrite for ast::Local {
55 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
57 "Local::rewrite {:?} {} {:?}",
58 self, shape.width, shape.indent
61 skip_out_of_file_lines_range!(context, self.span);
63 if contains_skip(&self.attrs) {
67 let attrs_str = self.attrs.rewrite(context, shape)?;
68 let mut result = if attrs_str.is_empty() {
71 combine_strs_with_missing_comments(
76 self.attrs.last().map(|a| a.span.hi()).unwrap(),
85 let pat_shape = shape.offset_left(4)?;
87 let pat_shape = pat_shape.sub_width(1)?;
88 let pat_str = self.pat.rewrite(context, pat_shape)?;
89 result.push_str(&pat_str);
91 // String that is placed within the assignment pattern and expression.
93 let mut infix = String::with_capacity(32);
95 if let Some(ref ty) = self.ty {
96 let separator = type_annotation_separator(context.config);
97 let indent = shape.indent + last_line_width(&result) + separator.len();
99 let budget = shape.width.checked_sub(indent.width() + 1)?;
100 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
102 infix.push_str(separator);
103 infix.push_str(&rewrite);
106 if self.init.is_some() {
107 infix.push_str(" =");
113 result.push_str(&infix);
115 if let Some(ref ex) = self.init {
116 // 1 = trailing semicolon;
117 let nested_shape = shape.sub_width(1)?;
119 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
127 // FIXME convert to using rewrite style rather than visitor
128 // FIXME format modules in this style
131 keyword: &'static str,
132 abi: Cow<'static, str>,
133 vis: Option<&'a ast::Visibility>,
134 body: Vec<BodyElement<'a>>,
139 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
142 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
147 .map(|i| BodyElement::ForeignItem(i))
154 enum BodyElement<'a> {
155 // Stmt(&'a ast::Stmt),
156 // Field(&'a ast::Field),
157 // Variant(&'a ast::Variant),
158 // Item(&'a ast::Item),
159 ForeignItem(&'a ast::ForeignItem),
162 /// Represents a fn's signature.
163 pub struct FnSig<'a> {
164 decl: &'a ast::FnDecl,
165 generics: &'a ast::Generics,
167 constness: ast::Constness,
168 defaultness: ast::Defaultness,
169 unsafety: ast::Unsafety,
170 visibility: ast::Visibility,
175 decl: &'a ast::FnDecl,
176 generics: &'a ast::Generics,
177 vis: ast::Visibility,
183 constness: ast::Constness::NotConst,
184 defaultness: ast::Defaultness::Final,
185 unsafety: ast::Unsafety::Normal,
190 pub fn from_method_sig(
191 method_sig: &'a ast::MethodSig,
192 generics: &'a ast::Generics,
195 unsafety: method_sig.unsafety,
196 constness: method_sig.constness.node,
197 defaultness: ast::Defaultness::Final,
199 decl: &*method_sig.decl,
201 visibility: DEFAULT_VISIBILITY,
206 fn_kind: &'a visit::FnKind,
207 generics: &'a ast::Generics,
208 decl: &'a ast::FnDecl,
209 defaultness: ast::Defaultness,
212 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
216 constness: constness.node,
219 visibility: visibility.clone(),
221 visit::FnKind::Method(_, method_sig, vis, _) => {
222 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
223 fn_sig.defaultness = defaultness;
224 if let Some(vis) = vis {
225 fn_sig.visibility = vis.clone();
233 fn to_str(&self, context: &RewriteContext) -> String {
234 let mut result = String::with_capacity(128);
235 // Vis defaultness constness unsafety abi.
236 result.push_str(&*format_visibility(context, &self.visibility));
237 result.push_str(format_defaultness(self.defaultness));
238 result.push_str(format_constness(self.constness));
239 result.push_str(format_unsafety(self.unsafety));
240 result.push_str(&format_abi(
242 context.config.force_explicit_abi(),
249 impl<'a> FmtVisitor<'a> {
250 fn format_item(&mut self, item: &Item) {
251 self.buffer.push_str(&item.abi);
253 let snippet = self.snippet(item.span);
254 let brace_pos = snippet.find_uncommented("{").unwrap();
257 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
258 // FIXME: this skips comments between the extern keyword and the opening
260 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
261 self.block_indent = self.block_indent.block_indent(self.config);
263 if item.body.is_empty() {
264 self.format_missing_no_indent(item.span.hi() - BytePos(1));
265 self.block_indent = self.block_indent.block_unindent(self.config);
266 let indent_str = self.block_indent.to_string(self.config);
267 self.push_str(&indent_str);
269 for item in &item.body {
270 self.format_body_element(item);
273 self.block_indent = self.block_indent.block_unindent(self.config);
274 self.format_missing_with_indent(item.span.hi() - BytePos(1));
279 self.last_pos = item.span.hi();
282 fn format_body_element(&mut self, element: &BodyElement) {
284 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
288 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
289 let item = Item::from_foreign_mod(fm, span, self.config);
290 self.format_item(&item);
293 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
294 let rewrite = item.rewrite(&self.get_context(), self.shape());
295 self.push_rewrite(item.span(), rewrite);
296 self.last_pos = item.span.hi();
306 inner_attrs: Option<&[ast::Attribute]>,
307 ) -> Option<String> {
308 let context = self.get_context();
310 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
312 let (mut result, force_newline_brace) =
313 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
316 if self.config.brace_style() == BraceStyle::AlwaysNextLine
317 || force_newline_brace
318 || last_line_width(&result) + 2 > self.shape().width
320 newline_brace = true;
321 } else if !result.contains('\n') {
322 newline_brace = false;
325 // Prepare for the function body by possibly adding a newline and
327 // FIXME we'll miss anything between the end of the signature and the
328 // start of the body, but we need more spans from the compiler to solve
331 result.push_str(&indent.to_string_with_newline(self.config));
336 self.single_line_fn(&result, block, inner_attrs)
337 .or_else(|| Some(result))
340 pub fn rewrite_required_fn(
344 sig: &ast::MethodSig,
345 generics: &ast::Generics,
347 ) -> Option<String> {
348 // Drop semicolon or it will be interpreted as comment.
349 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
350 let context = self.get_context();
352 let (mut result, _) = rewrite_fn_base(
356 &FnSig::from_method_sig(sig, generics),
362 // Re-attach semicolon
372 inner_attrs: Option<&[ast::Attribute]>,
373 ) -> Option<String> {
374 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
378 let codemap = self.get_context().codemap;
380 if self.config.empty_item_single_line()
381 && is_empty_block(block, None, codemap)
382 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
384 return Some(format!("{}{{}}", fn_str));
387 if self.config.fn_single_line() && is_simple_block_stmt(block, None, codemap) {
389 if let Some(stmt) = block.stmts.first() {
390 match stmt_expr(stmt) {
392 let suffix = if semicolon_for_expr(&self.get_context(), e) {
398 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
400 .or_else(|| Some(self.snippet(e.span).to_owned()))
402 None => stmt.rewrite(&self.get_context(), self.shape()),
409 if let Some(res) = rewrite {
410 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
411 if !res.contains('\n') && width <= self.config.max_width() {
412 return Some(format!("{}{{ {} }}", fn_str, res));
420 pub fn visit_static(&mut self, static_parts: &StaticParts) {
421 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
422 self.push_rewrite(static_parts.span, rewrite);
425 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
426 let is_tuple = struct_parts.def.is_tuple();
427 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
428 .map(|s| if is_tuple { s + ";" } else { s });
429 self.push_rewrite(struct_parts.span, rewrite);
435 vis: &ast::Visibility,
436 enum_def: &ast::EnumDef,
437 generics: &ast::Generics,
440 let enum_header = format_header(&self.get_context(), "enum ", ident, vis);
441 self.push_str(&enum_header);
443 let enum_snippet = self.snippet(span);
444 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
445 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
446 let generics_str = format_generics(
449 self.config.brace_style(),
450 if enum_def.variants.is_empty() {
451 BracePos::ForceSameLine
456 mk_sp(span.lo(), body_start),
457 last_line_width(&enum_header),
459 self.push_str(&generics_str);
461 self.last_pos = body_start;
463 match self.format_variant_list(enum_def, body_start, span.hi()) {
464 Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
466 self.push_rewrite(mk_sp(body_start, span.hi()), rw);
467 self.block_indent = self.block_indent.block_unindent(self.config);
472 // Format the body of an enum definition
473 fn format_variant_list(
475 enum_def: &ast::EnumDef,
478 ) -> Option<String> {
479 if enum_def.variants.is_empty() {
480 let mut buffer = String::with_capacity(128);
482 let span = mk_sp(body_lo, body_hi - BytePos(1));
483 format_empty_struct_or_tuple(
493 let mut result = String::with_capacity(1024);
494 let original_offset = self.block_indent;
495 self.block_indent = self.block_indent.block_indent(self.config);
497 let itemize_list_with = |one_line_width: usize| {
499 self.snippet_provider,
500 enum_def.variants.iter(),
504 if !f.node.attrs.is_empty() {
505 f.node.attrs[0].span.lo()
511 |f| self.format_variant(f, one_line_width),
517 let mut items: Vec<_> =
518 itemize_list_with(self.config.width_heuristics().struct_variant_width);
519 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
520 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
521 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
522 if has_multiline_variant && has_single_line_variant {
523 items = itemize_list_with(0);
526 let shape = self.shape().sub_width(2)?;
527 let fmt = ListFormatting {
528 tactic: DefinitiveListTactic::Vertical,
530 trailing_separator: self.config.trailing_comma(),
531 separator_place: SeparatorPlace::Back,
533 ends_with_newline: true,
534 preserve_newline: true,
539 let list = write_list(&items, &fmt)?;
540 result.push_str(&list);
541 result.push_str(&original_offset.to_string_with_newline(self.config));
546 // Variant of an enum.
547 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
548 if contains_skip(&field.node.attrs) {
549 let lo = field.node.attrs[0].span.lo();
550 let span = mk_sp(lo, field.span.hi());
551 return Some(self.snippet(span).to_owned());
554 let context = self.get_context();
556 let shape = self.shape().sub_width(1)?;
557 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
562 .map_or(field.span.lo(), |attr| attr.span.hi());
563 let span = mk_sp(lo, field.span.lo());
565 let variant_body = match field.node.data {
566 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
568 &StructParts::from_variant(field),
570 Some(one_line_width),
572 ast::VariantData::Unit(..) => {
573 if let Some(ref expr) = field.node.disr_expr {
574 let lhs = format!("{} =", rewrite_ident(&context, field.node.ident));
575 rewrite_assign_rhs(&context, lhs, &*expr.value, shape)?
577 rewrite_ident(&context, field.node.ident).to_owned()
582 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
585 fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
586 if self.get_context().config.reorder_impl_items() {
587 // Create visitor for each items, then reorder them.
588 let mut buffer = vec![];
590 self.visit_impl_item(item);
591 buffer.push((self.buffer.clone(), item.clone()));
594 // type -> const -> macro -> method
595 use ast::ImplItemKind::*;
596 fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
598 (Type(..), Type(..)) | (Const(..), Const(..)) => false,
603 buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
604 (Type(..), _) => Ordering::Less,
605 (_, Type(..)) => Ordering::Greater,
606 (Const(..), _) => Ordering::Less,
607 (_, Const(..)) => Ordering::Greater,
608 (Macro(..), _) => Ordering::Less,
609 (_, Macro(..)) => Ordering::Greater,
610 _ => a.span.lo().cmp(&b.span.lo()),
612 let mut prev_kind = None;
613 for (buf, item) in buffer {
614 // Make sure that there are at least a single empty line between
615 // different impl items.
618 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
622 let indent_str = self.block_indent.to_string_with_newline(self.config);
623 self.push_str(&indent_str);
624 self.push_str(buf.trim());
625 prev_kind = Some(item.node.clone());
629 self.visit_impl_item(item);
636 context: &RewriteContext,
639 where_span_end: Option<BytePos>,
640 ) -> Option<String> {
641 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
642 let mut result = String::with_capacity(128);
643 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
644 let sep = offset.to_string_with_newline(context.config);
645 result.push_str(&ref_and_type);
647 let where_budget = if result.contains('\n') {
648 context.config.max_width()
650 context.budget(last_line_width(&result))
653 let mut option = WhereClauseOption::snuggled(&ref_and_type);
654 let snippet = context.snippet(item.span);
655 let open_pos = snippet.find_uncommented("{")? + 1;
656 if !contains_comment(&snippet[open_pos..])
658 && generics.where_clause.predicates.len() == 1
659 && !result.contains('\n')
661 option.suppress_comma();
663 option.compress_where();
666 let mut where_clause_str = rewrite_where_clause(
668 &generics.where_clause,
669 context.config.brace_style(),
670 Shape::legacy(where_budget, offset.block_only()),
679 // If there is no where clause, we may have missing comments between the trait name and
680 // the opening brace.
681 if generics.where_clause.predicates.is_empty() {
682 if let Some(hi) = where_span_end {
683 match recover_missing_comment_in_span(
684 mk_sp(self_ty.span.hi(), hi),
685 Shape::indented(offset, context.config),
687 last_line_width(&result),
689 Some(ref missing_comment) if !missing_comment.is_empty() => {
690 result.push_str(missing_comment);
697 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
698 result.push_str(&where_clause_str);
699 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
700 // if the where_clause contains extra comments AND
701 // there is only one where clause predicate
702 // recover the suppressed comma in single line where_clause formatting
703 if generics.where_clause.predicates.len() == 1 {
704 result.push_str(",");
706 result.push_str(&format!("{}{{{}}}", &sep, &sep));
708 result.push_str(" {}");
713 result.push_str(&where_clause_str);
715 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
716 match context.config.brace_style() {
717 _ if need_newline => result.push_str(&sep),
718 BraceStyle::AlwaysNextLine => result.push_str(&sep),
719 BraceStyle::PreferSameLine => result.push(' '),
720 BraceStyle::SameLineWhere => {
721 if !where_clause_str.is_empty() {
722 result.push_str(&sep);
731 let snippet = context.snippet(item.span);
732 let open_pos = snippet.find_uncommented("{")? + 1;
734 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
735 let mut visitor = FmtVisitor::from_context(context);
736 let item_indent = offset.block_only().block_indent(context.config);
737 visitor.block_indent = item_indent;
738 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
740 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
741 visitor.visit_impl_items(items);
743 visitor.format_missing(item.span.hi() - BytePos(1));
745 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
746 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
748 result.push_str(&inner_indent_str);
749 result.push_str(visitor.buffer.to_string().trim());
750 result.push_str(&outer_indent_str);
753 if result.ends_with('{') && !context.config.empty_item_single_line() {
754 result.push_str(&sep);
764 fn is_impl_single_line(
765 context: &RewriteContext,
766 items: &[ast::ImplItem],
768 where_clause_str: &str,
771 let snippet = context.snippet(item.span);
772 let open_pos = snippet.find_uncommented("{")? + 1;
775 context.config.empty_item_single_line()
777 && !result.contains('\n')
778 && result.len() + where_clause_str.len() <= context.config.max_width()
779 && !contains_comment(&snippet[open_pos..]),
783 fn format_impl_ref_and_type(
784 context: &RewriteContext,
787 ) -> Option<String> {
788 if let ast::ItemKind::Impl(
798 let mut result = String::with_capacity(128);
800 result.push_str(&format_visibility(context, &item.vis));
801 result.push_str(format_defaultness(defaultness));
802 result.push_str(format_unsafety(unsafety));
804 let lo = context.snippet_provider.span_after(item.span, "impl");
805 let hi = match *trait_ref {
806 Some(ref tr) => tr.path.span.lo(),
807 None => self_ty.span.lo(),
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, mk_sp(lo, hi))?;
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 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 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 fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
969 if let ast::ItemKind::Trait(
977 let mut result = String::with_capacity(128);
978 let header = format!(
980 format_visibility(context, &item.vis),
981 format_unsafety(unsafety),
982 format_auto(is_auto),
984 result.push_str(&header);
986 let body_lo = context.snippet_provider.span_after(item.span, "{");
988 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
989 let generics_str = rewrite_generics(
991 rewrite_ident(context, item.ident),
994 mk_sp(item.span.lo(), body_lo),
996 result.push_str(&generics_str);
998 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
999 if !generic_bounds.is_empty() {
1000 let ident_hi = context
1002 .span_after(item.span, &item.ident.as_str());
1003 let bound_hi = generic_bounds.last().unwrap().span().hi();
1004 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1005 if contains_comment(snippet) {
1009 result = rewrite_assign_rhs_with(
1014 RhsTactics::ForceNextLineWithoutIndent,
1018 // Rewrite where clause.
1019 if !generics.where_clause.predicates.is_empty() {
1020 let where_density = if context.config.indent_style() == IndentStyle::Block {
1026 let where_budget = context.budget(last_line_width(&result));
1027 let pos_before_where = if generic_bounds.is_empty() {
1028 generics.where_clause.span.lo()
1030 generic_bounds[generic_bounds.len() - 1].span().hi()
1032 let option = WhereClauseOption::snuggled(&generics_str);
1033 let where_clause_str = rewrite_where_clause(
1035 &generics.where_clause,
1036 context.config.brace_style(),
1037 Shape::legacy(where_budget, offset.block_only()),
1045 // If the where clause cannot fit on the same line,
1046 // put the where clause on a new line
1047 if !where_clause_str.contains('\n')
1048 && last_line_width(&result) + where_clause_str.len() + offset.width()
1049 > context.config.comment_width()
1051 let width = offset.block_indent + context.config.tab_spaces() - 1;
1052 let where_indent = Indent::new(0, width);
1053 result.push_str(&where_indent.to_string_with_newline(context.config));
1055 result.push_str(&where_clause_str);
1057 let item_snippet = context.snippet(item.span);
1058 if let Some(lo) = item_snippet.find('/') {
1060 let comment_hi = body_lo - BytePos(1);
1061 let comment_lo = item.span.lo() + BytePos(lo as u32);
1062 if comment_lo < comment_hi {
1063 match recover_missing_comment_in_span(
1064 mk_sp(comment_lo, comment_hi),
1065 Shape::indented(offset, context.config),
1067 last_line_width(&result),
1069 Some(ref missing_comment) if !missing_comment.is_empty() => {
1070 result.push_str(missing_comment);
1078 match context.config.brace_style() {
1079 _ if last_line_contains_single_line_comment(&result)
1080 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1082 result.push_str(&offset.to_string_with_newline(context.config));
1084 BraceStyle::AlwaysNextLine => {
1085 result.push_str(&offset.to_string_with_newline(context.config));
1087 BraceStyle::PreferSameLine => result.push(' '),
1088 BraceStyle::SameLineWhere => {
1089 if result.contains('\n')
1090 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1092 result.push_str(&offset.to_string_with_newline(context.config));
1100 let snippet = context.snippet(item.span);
1101 let open_pos = snippet.find_uncommented("{")? + 1;
1103 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1104 let mut visitor = FmtVisitor::from_context(context);
1105 visitor.block_indent = offset.block_only().block_indent(context.config);
1106 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1108 for item in trait_items {
1109 visitor.visit_trait_item(item);
1112 visitor.format_missing(item.span.hi() - BytePos(1));
1114 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1115 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1117 result.push_str(&inner_indent_str);
1118 result.push_str(visitor.buffer.to_string().trim());
1119 result.push_str(&outer_indent_str);
1120 } else if result.contains('\n') {
1131 pub fn format_trait_alias(
1132 context: &RewriteContext,
1134 generics: &ast::Generics,
1135 generic_bounds: &ast::GenericBounds,
1137 ) -> Option<String> {
1138 let alias = rewrite_ident(context, ident);
1139 // 6 = "trait ", 2 = " ="
1140 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1141 let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
1142 let lhs = format!("trait {} =", generics_str);
1144 rewrite_assign_rhs(context, lhs, generic_bounds, shape.sub_width(1)?).map(|s| s + ";")
1147 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1148 let header_str = format_header(context, p.prefix, p.ident, p.vis);
1149 let generics_str = if let Some(generics) = p.generics {
1150 let hi = if generics.where_clause.predicates.is_empty() {
1153 generics.where_clause.span.hi()
1158 context.config.brace_style(),
1161 mk_sp(generics.span.lo(), hi),
1162 last_line_width(&header_str),
1167 Some(format!("{}{};", header_str, generics_str))
1170 pub fn format_struct_struct(
1171 context: &RewriteContext,
1172 struct_parts: &StructParts,
1173 fields: &[ast::StructField],
1175 one_line_width: Option<usize>,
1176 ) -> Option<String> {
1177 let mut result = String::with_capacity(1024);
1178 let span = struct_parts.span;
1180 let header_str = struct_parts.format_header(context);
1181 result.push_str(&header_str);
1183 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1184 let body_lo = context.snippet_provider.span_after(span, "{");
1186 let generics_str = match struct_parts.generics {
1187 Some(g) => format_generics(
1190 context.config.brace_style(),
1191 if fields.is_empty() {
1192 BracePos::ForceSameLine
1197 mk_sp(header_hi, body_lo),
1198 last_line_width(&result),
1201 // 3 = ` {}`, 2 = ` {`.
1202 let overhead = if fields.is_empty() { 3 } else { 2 };
1203 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1204 || context.config.max_width() < overhead + result.len()
1206 format!("\n{}{{", offset.block_only().to_string(context.config))
1213 let overhead = if fields.is_empty() { 1 } else { 0 };
1214 let total_width = result.len() + generics_str.len() + overhead;
1215 if !generics_str.is_empty()
1216 && !generics_str.contains('\n')
1217 && total_width > context.config.max_width()
1220 result.push_str(&offset.to_string(context.config));
1221 result.push_str(generics_str.trim_left());
1223 result.push_str(&generics_str);
1226 if fields.is_empty() {
1227 let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1228 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1229 return Some(result);
1233 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1234 let one_line_budget =
1235 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1237 let items_str = rewrite_with_alignment(
1240 Shape::indented(offset, context.config).sub_width(1)?,
1241 mk_sp(body_lo, span.hi()),
1245 if !items_str.contains('\n')
1246 && !result.contains('\n')
1247 && items_str.len() <= one_line_budget
1248 && !last_line_contains_single_line_comment(&items_str)
1250 Some(format!("{} {} }}", result, items_str))
1256 .block_indent(context.config)
1257 .to_string(context.config),
1259 offset.to_string(context.config)
1264 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1266 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1267 _ => default_span.lo(),
1271 // Format tuple or struct without any fields. We need to make sure that the comments
1272 // inside the delimiters are preserved.
1273 fn format_empty_struct_or_tuple(
1274 context: &RewriteContext,
1277 result: &mut String,
1281 // 3 = " {}" or "();"
1282 let used_width = last_line_used_width(&result, offset.width()) + 3;
1283 if used_width > context.config.max_width() {
1284 result.push_str(&offset.to_string_with_newline(context.config))
1286 result.push_str(opener);
1287 match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1288 Some(ref s) if s.is_empty() => (),
1290 if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1291 let nested_indent_str = offset
1292 .block_indent(context.config)
1293 .to_string_with_newline(context.config);
1294 result.push_str(&nested_indent_str);
1297 if last_line_contains_single_line_comment(s) {
1298 result.push_str(&offset.to_string_with_newline(context.config));
1301 None => result.push_str(context.snippet(span)),
1303 result.push_str(closer);
1306 fn format_tuple_struct(
1307 context: &RewriteContext,
1308 struct_parts: &StructParts,
1309 fields: &[ast::StructField],
1311 ) -> Option<String> {
1312 let mut result = String::with_capacity(1024);
1313 let span = struct_parts.span;
1315 let header_str = struct_parts.format_header(context);
1316 result.push_str(&header_str);
1318 let body_lo = if fields.is_empty() {
1319 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1322 .span_after(mk_sp(lo, span.hi()), "(")
1326 let body_hi = if fields.is_empty() {
1329 .span_after(mk_sp(body_lo, span.hi()), ")")
1331 // This is a dirty hack to work around a missing `)` from the span of the last field.
1332 let last_arg_span = fields[fields.len() - 1].span;
1333 if context.snippet(last_arg_span).ends_with(')') {
1338 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1342 let where_clause_str = match struct_parts.generics {
1344 let budget = context.budget(last_line_width(&header_str));
1345 let shape = Shape::legacy(budget, offset);
1346 let g_span = mk_sp(span.lo(), body_lo);
1347 let generics_str = rewrite_generics(context, "", generics, shape, g_span)?;
1348 result.push_str(&generics_str);
1350 let where_budget = context.budget(last_line_width(&result));
1351 let option = WhereClauseOption::new(true, false);
1352 rewrite_where_clause(
1354 &generics.where_clause,
1355 context.config.brace_style(),
1356 Shape::legacy(where_budget, offset.block_only()),
1357 Density::Compressed,
1365 None => "".to_owned(),
1368 if fields.is_empty() {
1369 let body_hi = context
1371 .span_before(mk_sp(body_lo, span.hi()), ")");
1372 let inner_span = mk_sp(body_lo, body_hi);
1373 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1375 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1376 let fields = &fields.iter().collect::<Vec<_>>();
1377 result = overflow::rewrite_with_parens(
1383 context.config.width_heuristics().fn_call_width,
1388 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1389 && (result.contains('\n')
1390 || offset.block_indent + result.len() + where_clause_str.len() + 1
1391 > context.config.max_width())
1393 // We need to put the where clause on a new line, but we didn't
1394 // know that earlier, so the where clause will not be indented properly.
1397 &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1400 result.push_str(&where_clause_str);
1405 pub fn rewrite_type_alias(
1406 context: &RewriteContext,
1410 generics: &ast::Generics,
1411 vis: &ast::Visibility,
1413 ) -> Option<String> {
1414 let mut result = String::with_capacity(128);
1416 result.push_str(&format_visibility(context, vis));
1417 result.push_str("type ");
1420 let g_shape = Shape::indented(indent, context.config)
1421 .offset_left(result.len())?
1424 context.snippet_provider.span_after(span, "type"),
1427 let generics_str = rewrite_generics(
1429 rewrite_ident(context, ident),
1434 result.push_str(&generics_str);
1436 let where_budget = context.budget(last_line_width(&result));
1437 let option = WhereClauseOption::snuggled(&result);
1438 let where_clause_str = rewrite_where_clause(
1440 &generics.where_clause,
1441 context.config.brace_style(),
1442 Shape::legacy(where_budget, indent),
1450 result.push_str(&where_clause_str);
1451 if where_clause_str.is_empty() {
1452 result.push_str(" =");
1454 result.push_str(&format!(
1456 indent.to_string_with_newline(context.config)
1461 let ty_shape = Shape::indented(indent, context.config).sub_width(1)?;
1462 rewrite_assign_rhs(context, result, ty, ty_shape).map(|s| s + ";")
1465 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1467 if config.space_before_colon() { " " } else { "" },
1468 if config.space_after_colon() { " " } else { "" },
1472 pub fn rewrite_struct_field_prefix(
1473 context: &RewriteContext,
1474 field: &ast::StructField,
1475 ) -> Option<String> {
1476 let vis = format_visibility(context, &field.vis);
1477 let type_annotation_spacing = type_annotation_spacing(context.config);
1478 Some(match field.ident {
1479 Some(name) => format!(
1482 rewrite_ident(context, name),
1483 type_annotation_spacing.0
1485 None => format!("{}", vis),
1489 impl Rewrite for ast::StructField {
1490 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1491 rewrite_struct_field(context, self, shape, 0)
1495 pub fn rewrite_struct_field(
1496 context: &RewriteContext,
1497 field: &ast::StructField,
1499 lhs_max_width: usize,
1500 ) -> Option<String> {
1501 if contains_skip(&field.attrs) {
1502 return Some(context.snippet(field.span()).to_owned());
1505 let type_annotation_spacing = type_annotation_spacing(context.config);
1506 let prefix = rewrite_struct_field_prefix(context, field)?;
1508 let attrs_str = field.attrs.rewrite(context, shape)?;
1509 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1510 let missing_span = if field.attrs.is_empty() {
1511 mk_sp(field.span.lo(), field.span.lo())
1513 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1515 let mut spacing = String::from(if field.ident.is_some() {
1516 type_annotation_spacing.1
1520 // Try to put everything on a single line.
1521 let attr_prefix = combine_strs_with_missing_comments(
1529 let overhead = last_line_width(&attr_prefix);
1530 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1531 for _ in 0..lhs_offset {
1534 // In this extreme case we will be missing a space betweeen an attribute and a field.
1535 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1539 .offset_left(overhead + spacing.len())
1540 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1541 if let Some(ref ty) = orig_ty {
1542 if !ty.contains('\n') {
1543 return Some(attr_prefix + &spacing + ty);
1547 let is_prefix_empty = prefix.is_empty();
1548 // We must use multiline. We are going to put attributes and a field on different lines.
1549 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1550 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1551 let field_str = if is_prefix_empty {
1552 field_str.trim_left()
1556 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1559 pub struct StaticParts<'a> {
1561 vis: &'a ast::Visibility,
1564 mutability: ast::Mutability,
1565 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1566 defaultness: Option<ast::Defaultness>,
1570 impl<'a> StaticParts<'a> {
1571 pub fn from_item(item: &'a ast::Item) -> Self {
1572 let (prefix, ty, mutability, expr) = match item.node {
1573 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1574 ast::ItemKind::Const(ref ty, ref expr) => {
1575 ("const", ty, ast::Mutability::Immutable, expr)
1577 _ => unreachable!(),
1585 expr_opt: Some(expr),
1591 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1592 let (ty, expr_opt) = match ti.node {
1593 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1594 _ => unreachable!(),
1598 vis: &DEFAULT_VISIBILITY,
1601 mutability: ast::Mutability::Immutable,
1602 expr_opt: expr_opt.as_ref(),
1608 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1609 let (ty, expr) = match ii.node {
1610 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1611 _ => unreachable!(),
1618 mutability: ast::Mutability::Immutable,
1619 expr_opt: Some(expr),
1620 defaultness: Some(ii.defaultness),
1627 context: &RewriteContext,
1628 static_parts: &StaticParts,
1630 ) -> Option<String> {
1631 let colon = colon_spaces(
1632 context.config.space_before_colon(),
1633 context.config.space_after_colon(),
1635 let mut prefix = format!(
1637 format_visibility(context, static_parts.vis),
1638 static_parts.defaultness.map_or("", format_defaultness),
1639 static_parts.prefix,
1640 format_mutability(static_parts.mutability),
1646 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1647 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1648 Some(ty_str) => ty_str,
1650 if prefix.ends_with(' ') {
1653 let nested_indent = offset.block_indent(context.config);
1654 let nested_shape = Shape::indented(nested_indent, context.config);
1655 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1658 nested_indent.to_string_with_newline(context.config),
1664 if let Some(expr) = static_parts.expr_opt {
1665 let lhs = format!("{}{} =", prefix, ty_str);
1667 let remaining_width = context.budget(offset.block_indent + 1);
1672 Shape::legacy(remaining_width, offset.block_only()),
1673 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1674 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1676 Some(format!("{}{};", prefix, ty_str))
1680 pub fn rewrite_associated_type(
1682 ty_opt: Option<&ptr::P<ast::Ty>>,
1683 generic_bounds_opt: Option<&ast::GenericBounds>,
1684 context: &RewriteContext,
1686 ) -> Option<String> {
1687 let prefix = format!("type {}", rewrite_ident(context, ident));
1689 let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
1690 if bounds.is_empty() {
1694 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1695 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1701 if let Some(ty) = ty_opt {
1703 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1704 let lhs = format!("{}{} =", prefix, type_bounds_str);
1705 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1707 Some(format!("{}{};", prefix, type_bounds_str))
1711 pub fn rewrite_associated_impl_type(
1713 defaultness: ast::Defaultness,
1714 ty_opt: Option<&ptr::P<ast::Ty>>,
1715 generic_bounds_opt: Option<&ast::GenericBounds>,
1716 context: &RewriteContext,
1718 ) -> Option<String> {
1719 let result = rewrite_associated_type(ident, ty_opt, generic_bounds_opt, context, indent)?;
1722 ast::Defaultness::Default => Some(format!("default {}", result)),
1727 impl Rewrite for ast::FunctionRetTy {
1728 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1730 ast::FunctionRetTy::Default(_) => Some(String::new()),
1731 ast::FunctionRetTy::Ty(ref ty) => {
1732 let inner_width = shape.width.checked_sub(3)?;
1733 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1734 .map(|r| format!("-> {}", r))
1740 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1742 ast::TyKind::Infer => {
1743 let original = context.snippet(ty.span);
1750 impl Rewrite for ast::Arg {
1751 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1752 if is_named_arg(self) {
1753 let mut result = self
1755 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1757 if !is_empty_infer(context, &*self.ty) {
1758 if context.config.space_before_colon() {
1759 result.push_str(" ");
1761 result.push_str(":");
1762 if context.config.space_after_colon() {
1763 result.push_str(" ");
1765 let overhead = last_line_width(&result);
1766 let max_width = shape.width.checked_sub(overhead)?;
1769 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1770 result.push_str(&ty_str);
1775 self.ty.rewrite(context, shape)
1780 fn rewrite_explicit_self(
1781 explicit_self: &ast::ExplicitSelf,
1783 context: &RewriteContext,
1784 ) -> Option<String> {
1785 match explicit_self.node {
1786 ast::SelfKind::Region(lt, m) => {
1787 let mut_str = format_mutability(m);
1790 let lifetime_str = l.rewrite(
1792 Shape::legacy(context.config.max_width(), Indent::empty()),
1794 Some(format!("&{} {}self", lifetime_str, mut_str))
1796 None => Some(format!("&{}self", mut_str)),
1799 ast::SelfKind::Explicit(ref ty, _) => {
1800 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1802 let mutability = explicit_self_mutability(&args[0]);
1803 let type_str = ty.rewrite(
1805 Shape::legacy(context.config.max_width(), Indent::empty()),
1810 format_mutability(mutability),
1814 ast::SelfKind::Value(_) => {
1815 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1817 let mutability = explicit_self_mutability(&args[0]);
1819 Some(format!("{}self", format_mutability(mutability)))
1824 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1825 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1826 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1827 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1834 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1835 if is_named_arg(arg) {
1842 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1844 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1845 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1846 _ => arg.ty.span.hi(),
1850 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1851 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1852 ident != symbol::keywords::Invalid.ident()
1858 // Return type is (result, force_new_line_for_brace)
1860 context: &RewriteContext,
1865 newline_brace: bool,
1867 ) -> Option<(String, bool)> {
1868 let mut force_new_line_for_brace = false;
1870 let where_clause = &fn_sig.generics.where_clause;
1872 let mut result = String::with_capacity(1024);
1873 result.push_str(&fn_sig.to_str(context));
1876 result.push_str("fn ");
1879 let overhead = if has_body && !newline_brace {
1886 let used_width = last_line_used_width(&result, indent.width());
1887 let one_line_budget = context.budget(used_width + overhead);
1889 width: one_line_budget,
1893 let fd = fn_sig.decl;
1894 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1895 let generics_str = rewrite_generics(
1897 rewrite_ident(context, ident),
1902 result.push_str(&generics_str);
1904 let snuggle_angle_bracket = generics_str
1907 .map_or(false, |l| l.trim_left().len() == 1);
1909 // Note that the width and indent don't really matter, we'll re-layout the
1910 // return type later anyway.
1913 .rewrite(context, Shape::indented(indent, context.config))?;
1915 let multi_line_ret_str = ret_str.contains('\n');
1916 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1919 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1930 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1931 one_line_budget, multi_line_budget, arg_indent
1934 // Check if vertical layout was forced.
1935 if one_line_budget == 0 {
1936 if snuggle_angle_bracket {
1939 result.push_str("(");
1940 if context.config.indent_style() == IndentStyle::Visual {
1941 result.push_str(&arg_indent.to_string_with_newline(context.config));
1948 // Skip `pub(crate)`.
1949 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
1950 // A conservative estimation, to goal is to be over all parens in generics
1951 let args_start = fn_sig
1956 .map_or(lo_after_visibility, |param| param.span().hi());
1957 let args_end = if fd.inputs.is_empty() {
1960 .span_after(mk_sp(args_start, span.hi()), ")")
1962 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1963 context.snippet_provider.span_after(last_span, ")")
1965 let args_span = mk_sp(
1968 .span_after(mk_sp(args_start, span.hi()), "("),
1971 let arg_str = rewrite_args(
1974 fd.get_self().as_ref(),
1981 generics_str.contains('\n'),
1984 let put_args_in_block = match context.config.indent_style() {
1985 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1987 } && !fd.inputs.is_empty();
1989 let mut args_last_line_contains_comment = false;
1990 if put_args_in_block {
1991 arg_indent = indent.block_indent(context.config);
1992 result.push_str(&arg_indent.to_string_with_newline(context.config));
1993 result.push_str(&arg_str);
1994 result.push_str(&indent.to_string_with_newline(context.config));
1997 result.push_str(&arg_str);
1998 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1999 // Put the closing brace on the next line if it overflows the max width.
2001 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
2004 // If the last line of args contains comment, we cannot put the closing paren
2005 // on the same line.
2009 .map_or(false, |last_line| last_line.contains("//"))
2011 args_last_line_contains_comment = true;
2012 result.push_str(&arg_indent.to_string_with_newline(context.config));
2018 if let ast::FunctionRetTy::Ty(..) = fd.output {
2019 let ret_should_indent = match context.config.indent_style() {
2020 // If our args are block layout then we surely must have space.
2021 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
2022 _ if args_last_line_contains_comment => false,
2023 _ if result.contains('\n') || multi_line_ret_str => true,
2025 // If the return type would push over the max width, then put the return type on
2026 // a new line. With the +1 for the signature length an additional space between
2027 // the closing parenthesis of the argument and the arrow '->' is considered.
2028 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2030 // If there is no where clause, take into account the space after the return type
2032 if where_clause.predicates.is_empty() {
2036 sig_length > context.config.max_width()
2039 let ret_indent = if ret_should_indent {
2040 let indent = if arg_str.is_empty() {
2041 // Aligning with non-existent args looks silly.
2042 force_new_line_for_brace = true;
2045 // FIXME: we might want to check that using the arg indent
2046 // doesn't blow our budget, and if it does, then fallback to
2047 // the where clause indent.
2051 result.push_str(&indent.to_string_with_newline(context.config));
2055 Indent::new(indent.block_indent, last_line_width(&result))
2058 if multi_line_ret_str || ret_should_indent {
2059 // Now that we know the proper indent and width, we need to
2060 // re-layout the return type.
2063 .rewrite(context, Shape::indented(ret_indent, context.config))?;
2064 result.push_str(&ret_str);
2066 result.push_str(&ret_str);
2069 // Comment between return type and the end of the decl.
2070 let snippet_lo = fd.output.span().hi();
2071 if where_clause.predicates.is_empty() {
2072 let snippet_hi = span.hi();
2073 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2074 // Try to preserve the layout of the original snippet.
2075 let original_starts_with_newline = snippet
2077 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2078 let original_ends_with_newline = snippet
2079 .rfind(|c| c != ' ')
2080 .map_or(false, |i| snippet[i..].ends_with('\n'));
2081 let snippet = snippet.trim();
2082 if !snippet.is_empty() {
2083 result.push(if original_starts_with_newline {
2088 result.push_str(snippet);
2089 if original_ends_with_newline {
2090 force_new_line_for_brace = true;
2096 let pos_before_where = match fd.output {
2097 ast::FunctionRetTy::Default(..) => args_span.hi(),
2098 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2101 let is_args_multi_lined = arg_str.contains('\n');
2103 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2104 let where_clause_str = rewrite_where_clause(
2107 context.config.brace_style(),
2108 Shape::indented(indent, context.config),
2114 is_args_multi_lined,
2116 // If there are neither where clause nor return type, we may be missing comments between
2118 if where_clause_str.is_empty() {
2119 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2120 match recover_missing_comment_in_span(
2121 mk_sp(args_span.hi(), ret_span.hi()),
2124 last_line_width(&result),
2126 Some(ref missing_comment) if !missing_comment.is_empty() => {
2127 result.push_str(missing_comment);
2128 force_new_line_for_brace = true;
2135 result.push_str(&where_clause_str);
2137 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2138 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2139 Some((result, force_new_line_for_brace))
2142 #[derive(Copy, Clone)]
2143 struct WhereClauseOption {
2144 suppress_comma: bool, // Force no trailing comma
2145 snuggle: bool, // Do not insert newline before `where`
2146 compress_where: bool, // Try single line where clause instead of vertical layout
2149 impl WhereClauseOption {
2150 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2154 compress_where: false,
2158 pub fn snuggled(current: &str) -> WhereClauseOption {
2160 suppress_comma: false,
2161 snuggle: last_line_width(current) == 1,
2162 compress_where: false,
2166 pub fn suppress_comma(&mut self) {
2167 self.suppress_comma = true
2170 pub fn compress_where(&mut self) {
2171 self.compress_where = true
2174 pub fn snuggle(&mut self) {
2180 context: &RewriteContext,
2182 explicit_self: Option<&ast::ExplicitSelf>,
2183 one_line_budget: usize,
2184 multi_line_budget: usize,
2189 generics_str_contains_newline: bool,
2190 ) -> Option<String> {
2191 let mut arg_item_strs = args
2193 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2194 .collect::<Option<Vec<_>>>()?;
2196 // Account for sugary self.
2197 // FIXME: the comment for the self argument is dropped. This is blocked
2198 // on rust issue #27522.
2199 let min_args = explicit_self
2200 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2201 .map_or(1, |self_str| {
2202 arg_item_strs[0] = self_str;
2206 // Comments between args.
2207 let mut arg_items = Vec::new();
2209 arg_items.push(ListItem::from_str(""));
2212 // FIXME(#21): if there are no args, there might still be a comment, but
2213 // without spans for the comment or parens, there is no chance of
2214 // getting it right. You also don't get to put a comment on self, unless
2216 if args.len() >= min_args || variadic {
2217 let comment_span_start = if min_args == 2 {
2218 let second_arg_start = if arg_has_pattern(&args[1]) {
2219 args[1].pat.span.lo()
2221 args[1].ty.span.lo()
2223 let reduced_span = mk_sp(span.lo(), second_arg_start);
2225 context.snippet_provider.span_after_last(reduced_span, ",")
2230 enum ArgumentKind<'a> {
2231 Regular(&'a ast::Arg),
2235 let variadic_arg = if variadic {
2236 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2237 let variadic_start =
2238 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2239 Some(ArgumentKind::Variadic(variadic_start))
2244 let more_items = itemize_list(
2245 context.snippet_provider,
2246 args[min_args - 1..]
2248 .map(ArgumentKind::Regular)
2249 .chain(variadic_arg),
2253 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2254 ArgumentKind::Variadic(start) => start,
2257 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2258 ArgumentKind::Variadic(start) => start + BytePos(3),
2261 ArgumentKind::Regular(..) => None,
2262 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2269 arg_items.extend(more_items);
2272 let fits_in_one_line = !generics_str_contains_newline
2273 && (arg_items.is_empty()
2274 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2276 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2277 item.item = Some(arg);
2280 let last_line_ends_with_comment = arg_items
2283 .and_then(|item| item.post_comment.as_ref())
2284 .map_or(false, |s| s.trim().starts_with("//"));
2286 let (indent, trailing_comma) = match context.config.indent_style() {
2287 IndentStyle::Block if fits_in_one_line => {
2288 (indent.block_indent(context.config), SeparatorTactic::Never)
2290 IndentStyle::Block => (
2291 indent.block_indent(context.config),
2292 context.config.trailing_comma(),
2294 IndentStyle::Visual if last_line_ends_with_comment => {
2295 (arg_indent, context.config.trailing_comma())
2297 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2300 let tactic = definitive_tactic(
2302 context.config.fn_args_density().to_list_tactic(),
2306 let budget = match tactic {
2307 DefinitiveListTactic::Horizontal => one_line_budget,
2308 _ => multi_line_budget,
2311 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2313 let fmt = ListFormatting {
2316 trailing_separator: if variadic {
2317 SeparatorTactic::Never
2321 separator_place: SeparatorPlace::Back,
2322 shape: Shape::legacy(budget, indent),
2323 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2324 preserve_newline: true,
2326 config: context.config,
2329 write_list(&arg_items, &fmt)
2332 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2333 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2334 ident != symbol::keywords::Invalid.ident()
2340 fn compute_budgets_for_args(
2341 context: &RewriteContext,
2345 newline_brace: bool,
2347 force_vertical_layout: bool,
2348 ) -> Option<((usize, usize, Indent))> {
2350 "compute_budgets_for_args {} {:?}, {}, {}",
2356 // Try keeping everything on the same line.
2357 if !result.contains('\n') && !force_vertical_layout {
2358 // 2 = `()`, 3 = `() `, space is before ret_string.
2359 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2360 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2370 let one_line_budget = context.budget(used_space);
2372 if one_line_budget > 0 {
2374 let (indent, multi_line_budget) = match context.config.indent_style() {
2375 IndentStyle::Block => {
2376 let indent = indent.block_indent(context.config);
2377 (indent, context.budget(indent.width() + 1))
2379 IndentStyle::Visual => {
2380 let indent = indent + result.len() + 1;
2381 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2382 (indent, context.budget(multi_line_overhead))
2386 return Some((one_line_budget, multi_line_budget, indent));
2390 // Didn't work. we must force vertical layout and put args on a newline.
2391 let new_indent = indent.block_indent(context.config);
2392 let used_space = match context.config.indent_style() {
2394 IndentStyle::Block => new_indent.width() + 1,
2395 // Account for `)` and possibly ` {`.
2396 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2398 Some((0, context.budget(used_space), new_indent))
2401 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2402 let predicate_count = where_clause.predicates.len();
2404 if config.where_single_line() && predicate_count == 1 {
2407 let brace_style = config.brace_style();
2409 brace_style == BraceStyle::AlwaysNextLine
2410 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2413 fn rewrite_generics(
2414 context: &RewriteContext,
2416 generics: &ast::Generics,
2419 ) -> Option<String> {
2420 // FIXME: convert bounds to where clauses where they get too big or if
2421 // there is a where clause at all.
2423 if generics.params.is_empty() {
2424 return Some(ident.to_owned());
2427 let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>();
2428 overflow::rewrite_with_angle_brackets(context, ident, params, shape, span)
2431 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2432 match config.indent_style() {
2433 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2434 IndentStyle::Block => {
2438 .block_indent(config.tab_spaces())
2439 .with_max_width(config)
2445 fn rewrite_where_clause_rfc_style(
2446 context: &RewriteContext,
2447 where_clause: &ast::WhereClause,
2450 span_end: Option<BytePos>,
2451 span_end_before_where: BytePos,
2452 where_clause_option: WhereClauseOption,
2453 is_args_multi_line: bool,
2454 ) -> Option<String> {
2455 let block_shape = shape.block().with_max_width(context.config);
2457 let (span_before, span_after) =
2458 missing_span_before_after_where(span_end_before_where, where_clause);
2459 let (comment_before, comment_after) =
2460 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2462 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2465 block_shape.indent.to_string_with_newline(context.config)
2468 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2470 let clause_shape = clause_shape.sub_width(1)?;
2471 // each clause on one line, trailing comma (except if suppress_comma)
2472 let span_start = where_clause.predicates[0].span().lo();
2473 // If we don't have the start of the next span, then use the end of the
2474 // predicates, but that means we miss comments.
2475 let len = where_clause.predicates.len();
2476 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2477 let span_end = span_end.unwrap_or(end_of_preds);
2478 let items = itemize_list(
2479 context.snippet_provider,
2480 where_clause.predicates.iter(),
2483 |pred| pred.span().lo(),
2484 |pred| pred.span().hi(),
2485 |pred| pred.rewrite(context, clause_shape),
2490 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2491 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2492 SeparatorTactic::Never
2494 context.config.trailing_comma()
2497 // shape should be vertical only and only if we have `where_single_line` option enabled
2498 // and the number of items of the where clause is equal to 1
2499 let shape_tactic = if where_single_line {
2500 DefinitiveListTactic::Horizontal
2502 DefinitiveListTactic::Vertical
2505 let fmt = ListFormatting {
2506 tactic: shape_tactic,
2508 trailing_separator: comma_tactic,
2509 separator_place: SeparatorPlace::Back,
2510 shape: clause_shape,
2511 ends_with_newline: true,
2512 preserve_newline: true,
2514 config: context.config,
2516 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2518 let comment_separator = |comment: &str, shape: Shape| {
2519 if comment.is_empty() {
2522 shape.indent.to_string_with_newline(context.config)
2525 let newline_before_where = comment_separator(&comment_before, shape);
2526 let newline_after_where = comment_separator(&comment_after, clause_shape);
2529 let clause_sep = if where_clause_option.compress_where
2530 && comment_before.is_empty()
2531 && comment_after.is_empty()
2532 && !preds_str.contains('\n')
2533 && 6 + preds_str.len() <= shape.width || where_single_line
2537 clause_shape.indent.to_string_with_newline(context.config)
2540 "{}{}{}where{}{}{}{}",
2543 newline_before_where,
2544 newline_after_where,
2551 fn rewrite_where_clause(
2552 context: &RewriteContext,
2553 where_clause: &ast::WhereClause,
2554 brace_style: BraceStyle,
2558 span_end: Option<BytePos>,
2559 span_end_before_where: BytePos,
2560 where_clause_option: WhereClauseOption,
2561 is_args_multi_line: bool,
2562 ) -> Option<String> {
2563 if where_clause.predicates.is_empty() {
2564 return Some(String::new());
2567 if context.config.indent_style() == IndentStyle::Block {
2568 return rewrite_where_clause_rfc_style(
2574 span_end_before_where,
2575 where_clause_option,
2580 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2582 let offset = match context.config.indent_style() {
2583 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2584 // 6 = "where ".len()
2585 IndentStyle::Visual => shape.indent + extra_indent + 6,
2587 // FIXME: if indent_style != Visual, then the budgets below might
2588 // be out by a char or two.
2590 let budget = context.config.max_width() - offset.width();
2591 let span_start = where_clause.predicates[0].span().lo();
2592 // If we don't have the start of the next span, then use the end of the
2593 // predicates, but that means we miss comments.
2594 let len = where_clause.predicates.len();
2595 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2596 let span_end = span_end.unwrap_or(end_of_preds);
2597 let items = itemize_list(
2598 context.snippet_provider,
2599 where_clause.predicates.iter(),
2602 |pred| pred.span().lo(),
2603 |pred| pred.span().hi(),
2604 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2609 let item_vec = items.collect::<Vec<_>>();
2610 // FIXME: we don't need to collect here
2611 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2613 let mut comma_tactic = context.config.trailing_comma();
2614 // Kind of a hack because we don't usually have trailing commas in where clauses.
2615 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2616 comma_tactic = SeparatorTactic::Never;
2619 let fmt = ListFormatting {
2622 trailing_separator: comma_tactic,
2623 separator_place: SeparatorPlace::Back,
2624 shape: Shape::legacy(budget, offset),
2625 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2626 preserve_newline: true,
2628 config: context.config,
2630 let preds_str = write_list(&item_vec, &fmt)?;
2632 let end_length = if terminator == "{" {
2633 // If the brace is on the next line we don't need to count it otherwise it needs two
2636 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2637 BraceStyle::PreferSameLine => 2,
2639 } else if terminator == "=" {
2644 if density == Density::Tall
2645 || preds_str.contains('\n')
2646 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2650 (shape.indent + extra_indent).to_string(context.config),
2654 Some(format!(" where {}", preds_str))
2658 fn missing_span_before_after_where(
2659 before_item_span_end: BytePos,
2660 where_clause: &ast::WhereClause,
2662 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2664 let pos_after_where = where_clause.span.lo() + BytePos(5);
2665 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2666 (missing_span_before, missing_span_after)
2669 fn rewrite_comments_before_after_where(
2670 context: &RewriteContext,
2671 span_before_where: Span,
2672 span_after_where: Span,
2674 ) -> Option<(String, String)> {
2675 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2676 let after_comment = rewrite_missing_comment(
2678 shape.block_indent(context.config.tab_spaces()),
2681 Some((before_comment, after_comment))
2685 context: &RewriteContext,
2688 vis: &ast::Visibility,
2692 format_visibility(context, vis),
2694 rewrite_ident(context, ident)
2698 #[derive(PartialEq, Eq, Clone, Copy)]
2706 context: &RewriteContext,
2707 generics: &ast::Generics,
2708 brace_style: BraceStyle,
2709 brace_pos: BracePos,
2713 ) -> Option<String> {
2714 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2715 let mut result = rewrite_generics(context, "", generics, shape, span)?;
2717 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2718 let budget = context.budget(last_line_used_width(&result, offset.width()));
2719 let mut option = WhereClauseOption::snuggled(&result);
2720 if brace_pos == BracePos::None {
2721 option.suppress_comma = true;
2723 // If the generics are not parameterized then generics.span.hi() == 0,
2724 // so we use span.lo(), which is the position after `struct Foo`.
2725 let span_end_before_where = if !generics.params.is_empty() {
2730 let where_clause_str = rewrite_where_clause(
2732 &generics.where_clause,
2734 Shape::legacy(budget, offset.block_only()),
2738 span_end_before_where,
2742 result.push_str(&where_clause_str);
2743 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2744 || (generics.where_clause.predicates.is_empty()
2745 && trimmed_last_line_width(&result) == 1)
2747 brace_pos == BracePos::ForceSameLine
2748 || trimmed_last_line_width(&result) == 1
2749 || brace_style != BraceStyle::AlwaysNextLine
2751 if brace_pos == BracePos::None {
2752 return Some(result);
2754 let total_used_width = last_line_used_width(&result, used_width);
2755 let remaining_budget = context.budget(total_used_width);
2756 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2757 // and hence we take the closer into account as well for one line budget.
2758 // We assume that the closer has the same length as the opener.
2759 let overhead = if brace_pos == BracePos::ForceSameLine {
2766 let forbid_same_line_brace = overhead > remaining_budget;
2767 if !forbid_same_line_brace && same_line_brace {
2771 result.push_str(&offset.block_only().to_string(context.config));
2778 impl Rewrite for ast::ForeignItem {
2779 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2780 let attrs_str = self.attrs.rewrite(context, shape)?;
2781 // Drop semicolon or it will be interpreted as comment.
2782 // FIXME: this may be a faulty span from libsyntax.
2783 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2785 let item_str = match self.node {
2786 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2791 &FnSig::new(fn_decl, generics, self.vis.clone()),
2795 ).map(|(s, _)| format!("{};", s))
2797 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2798 // FIXME(#21): we're dropping potential comments in between the
2799 // function keywords here.
2800 let vis = format_visibility(context, &self.vis);
2801 let mut_str = if is_mutable { "mut " } else { "" };
2802 let prefix = format!(
2806 rewrite_ident(context, self.ident)
2809 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
2811 ast::ForeignItemKind::Ty => {
2812 let vis = format_visibility(context, &self.vis);
2816 rewrite_ident(context, self.ident)
2819 ast::ForeignItemKind::Macro(ref mac) => {
2820 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
2824 let missing_span = if self.attrs.is_empty() {
2825 mk_sp(self.span.lo(), self.span.lo())
2827 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2829 combine_strs_with_missing_comments(
2840 /// Rewrite an inline mod.
2841 pub fn rewrite_mod(context: &RewriteContext, item: &ast::Item) -> String {
2842 let mut result = String::with_capacity(32);
2843 result.push_str(&*format_visibility(context, &item.vis));
2844 result.push_str("mod ");
2845 result.push_str(rewrite_ident(context, item.ident));
2850 /// Rewrite `extern crate foo;` WITHOUT attributes.
2851 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2852 assert!(is_extern_crate(item));
2853 let new_str = context.snippet(item.span);
2854 Some(if contains_comment(new_str) {
2857 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2858 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2862 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2863 pub fn is_mod_decl(item: &ast::Item) -> bool {
2865 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2870 pub fn is_use_item(item: &ast::Item) -> bool {
2872 ast::ItemKind::Use(_) => true,
2877 pub fn is_extern_crate(item: &ast::Item) -> bool {
2879 ast::ItemKind::ExternCrate(..) => true,