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 syntax::codemap::{self, BytePos, Span};
20 use syntax::{abi, ast, ptr, symbol};
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle};
26 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27 rewrite_assign_rhs_with, ExprType, RhsTactics};
28 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
29 use macros::{rewrite_macro, MacroPosition};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
34 use types::TraitTyParamBounds;
35 use utils::{colon_spaces, contains_skip, first_line_width, format_abi, format_constness,
36 format_defaultness, format_mutability, format_unsafety, format_visibility,
37 is_attributes_extendable, last_line_contains_single_line_comment,
38 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
39 stmt_expr, trimmed_last_line_width};
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 // TODO convert to using rewrite style rather than visitor
128 // TODO 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),
146 .map(|i| BodyElement::ForeignItem(i))
153 enum BodyElement<'a> {
154 // Stmt(&'a ast::Stmt),
155 // Field(&'a ast::Field),
156 // Variant(&'a ast::Variant),
157 // Item(&'a ast::Item),
158 ForeignItem(&'a ast::ForeignItem),
161 /// Represents a fn's signature.
162 pub struct FnSig<'a> {
163 decl: &'a ast::FnDecl,
164 generics: &'a ast::Generics,
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 constness: ast::Constness::NotConst,
183 defaultness: ast::Defaultness::Final,
184 unsafety: ast::Unsafety::Normal,
189 pub fn from_method_sig(
190 method_sig: &'a ast::MethodSig,
191 generics: &'a ast::Generics,
194 unsafety: method_sig.unsafety,
195 constness: method_sig.constness.node,
196 defaultness: ast::Defaultness::Final,
198 decl: &*method_sig.decl,
200 visibility: DEFAULT_VISIBILITY,
205 fn_kind: &'a visit::FnKind,
206 generics: &'a ast::Generics,
207 decl: &'a ast::FnDecl,
208 defaultness: ast::Defaultness,
211 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
215 constness: constness.node,
218 visibility: visibility.clone(),
220 visit::FnKind::Method(_, method_sig, vis, _) => {
221 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
222 fn_sig.defaultness = defaultness;
223 if let Some(vis) = vis {
224 fn_sig.visibility = vis.clone();
232 fn to_str(&self, context: &RewriteContext) -> String {
233 let mut result = String::with_capacity(128);
234 // Vis defaultness constness unsafety abi.
235 result.push_str(&*format_visibility(&self.visibility));
236 result.push_str(format_defaultness(self.defaultness));
237 result.push_str(format_constness(self.constness));
238 result.push_str(format_unsafety(self.unsafety));
239 result.push_str(&format_abi(
241 context.config.force_explicit_abi(),
248 impl<'a> FmtVisitor<'a> {
249 fn format_item(&mut self, item: &Item) {
250 self.buffer.push_str(&item.abi);
252 let snippet = self.snippet(item.span);
253 let brace_pos = snippet.find_uncommented("{").unwrap();
256 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
257 // FIXME: this skips comments between the extern keyword and the opening
259 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
260 self.block_indent = self.block_indent.block_indent(self.config);
262 if item.body.is_empty() {
263 self.format_missing_no_indent(item.span.hi() - BytePos(1));
264 self.block_indent = self.block_indent.block_unindent(self.config);
265 let indent_str = self.block_indent.to_string(self.config);
266 self.push_str(&indent_str);
268 for item in &item.body {
269 self.format_body_element(item);
272 self.block_indent = self.block_indent.block_unindent(self.config);
273 self.format_missing_with_indent(item.span.hi() - BytePos(1));
278 self.last_pos = item.span.hi();
281 fn format_body_element(&mut self, element: &BodyElement) {
283 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
287 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
288 let item = Item::from_foreign_mod(fm, span, self.config);
289 self.format_item(&item);
292 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
293 let rewrite = item.rewrite(&self.get_context(), self.shape());
294 self.push_rewrite(item.span(), rewrite);
295 self.last_pos = item.span.hi();
305 inner_attrs: Option<&[ast::Attribute]>,
306 ) -> Option<String> {
307 let context = self.get_context();
309 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
311 let (mut result, force_newline_brace) =
312 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
315 if self.config.brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
316 || last_line_width(&result) + 2 > self.shape().width
318 newline_brace = true;
319 } else if !result.contains('\n') {
320 newline_brace = false;
323 // Prepare for the function body by possibly adding a newline and
325 // FIXME we'll miss anything between the end of the signature and the
326 // start of the body, but we need more spans from the compiler to solve
329 result.push_str(&indent.to_string_with_newline(self.config));
334 self.single_line_fn(&result, block, inner_attrs)
335 .or_else(|| Some(result))
338 pub fn rewrite_required_fn(
342 sig: &ast::MethodSig,
343 generics: &ast::Generics,
345 ) -> Option<String> {
346 // Drop semicolon or it will be interpreted as comment.
347 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
348 let context = self.get_context();
350 let (mut result, _) = rewrite_fn_base(
354 &FnSig::from_method_sig(sig, generics),
360 // Re-attach semicolon
370 inner_attrs: Option<&[ast::Attribute]>,
371 ) -> Option<String> {
372 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
376 let codemap = self.get_context().codemap;
378 if self.config.empty_item_single_line() && is_empty_block(block, None, codemap)
379 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
381 return Some(format!("{}{{}}", fn_str));
384 if self.config.fn_single_line() && is_simple_block_stmt(block, None, codemap) {
386 if let Some(stmt) = block.stmts.first() {
387 match stmt_expr(stmt) {
389 let suffix = if semicolon_for_expr(&self.get_context(), e) {
395 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
397 .or_else(|| Some(self.snippet(e.span).to_owned()))
399 None => stmt.rewrite(&self.get_context(), self.shape()),
406 if let Some(res) = rewrite {
407 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
408 if !res.contains('\n') && width <= self.config.max_width() {
409 return Some(format!("{}{{ {} }}", fn_str, res));
417 pub fn visit_static(&mut self, static_parts: &StaticParts) {
418 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
419 self.push_rewrite(static_parts.span, rewrite);
422 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
423 let is_tuple = struct_parts.def.is_tuple();
424 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
425 .map(|s| if is_tuple { s + ";" } else { s });
426 self.push_rewrite(struct_parts.span, rewrite);
432 vis: &ast::Visibility,
433 enum_def: &ast::EnumDef,
434 generics: &ast::Generics,
437 let enum_header = format_header("enum ", ident, vis);
438 self.push_str(&enum_header);
440 let enum_snippet = self.snippet(span);
441 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
442 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
443 let generics_str = format_generics(
446 self.config.brace_style(),
447 if enum_def.variants.is_empty() {
448 BracePos::ForceSameLine
453 mk_sp(span.lo(), body_start),
454 last_line_width(&enum_header),
456 self.push_str(&generics_str);
458 self.last_pos = body_start;
460 self.block_indent = self.block_indent.block_indent(self.config);
461 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
463 Some(ref body_str) => self.push_str(body_str),
464 None => self.format_missing_no_indent(span.hi() - BytePos(1)),
466 self.block_indent = self.block_indent.block_unindent(self.config);
468 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
469 let indent_str = self.block_indent.to_string(self.config);
470 self.push_str(&indent_str);
473 self.last_pos = span.hi();
476 // Format the body of an enum definition
477 fn format_variant_list(
479 enum_def: &ast::EnumDef,
482 ) -> Option<String> {
483 if enum_def.variants.is_empty() {
486 let mut result = String::with_capacity(1024);
487 let indentation = self.block_indent.to_string_with_newline(self.config);
488 result.push_str(&indentation);
490 let itemize_list_with = |one_line_width: usize| {
492 self.snippet_provider,
493 enum_def.variants.iter(),
497 if !f.node.attrs.is_empty() {
498 f.node.attrs[0].span.lo()
504 |f| self.format_variant(f, one_line_width),
510 let mut items: Vec<_> =
511 itemize_list_with(self.config.width_heuristics().struct_variant_width);
512 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
513 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
514 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
515 if has_multiline_variant && has_single_line_variant {
516 items = itemize_list_with(0);
519 let shape = self.shape().sub_width(2)?;
520 let fmt = ListFormatting {
521 tactic: DefinitiveListTactic::Vertical,
523 trailing_separator: self.config.trailing_comma(),
524 separator_place: SeparatorPlace::Back,
526 ends_with_newline: true,
527 preserve_newline: true,
531 let list = write_list(&items, &fmt)?;
532 result.push_str(&list);
537 // Variant of an enum.
538 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
539 if contains_skip(&field.node.attrs) {
540 let lo = field.node.attrs[0].span.lo();
541 let span = mk_sp(lo, field.span.hi());
542 return Some(self.snippet(span).to_owned());
545 let context = self.get_context();
547 let shape = self.shape().sub_width(1)?;
548 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
553 .map_or(field.span.lo(), |attr| attr.span.hi());
554 let span = mk_sp(lo, field.span.lo());
556 let variant_body = match field.node.data {
557 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
559 &StructParts::from_variant(field),
561 Some(one_line_width),
563 ast::VariantData::Unit(..) => {
564 if let Some(ref expr) = field.node.disr_expr {
565 let lhs = format!("{} =", field.node.ident.name);
566 rewrite_assign_rhs(&context, lhs, &**expr, shape)?
568 field.node.ident.name.to_string()
573 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
578 context: &RewriteContext,
581 where_span_end: Option<BytePos>,
582 ) -> Option<String> {
583 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
584 let mut result = String::with_capacity(128);
585 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
586 let sep = offset.to_string_with_newline(context.config);
587 result.push_str(&ref_and_type);
589 let where_budget = if result.contains('\n') {
590 context.config.max_width()
592 context.budget(last_line_width(&result))
594 let option = WhereClauseOption::snuggled(&ref_and_type);
595 let where_clause_str = rewrite_where_clause(
597 &generics.where_clause,
598 context.config.brace_style(),
599 Shape::legacy(where_budget, offset.block_only()),
608 // If there is no where clause, we may have missing comments between the trait name and
609 // the opening brace.
610 if generics.where_clause.predicates.is_empty() {
611 if let Some(hi) = where_span_end {
612 match recover_missing_comment_in_span(
613 mk_sp(self_ty.span.hi(), hi),
614 Shape::indented(offset, context.config),
616 last_line_width(&result),
618 Some(ref missing_comment) if !missing_comment.is_empty() => {
619 result.push_str(missing_comment);
626 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
627 result.push_str(&where_clause_str);
628 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
629 result.push_str(&format!("{}{{{}}}", &sep, &sep));
631 result.push_str(" {}");
636 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
637 let width = offset.block_indent + context.config.tab_spaces() - 1;
638 let where_indent = Indent::new(0, width);
639 result.push_str(&where_indent.to_string_with_newline(context.config));
641 result.push_str(&where_clause_str);
643 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
644 match context.config.brace_style() {
645 _ if need_newline => result.push_str(&sep),
646 BraceStyle::AlwaysNextLine => result.push_str(&sep),
647 BraceStyle::PreferSameLine => result.push(' '),
648 BraceStyle::SameLineWhere => {
649 if !where_clause_str.is_empty() {
650 result.push_str(&sep);
659 let snippet = context.snippet(item.span);
660 let open_pos = snippet.find_uncommented("{")? + 1;
662 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
663 let mut visitor = FmtVisitor::from_context(context);
664 let item_indent = offset.block_only().block_indent(context.config);
665 visitor.block_indent = item_indent;
666 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
668 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
669 if context.config.reorder_impl_items() {
670 // Create visitor for each items, then reorder them.
671 let mut buffer = vec![];
673 visitor.visit_impl_item(item);
674 buffer.push((visitor.buffer.clone(), item.clone()));
675 visitor.buffer.clear();
677 // type -> const -> macro -> method
678 use ast::ImplItemKind::*;
679 fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
681 (Type(..), Type(..)) | (Const(..), Const(..)) => false,
686 buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
687 (Type(..), _) => Ordering::Less,
688 (_, Type(..)) => Ordering::Greater,
689 (Const(..), _) => Ordering::Less,
690 (_, Const(..)) => Ordering::Greater,
691 (Macro(..), _) => Ordering::Less,
692 (_, Macro(..)) => Ordering::Greater,
695 let mut prev_kind = None;
696 for (buf, item) in buffer {
697 // Make sure that there are at least a single empty line between
698 // different impl items.
701 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
703 visitor.push_str("\n");
705 visitor.push_str(&item_indent.to_string_with_newline(context.config));
706 visitor.push_str(buf.trim());
707 prev_kind = Some(item.node.clone());
711 visitor.visit_impl_item(item);
715 visitor.format_missing(item.span.hi() - BytePos(1));
717 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
718 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
720 result.push_str(&inner_indent_str);
721 result.push_str(visitor.buffer.to_string().trim());
722 result.push_str(&outer_indent_str);
725 if result.ends_with('{') {
726 result.push_str(&sep);
736 fn is_impl_single_line(
737 context: &RewriteContext,
738 items: &[ast::ImplItem],
740 where_clause_str: &str,
743 let snippet = context.snippet(item.span);
744 let open_pos = snippet.find_uncommented("{")? + 1;
747 context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
748 && result.len() + where_clause_str.len() <= context.config.max_width()
749 && !contains_comment(&snippet[open_pos..]),
753 fn format_impl_ref_and_type(
754 context: &RewriteContext,
757 ) -> Option<String> {
758 if let ast::ItemKind::Impl(
768 let mut result = String::with_capacity(128);
770 result.push_str(&format_visibility(&item.vis));
771 result.push_str(format_defaultness(defaultness));
772 result.push_str(format_unsafety(unsafety));
774 let lo = context.snippet_provider.span_after(item.span, "impl");
775 let hi = match *trait_ref {
776 Some(ref tr) => tr.path.span.lo(),
777 None => self_ty.span.lo(),
779 let shape = generics_shape_from_config(
781 Shape::indented(offset + last_line_width(&result), context.config),
784 let generics_str = rewrite_generics(context, "impl", generics, shape, mk_sp(lo, hi))?;
785 result.push_str(&generics_str);
787 let polarity_str = if polarity == ast::ImplPolarity::Negative {
793 if let Some(ref trait_ref) = *trait_ref {
794 let result_len = last_line_width(&result);
795 result.push_str(&rewrite_trait_ref(
804 // Try to put the self type in a single line.
806 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
807 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
808 // If there is no where clause adapt budget for type formatting to take space and curly
809 // brace into account.
810 match context.config.brace_style() {
811 BraceStyle::AlwaysNextLine => 0,
817 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
818 // 1 = space before the type.
819 let budget = context.budget(used_space + 1);
820 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
821 if !self_ty_str.contains('\n') {
822 if trait_ref.is_some() {
823 result.push_str(" for ");
827 result.push_str(&self_ty_str);
832 // Couldn't fit the self type on a single line, put it on a new line.
834 // Add indentation of one additional tab.
835 let new_line_offset = offset.block_indent(context.config);
836 result.push_str(&new_line_offset.to_string(context.config));
837 if trait_ref.is_some() {
838 result.push_str("for ");
840 let budget = context.budget(last_line_width(&result));
841 let type_offset = match context.config.indent_style() {
842 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
843 IndentStyle::Block => new_line_offset,
845 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
852 fn rewrite_trait_ref(
853 context: &RewriteContext,
854 trait_ref: &ast::TraitRef,
858 ) -> Option<String> {
859 // 1 = space between generics and trait_ref
860 let used_space = 1 + polarity_str.len() + result_len;
861 let shape = Shape::indented(offset + used_space, context.config);
862 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
863 if !trait_ref_str.contains('\n') {
864 return Some(format!(" {}{}", polarity_str, &trait_ref_str));
867 // We could not make enough space for trait_ref, so put it on new line.
868 let offset = offset.block_indent(context.config);
869 let shape = Shape::indented(offset, context.config);
870 let trait_ref_str = trait_ref.rewrite(context, shape)?;
873 &offset.to_string_with_newline(context.config),
879 pub struct StructParts<'a> {
882 vis: &'a ast::Visibility,
883 def: &'a ast::VariantData,
884 generics: Option<&'a ast::Generics>,
888 impl<'a> StructParts<'a> {
889 fn format_header(&self) -> String {
890 format_header(self.prefix, self.ident, self.vis)
893 fn from_variant(variant: &'a ast::Variant) -> Self {
896 ident: variant.node.ident,
897 vis: &DEFAULT_VISIBILITY,
898 def: &variant.node.data,
904 pub fn from_item(item: &'a ast::Item) -> Self {
905 let (prefix, def, generics) = match item.node {
906 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
907 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
915 generics: Some(generics),
922 context: &RewriteContext,
923 struct_parts: &StructParts,
925 one_line_width: Option<usize>,
926 ) -> Option<String> {
927 match *struct_parts.def {
928 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
929 ast::VariantData::Tuple(ref fields, _) => {
930 format_tuple_struct(context, struct_parts, fields, offset)
932 ast::VariantData::Struct(ref fields, _) => {
933 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
938 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
939 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
942 let mut result = String::with_capacity(128);
943 let header = format!(
945 format_visibility(&item.vis),
946 format_unsafety(unsafety),
949 result.push_str(&header);
951 let body_lo = context.snippet_provider.span_after(item.span, "{");
953 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
954 let generics_str = rewrite_generics(
956 &item.ident.to_string(),
959 mk_sp(item.span.lo(), body_lo),
961 result.push_str(&generics_str);
963 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
964 if !type_param_bounds.is_empty() {
965 let ident_hi = context
967 .span_after(item.span, &format!("{}", item.ident));
968 let bound_hi = type_param_bounds.last().unwrap().span().hi();
969 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
970 if contains_comment(snippet) {
974 if !type_param_bounds.is_empty() {
975 result = rewrite_assign_rhs_with(
978 &TraitTyParamBounds::new(type_param_bounds),
980 RhsTactics::ForceNextLine,
984 // Rewrite where clause.
985 if !generics.where_clause.predicates.is_empty() {
986 let where_density = if context.config.indent_style() == IndentStyle::Block {
992 let where_budget = context.budget(last_line_width(&result));
993 let pos_before_where = if type_param_bounds.is_empty() {
994 generics.where_clause.span.lo()
996 type_param_bounds[type_param_bounds.len() - 1].span().hi()
998 let option = WhereClauseOption::snuggled(&generics_str);
999 let where_clause_str = rewrite_where_clause(
1001 &generics.where_clause,
1002 context.config.brace_style(),
1003 Shape::legacy(where_budget, offset.block_only()),
1011 // If the where clause cannot fit on the same line,
1012 // put the where clause on a new line
1013 if !where_clause_str.contains('\n')
1014 && last_line_width(&result) + where_clause_str.len() + offset.width()
1015 > context.config.comment_width()
1017 let width = offset.block_indent + context.config.tab_spaces() - 1;
1018 let where_indent = Indent::new(0, width);
1019 result.push_str(&where_indent.to_string_with_newline(context.config));
1021 result.push_str(&where_clause_str);
1023 let item_snippet = context.snippet(item.span);
1024 if let Some(lo) = item_snippet.find('/') {
1026 let comment_hi = body_lo - BytePos(1);
1027 let comment_lo = item.span.lo() + BytePos(lo as u32);
1028 if comment_lo < comment_hi {
1029 match recover_missing_comment_in_span(
1030 mk_sp(comment_lo, comment_hi),
1031 Shape::indented(offset, context.config),
1033 last_line_width(&result),
1035 Some(ref missing_comment) if !missing_comment.is_empty() => {
1036 result.push_str(missing_comment);
1044 match context.config.brace_style() {
1045 _ if last_line_contains_single_line_comment(&result)
1046 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1048 result.push_str(&offset.to_string_with_newline(context.config));
1050 BraceStyle::AlwaysNextLine => {
1051 result.push_str(&offset.to_string_with_newline(context.config));
1053 BraceStyle::PreferSameLine => result.push(' '),
1054 BraceStyle::SameLineWhere => {
1055 if result.contains('\n')
1056 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1058 result.push_str(&offset.to_string_with_newline(context.config));
1066 let snippet = context.snippet(item.span);
1067 let open_pos = snippet.find_uncommented("{")? + 1;
1069 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1070 let mut visitor = FmtVisitor::from_context(context);
1071 visitor.block_indent = offset.block_only().block_indent(context.config);
1072 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1074 for item in trait_items {
1075 visitor.visit_trait_item(item);
1078 visitor.format_missing(item.span.hi() - BytePos(1));
1080 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1081 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1083 result.push_str(&inner_indent_str);
1084 result.push_str(visitor.buffer.to_string().trim());
1085 result.push_str(&outer_indent_str);
1086 } else if result.contains('\n') {
1097 pub fn format_trait_alias(
1098 context: &RewriteContext,
1100 generics: &ast::Generics,
1101 ty_param_bounds: &ast::TyParamBounds,
1103 ) -> Option<String> {
1104 let alias = ident.name.as_str();
1105 // 6 = "trait ", 2 = " ="
1106 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1107 let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
1108 let lhs = format!("trait {} =", generics_str);
1110 rewrite_assign_rhs(context, lhs, ty_param_bounds, shape.sub_width(1)?).map(|s| s + ";")
1113 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1114 let header_str = format_header(p.prefix, p.ident, p.vis);
1115 let generics_str = if let Some(generics) = p.generics {
1116 let hi = if generics.where_clause.predicates.is_empty() {
1119 generics.where_clause.span.hi()
1124 context.config.brace_style(),
1127 mk_sp(generics.span.lo(), hi),
1128 last_line_width(&header_str),
1133 Some(format!("{}{};", header_str, generics_str))
1136 pub fn format_struct_struct(
1137 context: &RewriteContext,
1138 struct_parts: &StructParts,
1139 fields: &[ast::StructField],
1141 one_line_width: Option<usize>,
1142 ) -> Option<String> {
1143 let mut result = String::with_capacity(1024);
1144 let span = struct_parts.span;
1146 let header_str = struct_parts.format_header();
1147 result.push_str(&header_str);
1149 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1150 let body_lo = context.snippet_provider.span_after(span, "{");
1152 let generics_str = match struct_parts.generics {
1153 Some(g) => format_generics(
1156 context.config.brace_style(),
1157 if fields.is_empty() {
1158 BracePos::ForceSameLine
1163 mk_sp(header_hi, body_lo),
1164 last_line_width(&result),
1167 // 3 = ` {}`, 2 = ` {`.
1168 let overhead = if fields.is_empty() { 3 } else { 2 };
1169 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1170 || context.config.max_width() < overhead + result.len()
1172 format!("\n{}{{", offset.block_only().to_string(context.config))
1179 let overhead = if fields.is_empty() { 1 } else { 0 };
1180 let total_width = result.len() + generics_str.len() + overhead;
1181 if !generics_str.is_empty() && !generics_str.contains('\n')
1182 && total_width > context.config.max_width()
1185 result.push_str(&offset.to_string(context.config));
1186 result.push_str(generics_str.trim_left());
1188 result.push_str(&generics_str);
1191 if fields.is_empty() {
1192 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1193 if snippet.trim().is_empty() {
1195 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1197 result.push_str(snippet.trim_right());
1199 result.push_str(&offset.to_string(context.config));
1201 result.push_str(snippet);
1204 return Some(result);
1208 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1209 let one_line_budget =
1210 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1212 let items_str = rewrite_with_alignment(
1215 Shape::indented(offset, context.config).sub_width(1)?,
1216 mk_sp(body_lo, span.hi()),
1220 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget
1221 && !last_line_contains_single_line_comment(&items_str)
1223 Some(format!("{} {} }}", result, items_str))
1229 .block_indent(context.config)
1230 .to_string(context.config),
1232 offset.to_string(context.config)
1237 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1239 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1240 _ => default_span.lo(),
1244 fn format_tuple_struct(
1245 context: &RewriteContext,
1246 struct_parts: &StructParts,
1247 fields: &[ast::StructField],
1249 ) -> Option<String> {
1250 let mut result = String::with_capacity(1024);
1251 let span = struct_parts.span;
1253 let header_str = struct_parts.format_header();
1254 result.push_str(&header_str);
1256 let body_lo = if fields.is_empty() {
1257 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1260 .span_after(mk_sp(lo, span.hi()), "(")
1264 let body_hi = if fields.is_empty() {
1267 .span_after(mk_sp(body_lo, span.hi()), ")")
1269 // This is a dirty hack to work around a missing `)` from the span of the last field.
1270 let last_arg_span = fields[fields.len() - 1].span;
1271 if context.snippet(last_arg_span).ends_with(')') {
1276 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1280 let where_clause_str = match struct_parts.generics {
1282 let budget = context.budget(last_line_width(&header_str));
1283 let shape = Shape::legacy(budget, offset);
1284 let g_span = mk_sp(span.lo(), body_lo);
1285 let generics_str = rewrite_generics(context, "", generics, shape, g_span)?;
1286 result.push_str(&generics_str);
1288 let where_budget = context.budget(last_line_width(&result));
1289 let option = WhereClauseOption::new(true, false);
1290 rewrite_where_clause(
1292 &generics.where_clause,
1293 context.config.brace_style(),
1294 Shape::legacy(where_budget, offset.block_only()),
1295 Density::Compressed,
1303 None => "".to_owned(),
1306 if fields.is_empty() {
1308 let used_width = last_line_used_width(&result, offset.width()) + 3;
1309 if used_width > context.config.max_width() {
1311 result.push_str(&offset
1312 .block_indent(context.config)
1313 .to_string(context.config))
1316 let snippet = context.snippet(mk_sp(
1320 .span_before(mk_sp(body_lo, span.hi()), ")"),
1322 if snippet.is_empty() {
1324 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1325 result.push_str(snippet.trim_right());
1327 result.push_str(&offset.to_string(context.config));
1329 result.push_str(snippet);
1333 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1334 let fields = &fields.iter().collect::<Vec<_>>();
1335 result = overflow::rewrite_with_parens(
1341 context.config.width_heuristics().fn_call_width,
1346 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1347 && (result.contains('\n')
1348 || offset.block_indent + result.len() + where_clause_str.len() + 1
1349 > context.config.max_width())
1351 // We need to put the where clause on a new line, but we didn't
1352 // know that earlier, so the where clause will not be indented properly.
1355 .push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1356 .to_string(context.config));
1358 result.push_str(&where_clause_str);
1363 pub fn rewrite_type_alias(
1364 context: &RewriteContext,
1368 generics: &ast::Generics,
1369 vis: &ast::Visibility,
1371 ) -> Option<String> {
1372 let mut result = String::with_capacity(128);
1374 result.push_str(&format_visibility(vis));
1375 result.push_str("type ");
1378 let g_shape = Shape::indented(indent, context.config)
1379 .offset_left(result.len())?
1382 context.snippet_provider.span_after(span, "type"),
1385 let generics_str = rewrite_generics(context, &ident.to_string(), generics, g_shape, g_span)?;
1386 result.push_str(&generics_str);
1388 let where_budget = context.budget(last_line_width(&result));
1389 let option = WhereClauseOption::snuggled(&result);
1390 let where_clause_str = rewrite_where_clause(
1392 &generics.where_clause,
1393 context.config.brace_style(),
1394 Shape::legacy(where_budget, indent),
1402 result.push_str(&where_clause_str);
1403 if where_clause_str.is_empty() {
1404 result.push_str(" =");
1406 result.push_str(&format!(
1408 indent.to_string_with_newline(context.config)
1413 let ty_shape = Shape::indented(indent, context.config).sub_width(1)?;
1414 rewrite_assign_rhs(context, result, ty, ty_shape).map(|s| s + ";")
1417 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1419 if config.space_before_colon() { " " } else { "" },
1420 if config.space_after_colon() { " " } else { "" },
1424 pub fn rewrite_struct_field_prefix(
1425 context: &RewriteContext,
1426 field: &ast::StructField,
1427 ) -> Option<String> {
1428 let vis = format_visibility(&field.vis);
1429 let type_annotation_spacing = type_annotation_spacing(context.config);
1430 Some(match field.ident {
1431 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1432 None => format!("{}", vis),
1436 impl Rewrite for ast::StructField {
1437 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1438 rewrite_struct_field(context, self, shape, 0)
1442 pub fn rewrite_struct_field(
1443 context: &RewriteContext,
1444 field: &ast::StructField,
1446 lhs_max_width: usize,
1447 ) -> Option<String> {
1448 if contains_skip(&field.attrs) {
1449 return Some(context.snippet(field.span()).to_owned());
1452 let type_annotation_spacing = type_annotation_spacing(context.config);
1453 let prefix = rewrite_struct_field_prefix(context, field)?;
1455 let attrs_str = field.attrs.rewrite(context, shape)?;
1456 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1457 let missing_span = if field.attrs.is_empty() {
1458 mk_sp(field.span.lo(), field.span.lo())
1460 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1462 let mut spacing = String::from(if field.ident.is_some() {
1463 type_annotation_spacing.1
1467 // Try to put everything on a single line.
1468 let attr_prefix = combine_strs_with_missing_comments(
1476 let overhead = last_line_width(&attr_prefix);
1477 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1478 for _ in 0..lhs_offset {
1481 // In this extreme case we will be missing a space betweeen an attribute and a field.
1482 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1486 .offset_left(overhead + spacing.len())
1487 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1488 if let Some(ref ty) = orig_ty {
1489 if !ty.contains('\n') {
1490 return Some(attr_prefix + &spacing + ty);
1494 let is_prefix_empty = prefix.is_empty();
1495 // We must use multiline. We are going to put attributes and a field on different lines.
1496 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1497 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1498 let field_str = if is_prefix_empty {
1499 field_str.trim_left()
1503 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1506 pub struct StaticParts<'a> {
1508 vis: &'a ast::Visibility,
1511 mutability: ast::Mutability,
1512 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1513 defaultness: Option<ast::Defaultness>,
1517 impl<'a> StaticParts<'a> {
1518 pub fn from_item(item: &'a ast::Item) -> Self {
1519 let (prefix, ty, mutability, expr) = match item.node {
1520 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1521 ast::ItemKind::Const(ref ty, ref expr) => {
1522 ("const", ty, ast::Mutability::Immutable, expr)
1524 _ => unreachable!(),
1532 expr_opt: Some(expr),
1538 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1539 let (ty, expr_opt) = match ti.node {
1540 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1541 _ => unreachable!(),
1545 vis: &DEFAULT_VISIBILITY,
1548 mutability: ast::Mutability::Immutable,
1549 expr_opt: expr_opt.as_ref(),
1555 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1556 let (ty, expr) = match ii.node {
1557 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1558 _ => unreachable!(),
1565 mutability: ast::Mutability::Immutable,
1566 expr_opt: Some(expr),
1567 defaultness: Some(ii.defaultness),
1574 context: &RewriteContext,
1575 static_parts: &StaticParts,
1577 ) -> Option<String> {
1578 let colon = colon_spaces(
1579 context.config.space_before_colon(),
1580 context.config.space_after_colon(),
1582 let mut prefix = format!(
1584 format_visibility(static_parts.vis),
1585 static_parts.defaultness.map_or("", format_defaultness),
1586 static_parts.prefix,
1587 format_mutability(static_parts.mutability),
1593 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1594 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1595 Some(ty_str) => ty_str,
1597 if prefix.ends_with(' ') {
1600 let nested_indent = offset.block_indent(context.config);
1601 let nested_shape = Shape::indented(nested_indent, context.config);
1602 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1605 nested_indent.to_string_with_newline(context.config),
1611 if let Some(expr) = static_parts.expr_opt {
1612 let lhs = format!("{}{} =", prefix, ty_str);
1614 let remaining_width = context.budget(offset.block_indent + 1);
1619 Shape::legacy(remaining_width, offset.block_only()),
1620 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1621 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1623 Some(format!("{}{};", prefix, ty_str))
1627 pub fn rewrite_associated_type(
1629 ty_opt: Option<&ptr::P<ast::Ty>>,
1630 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1631 context: &RewriteContext,
1633 ) -> Option<String> {
1634 let prefix = format!("type {}", ident);
1636 let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1637 if bounds.is_empty() {
1641 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1642 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1648 if let Some(ty) = ty_opt {
1650 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1651 let lhs = format!("{}{} =", prefix, type_bounds_str);
1652 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1654 Some(format!("{}{};", prefix, type_bounds_str))
1658 pub fn rewrite_associated_impl_type(
1660 defaultness: ast::Defaultness,
1661 ty_opt: Option<&ptr::P<ast::Ty>>,
1662 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1663 context: &RewriteContext,
1665 ) -> Option<String> {
1666 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1669 ast::Defaultness::Default => Some(format!("default {}", result)),
1674 impl Rewrite for ast::FunctionRetTy {
1675 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1677 ast::FunctionRetTy::Default(_) => Some(String::new()),
1678 ast::FunctionRetTy::Ty(ref ty) => {
1679 let inner_width = shape.width.checked_sub(3)?;
1680 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1681 .map(|r| format!("-> {}", r))
1687 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1689 ast::TyKind::Infer => {
1690 let original = context.snippet(ty.span);
1697 impl Rewrite for ast::Arg {
1698 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1699 if is_named_arg(self) {
1700 let mut result = self.pat
1701 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1703 if !is_empty_infer(context, &*self.ty) {
1704 if context.config.space_before_colon() {
1705 result.push_str(" ");
1707 result.push_str(":");
1708 if context.config.space_after_colon() {
1709 result.push_str(" ");
1711 let overhead = last_line_width(&result);
1712 let max_width = shape.width.checked_sub(overhead)?;
1713 let ty_str = self.ty
1714 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1715 result.push_str(&ty_str);
1720 self.ty.rewrite(context, shape)
1725 fn rewrite_explicit_self(
1726 explicit_self: &ast::ExplicitSelf,
1728 context: &RewriteContext,
1729 ) -> Option<String> {
1730 match explicit_self.node {
1731 ast::SelfKind::Region(lt, m) => {
1732 let mut_str = format_mutability(m);
1735 let lifetime_str = l.rewrite(
1737 Shape::legacy(context.config.max_width(), Indent::empty()),
1739 Some(format!("&{} {}self", lifetime_str, mut_str))
1741 None => Some(format!("&{}self", mut_str)),
1744 ast::SelfKind::Explicit(ref ty, _) => {
1745 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1747 let mutability = explicit_self_mutability(&args[0]);
1748 let type_str = ty.rewrite(
1750 Shape::legacy(context.config.max_width(), Indent::empty()),
1755 format_mutability(mutability),
1759 ast::SelfKind::Value(_) => {
1760 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1762 let mutability = explicit_self_mutability(&args[0]);
1764 Some(format!("{}self", format_mutability(mutability)))
1769 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1770 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1771 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1772 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1779 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1780 if is_named_arg(arg) {
1787 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1789 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1790 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1791 _ => arg.ty.span.hi(),
1795 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1796 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1797 ident != symbol::keywords::Invalid.ident()
1803 // Return type is (result, force_new_line_for_brace)
1805 context: &RewriteContext,
1810 newline_brace: bool,
1812 ) -> Option<(String, bool)> {
1813 let mut force_new_line_for_brace = false;
1815 let where_clause = &fn_sig.generics.where_clause;
1817 let mut result = String::with_capacity(1024);
1818 result.push_str(&fn_sig.to_str(context));
1821 result.push_str("fn ");
1824 let overhead = if has_body && !newline_brace {
1831 let used_width = last_line_used_width(&result, indent.width());
1832 let one_line_budget = context.budget(used_width + overhead);
1834 width: one_line_budget,
1838 let fd = fn_sig.decl;
1839 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1841 rewrite_generics(context, &ident.to_string(), fn_sig.generics, shape, g_span)?;
1842 result.push_str(&generics_str);
1844 let snuggle_angle_bracket = generics_str
1847 .map_or(false, |l| l.trim_left().len() == 1);
1849 // Note that the width and indent don't really matter, we'll re-layout the
1850 // return type later anyway.
1851 let ret_str = fd.output
1852 .rewrite(context, Shape::indented(indent, context.config))?;
1854 let multi_line_ret_str = ret_str.contains('\n');
1855 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1858 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1869 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1870 one_line_budget, multi_line_budget, arg_indent
1873 // Check if vertical layout was forced.
1874 if one_line_budget == 0 {
1875 if snuggle_angle_bracket {
1878 result.push_str("(");
1879 if context.config.indent_style() == IndentStyle::Visual {
1880 result.push_str(&arg_indent.to_string_with_newline(context.config));
1886 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1887 && result.ends_with('(')
1892 // Skip `pub(crate)`.
1893 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
1894 // A conservative estimation, to goal is to be over all parens in generics
1895 let args_start = fn_sig
1900 .map_or(lo_after_visibility, |param| param.span().hi());
1901 let args_end = if fd.inputs.is_empty() {
1904 .span_after(mk_sp(args_start, span.hi()), ")")
1906 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1907 context.snippet_provider.span_after(last_span, ")")
1909 let args_span = mk_sp(
1912 .span_after(mk_sp(args_start, span.hi()), "("),
1915 let arg_str = rewrite_args(
1918 fd.get_self().as_ref(),
1925 generics_str.contains('\n'),
1928 let put_args_in_block = match context.config.indent_style() {
1929 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1931 } && !fd.inputs.is_empty();
1933 let mut args_last_line_contains_comment = false;
1934 if put_args_in_block {
1935 arg_indent = indent.block_indent(context.config);
1936 result.push_str(&arg_indent.to_string_with_newline(context.config));
1937 result.push_str(&arg_str);
1938 result.push_str(&indent.to_string_with_newline(context.config));
1941 result.push_str(&arg_str);
1942 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1943 // Put the closing brace on the next line if it overflows the max width.
1945 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1948 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1951 // If the last line of args contains comment, we cannot put the closing paren
1952 // on the same line.
1956 .map_or(false, |last_line| last_line.contains("//"))
1958 args_last_line_contains_comment = true;
1959 result.push_str(&arg_indent.to_string_with_newline(context.config));
1965 if let ast::FunctionRetTy::Ty(..) = fd.output {
1966 let ret_should_indent = match context.config.indent_style() {
1967 // If our args are block layout then we surely must have space.
1968 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1969 _ if args_last_line_contains_comment => false,
1970 _ if result.contains('\n') || multi_line_ret_str => true,
1972 // If the return type would push over the max width, then put the return type on
1973 // a new line. With the +1 for the signature length an additional space between
1974 // the closing parenthesis of the argument and the arrow '->' is considered.
1975 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1977 // If there is no where clause, take into account the space after the return type
1979 if where_clause.predicates.is_empty() {
1983 sig_length > context.config.max_width()
1986 let ret_indent = if ret_should_indent {
1987 let indent = if arg_str.is_empty() {
1988 // Aligning with non-existent args looks silly.
1989 force_new_line_for_brace = true;
1992 // FIXME: we might want to check that using the arg indent
1993 // doesn't blow our budget, and if it does, then fallback to
1994 // the where clause indent.
1998 result.push_str(&indent.to_string_with_newline(context.config));
2002 Indent::new(indent.block_indent, last_line_width(&result))
2005 if multi_line_ret_str || ret_should_indent {
2006 // Now that we know the proper indent and width, we need to
2007 // re-layout the return type.
2008 let ret_str = fd.output
2009 .rewrite(context, Shape::indented(ret_indent, context.config))?;
2010 result.push_str(&ret_str);
2012 result.push_str(&ret_str);
2015 // Comment between return type and the end of the decl.
2016 let snippet_lo = fd.output.span().hi();
2017 if where_clause.predicates.is_empty() {
2018 let snippet_hi = span.hi();
2019 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2020 // Try to preserve the layout of the original snippet.
2021 let original_starts_with_newline = snippet
2023 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2024 let original_ends_with_newline = snippet
2025 .rfind(|c| c != ' ')
2026 .map_or(false, |i| snippet[i..].ends_with('\n'));
2027 let snippet = snippet.trim();
2028 if !snippet.is_empty() {
2029 result.push(if original_starts_with_newline {
2034 result.push_str(snippet);
2035 if original_ends_with_newline {
2036 force_new_line_for_brace = true;
2042 let pos_before_where = match fd.output {
2043 ast::FunctionRetTy::Default(..) => args_span.hi(),
2044 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2047 let is_args_multi_lined = arg_str.contains('\n');
2049 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2050 let where_clause_str = rewrite_where_clause(
2053 context.config.brace_style(),
2054 Shape::indented(indent, context.config),
2060 is_args_multi_lined,
2062 // If there are neither where clause nor return type, we may be missing comments between
2064 if where_clause_str.is_empty() {
2065 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2066 match recover_missing_comment_in_span(
2067 mk_sp(args_span.hi(), ret_span.hi()),
2070 last_line_width(&result),
2072 Some(ref missing_comment) if !missing_comment.is_empty() => {
2073 result.push_str(missing_comment);
2074 force_new_line_for_brace = true;
2081 result.push_str(&where_clause_str);
2083 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2084 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2085 Some((result, force_new_line_for_brace))
2088 #[derive(Copy, Clone)]
2089 struct WhereClauseOption {
2090 suppress_comma: bool, // Force no trailing comma
2091 snuggle: bool, // Do not insert newline before `where`
2092 compress_where: bool, // Try single line where clause instead of vertical layout
2095 impl WhereClauseOption {
2096 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2100 compress_where: false,
2104 pub fn snuggled(current: &str) -> WhereClauseOption {
2106 suppress_comma: false,
2107 snuggle: trimmed_last_line_width(current) == 1,
2108 compress_where: false,
2114 context: &RewriteContext,
2116 explicit_self: Option<&ast::ExplicitSelf>,
2117 one_line_budget: usize,
2118 multi_line_budget: usize,
2123 generics_str_contains_newline: bool,
2124 ) -> Option<String> {
2125 let mut arg_item_strs = args.iter()
2126 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2127 .collect::<Option<Vec<_>>>()?;
2129 // Account for sugary self.
2130 // FIXME: the comment for the self argument is dropped. This is blocked
2131 // on rust issue #27522.
2132 let min_args = explicit_self
2133 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2134 .map_or(1, |self_str| {
2135 arg_item_strs[0] = self_str;
2139 // Comments between args.
2140 let mut arg_items = Vec::new();
2142 arg_items.push(ListItem::from_str(""));
2145 // FIXME(#21): if there are no args, there might still be a comment, but
2146 // without spans for the comment or parens, there is no chance of
2147 // getting it right. You also don't get to put a comment on self, unless
2149 if args.len() >= min_args || variadic {
2150 let comment_span_start = if min_args == 2 {
2151 let second_arg_start = if arg_has_pattern(&args[1]) {
2152 args[1].pat.span.lo()
2154 args[1].ty.span.lo()
2156 let reduced_span = mk_sp(span.lo(), second_arg_start);
2158 context.snippet_provider.span_after_last(reduced_span, ",")
2163 enum ArgumentKind<'a> {
2164 Regular(&'a ast::Arg),
2168 let variadic_arg = if variadic {
2169 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2170 let variadic_start =
2171 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2172 Some(ArgumentKind::Variadic(variadic_start))
2177 let more_items = itemize_list(
2178 context.snippet_provider,
2179 args[min_args - 1..]
2181 .map(ArgumentKind::Regular)
2182 .chain(variadic_arg),
2186 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2187 ArgumentKind::Variadic(start) => start,
2190 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2191 ArgumentKind::Variadic(start) => start + BytePos(3),
2194 ArgumentKind::Regular(..) => None,
2195 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2202 arg_items.extend(more_items);
2205 let fits_in_one_line = !generics_str_contains_newline
2206 && (arg_items.is_empty()
2207 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2209 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2210 item.item = Some(arg);
2213 let last_line_ends_with_comment = arg_items
2216 .and_then(|item| item.post_comment.as_ref())
2217 .map_or(false, |s| s.trim().starts_with("//"));
2219 let (indent, trailing_comma) = match context.config.indent_style() {
2220 IndentStyle::Block if fits_in_one_line => {
2221 (indent.block_indent(context.config), SeparatorTactic::Never)
2223 IndentStyle::Block => (
2224 indent.block_indent(context.config),
2225 context.config.trailing_comma(),
2227 IndentStyle::Visual if last_line_ends_with_comment => {
2228 (arg_indent, context.config.trailing_comma())
2230 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2233 let tactic = definitive_tactic(
2235 context.config.fn_args_density().to_list_tactic(),
2239 let budget = match tactic {
2240 DefinitiveListTactic::Horizontal => one_line_budget,
2241 _ => multi_line_budget,
2244 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2246 let fmt = ListFormatting {
2249 trailing_separator: if variadic {
2250 SeparatorTactic::Never
2254 separator_place: SeparatorPlace::Back,
2255 shape: Shape::legacy(budget, indent),
2256 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2257 preserve_newline: true,
2258 config: context.config,
2261 write_list(&arg_items, &fmt)
2264 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2265 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2266 ident != symbol::keywords::Invalid.ident()
2272 fn compute_budgets_for_args(
2273 context: &RewriteContext,
2277 newline_brace: bool,
2279 force_vertical_layout: bool,
2280 ) -> Option<((usize, usize, Indent))> {
2282 "compute_budgets_for_args {} {:?}, {}, {}",
2288 // Try keeping everything on the same line.
2289 if !result.contains('\n') && !force_vertical_layout {
2290 // 2 = `()`, 3 = `() `, space is before ret_string.
2291 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2292 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2302 let one_line_budget = context.budget(used_space);
2304 if one_line_budget > 0 {
2306 let (indent, multi_line_budget) = match context.config.indent_style() {
2307 IndentStyle::Block => {
2308 let indent = indent.block_indent(context.config);
2309 (indent, context.budget(indent.width() + 1))
2311 IndentStyle::Visual => {
2312 let indent = indent + result.len() + 1;
2313 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2314 (indent, context.budget(multi_line_overhead))
2318 return Some((one_line_budget, multi_line_budget, indent));
2322 // Didn't work. we must force vertical layout and put args on a newline.
2323 let new_indent = indent.block_indent(context.config);
2324 let used_space = match context.config.indent_style() {
2326 IndentStyle::Block => new_indent.width() + 1,
2327 // Account for `)` and possibly ` {`.
2328 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2330 Some((0, context.budget(used_space), new_indent))
2333 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2334 let predicate_count = where_clause.predicates.len();
2336 if config.where_single_line() && predicate_count == 1 {
2339 let brace_style = config.brace_style();
2341 brace_style == BraceStyle::AlwaysNextLine
2342 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2345 fn rewrite_generics(
2346 context: &RewriteContext,
2348 generics: &ast::Generics,
2351 ) -> Option<String> {
2352 // FIXME: convert bounds to where clauses where they get too big or if
2353 // there is a where clause at all.
2355 if generics.params.is_empty() {
2356 return Some(ident.to_owned());
2359 let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>();
2360 overflow::rewrite_with_angle_brackets(context, ident, params, shape, span)
2363 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2364 match config.indent_style() {
2365 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2366 IndentStyle::Block => {
2370 .block_indent(config.tab_spaces())
2371 .with_max_width(config)
2377 fn rewrite_where_clause_rfc_style(
2378 context: &RewriteContext,
2379 where_clause: &ast::WhereClause,
2382 span_end: Option<BytePos>,
2383 span_end_before_where: BytePos,
2384 where_clause_option: WhereClauseOption,
2385 is_args_multi_line: bool,
2386 ) -> Option<String> {
2387 let block_shape = shape.block().with_max_width(context.config);
2389 let (span_before, span_after) =
2390 missing_span_before_after_where(span_end_before_where, where_clause);
2391 let (comment_before, comment_after) =
2392 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2394 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2397 block_shape.indent.to_string_with_newline(context.config)
2400 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2402 let clause_shape = clause_shape.sub_width(1)?;
2403 // each clause on one line, trailing comma (except if suppress_comma)
2404 let span_start = where_clause.predicates[0].span().lo();
2405 // If we don't have the start of the next span, then use the end of the
2406 // predicates, but that means we miss comments.
2407 let len = where_clause.predicates.len();
2408 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2409 let span_end = span_end.unwrap_or(end_of_preds);
2410 let items = itemize_list(
2411 context.snippet_provider,
2412 where_clause.predicates.iter(),
2415 |pred| pred.span().lo(),
2416 |pred| pred.span().hi(),
2417 |pred| pred.rewrite(context, clause_shape),
2422 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2423 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2424 SeparatorTactic::Never
2426 context.config.trailing_comma()
2429 // shape should be vertical only and only if we have `where_single_line` option enabled
2430 // and the number of items of the where clause is equal to 1
2431 let shape_tactic = if where_single_line {
2432 DefinitiveListTactic::Horizontal
2434 DefinitiveListTactic::Vertical
2437 let fmt = ListFormatting {
2438 tactic: shape_tactic,
2440 trailing_separator: comma_tactic,
2441 separator_place: SeparatorPlace::Back,
2442 shape: clause_shape,
2443 ends_with_newline: true,
2444 preserve_newline: true,
2445 config: context.config,
2447 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2449 let comment_separator = |comment: &str, shape: Shape| {
2450 if comment.is_empty() {
2453 shape.indent.to_string_with_newline(context.config)
2456 let newline_before_where = comment_separator(&comment_before, shape);
2457 let newline_after_where = comment_separator(&comment_after, clause_shape);
2460 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2461 && comment_after.is_empty() && !preds_str.contains('\n')
2462 && 6 + preds_str.len() <= shape.width || where_single_line
2466 clause_shape.indent.to_string_with_newline(context.config)
2469 "{}{}{}where{}{}{}{}",
2472 newline_before_where,
2473 newline_after_where,
2480 fn rewrite_where_clause(
2481 context: &RewriteContext,
2482 where_clause: &ast::WhereClause,
2483 brace_style: BraceStyle,
2487 span_end: Option<BytePos>,
2488 span_end_before_where: BytePos,
2489 where_clause_option: WhereClauseOption,
2490 is_args_multi_line: bool,
2491 ) -> Option<String> {
2492 if where_clause.predicates.is_empty() {
2493 return Some(String::new());
2496 if context.config.indent_style() == IndentStyle::Block {
2497 return rewrite_where_clause_rfc_style(
2503 span_end_before_where,
2504 where_clause_option,
2509 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2511 let offset = match context.config.indent_style() {
2512 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2513 // 6 = "where ".len()
2514 IndentStyle::Visual => shape.indent + extra_indent + 6,
2516 // FIXME: if indent_style != Visual, then the budgets below might
2517 // be out by a char or two.
2519 let budget = context.config.max_width() - offset.width();
2520 let span_start = where_clause.predicates[0].span().lo();
2521 // If we don't have the start of the next span, then use the end of the
2522 // predicates, but that means we miss comments.
2523 let len = where_clause.predicates.len();
2524 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2525 let span_end = span_end.unwrap_or(end_of_preds);
2526 let items = itemize_list(
2527 context.snippet_provider,
2528 where_clause.predicates.iter(),
2531 |pred| pred.span().lo(),
2532 |pred| pred.span().hi(),
2533 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2538 let item_vec = items.collect::<Vec<_>>();
2539 // FIXME: we don't need to collect here
2540 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2542 let mut comma_tactic = context.config.trailing_comma();
2543 // Kind of a hack because we don't usually have trailing commas in where clauses.
2544 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2545 comma_tactic = SeparatorTactic::Never;
2548 let fmt = ListFormatting {
2551 trailing_separator: comma_tactic,
2552 separator_place: SeparatorPlace::Back,
2553 shape: Shape::legacy(budget, offset),
2554 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2555 preserve_newline: true,
2556 config: context.config,
2558 let preds_str = write_list(&item_vec, &fmt)?;
2560 let end_length = if terminator == "{" {
2561 // If the brace is on the next line we don't need to count it otherwise it needs two
2564 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2565 BraceStyle::PreferSameLine => 2,
2567 } else if terminator == "=" {
2572 if density == Density::Tall || preds_str.contains('\n')
2573 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2577 (shape.indent + extra_indent).to_string(context.config),
2581 Some(format!(" where {}", preds_str))
2585 fn missing_span_before_after_where(
2586 before_item_span_end: BytePos,
2587 where_clause: &ast::WhereClause,
2589 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2591 let pos_after_where = where_clause.span.lo() + BytePos(5);
2592 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2593 (missing_span_before, missing_span_after)
2596 fn rewrite_comments_before_after_where(
2597 context: &RewriteContext,
2598 span_before_where: Span,
2599 span_after_where: Span,
2601 ) -> Option<(String, String)> {
2602 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2603 let after_comment = rewrite_missing_comment(
2605 shape.block_indent(context.config.tab_spaces()),
2608 Some((before_comment, after_comment))
2611 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2612 format!("{}{}{}", format_visibility(vis), item_name, ident)
2615 #[derive(PartialEq, Eq, Clone, Copy)]
2623 context: &RewriteContext,
2624 generics: &ast::Generics,
2625 brace_style: BraceStyle,
2626 brace_pos: BracePos,
2630 ) -> Option<String> {
2631 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2632 let mut result = rewrite_generics(context, "", generics, shape, span)?;
2634 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2635 let budget = context.budget(last_line_used_width(&result, offset.width()));
2636 let mut option = WhereClauseOption::snuggled(&result);
2637 if brace_pos == BracePos::None {
2638 option.suppress_comma = true;
2640 // If the generics are not parameterized then generics.span.hi() == 0,
2641 // so we use span.lo(), which is the position after `struct Foo`.
2642 let span_end_before_where = if generics.is_parameterized() {
2647 let where_clause_str = rewrite_where_clause(
2649 &generics.where_clause,
2651 Shape::legacy(budget, offset.block_only()),
2655 span_end_before_where,
2659 result.push_str(&where_clause_str);
2660 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2661 || (generics.where_clause.predicates.is_empty()
2662 && trimmed_last_line_width(&result) == 1)
2664 brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2665 || brace_style != BraceStyle::AlwaysNextLine
2667 if brace_pos == BracePos::None {
2668 return Some(result);
2670 let total_used_width = last_line_used_width(&result, used_width);
2671 let remaining_budget = context.budget(total_used_width);
2672 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2673 // and hence we take the closer into account as well for one line budget.
2674 // We assume that the closer has the same length as the opener.
2675 let overhead = if brace_pos == BracePos::ForceSameLine {
2682 let forbid_same_line_brace = overhead > remaining_budget;
2683 if !forbid_same_line_brace && same_line_brace {
2687 result.push_str(&offset.block_only().to_string(context.config));
2694 impl Rewrite for ast::ForeignItem {
2695 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2696 let attrs_str = self.attrs.rewrite(context, shape)?;
2697 // Drop semicolon or it will be interpreted as comment.
2698 // FIXME: this may be a faulty span from libsyntax.
2699 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2701 let item_str = match self.node {
2702 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2707 &FnSig::new(fn_decl, generics, self.vis.clone()),
2711 ).map(|(s, _)| format!("{};", s))
2713 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2714 // FIXME(#21): we're dropping potential comments in between the
2715 // function keywords here.
2716 let vis = format_visibility(&self.vis);
2717 let mut_str = if is_mutable { "mut " } else { "" };
2718 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2720 let shape = shape.sub_width(1)?;
2721 ty.rewrite(context, shape).map(|ty_str| {
2722 // 1 = space between prefix and type.
2723 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2726 let nested_indent = shape.indent.block_indent(context.config);
2727 nested_indent.to_string_with_newline(context.config)
2729 format!("{}{}{};", prefix, sep, ty_str)
2732 ast::ForeignItemKind::Ty => {
2733 let vis = format_visibility(&self.vis);
2734 Some(format!("{}type {};", vis, self.ident))
2736 ast::ForeignItemKind::Macro(ref mac) => {
2737 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
2741 let missing_span = if self.attrs.is_empty() {
2742 mk_sp(self.span.lo(), self.span.lo())
2744 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2746 combine_strs_with_missing_comments(
2757 impl Rewrite for ast::GenericParam {
2758 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2760 ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.rewrite(context, shape),
2761 ast::GenericParam::Type(ref ty) => ty.rewrite(context, shape),
2766 /// Rewrite an inline mod.
2767 pub fn rewrite_mod(item: &ast::Item) -> String {
2768 let mut result = String::with_capacity(32);
2769 result.push_str(&*format_visibility(&item.vis));
2770 result.push_str("mod ");
2771 result.push_str(&item.ident.to_string());
2776 /// Rewrite `extern crate foo;` WITHOUT attributes.
2777 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2778 assert!(is_extern_crate(item));
2779 let new_str = context.snippet(item.span);
2780 Some(if contains_comment(new_str) {
2783 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2784 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2788 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2789 pub fn is_mod_decl(item: &ast::Item) -> bool {
2791 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2796 pub fn is_use_item(item: &ast::Item) -> bool {
2798 ast::ItemKind::Use(_) => true,
2803 pub fn is_extern_crate(item: &ast::Item) -> bool {
2805 ast::ItemKind::ExternCrate(..) => true,