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.
16 use syntax::{abi, ast, ptr, symbol};
17 use syntax::ast::{CrateSugar, ImplItem};
18 use syntax::codemap::{BytePos, Span};
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, ReturnIndent, Style};
26 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27 rewrite_call_inner, ExprType};
28 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
29 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
32 use types::join_bounds;
33 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
34 format_constness, format_defaultness, format_mutability, format_unsafety,
35 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
36 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
37 stmt_expr, trim_newlines, trimmed_last_line_width};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
41 fn type_annotation_separator(config: &Config) -> &str {
43 config.space_before_type_annotation(),
44 config.space_after_type_annotation_colon(),
48 // Statements of the form
49 // let pat: ty = init;
50 impl Rewrite for ast::Local {
51 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
53 "Local::rewrite {:?} {} {:?}",
59 skip_out_of_file_lines_range!(context, self.span);
61 if contains_skip(&self.attrs) {
65 let attrs_str = self.attrs.rewrite(context, shape)?;
66 let mut result = if attrs_str.is_empty() {
69 combine_strs_with_missing_comments(
74 self.attrs.last().map(|a| a.span.hi()).unwrap(),
83 let pat_shape = shape.offset_left(4)?;
85 let pat_shape = pat_shape.sub_width(1)?;
86 let pat_str = self.pat.rewrite(context, pat_shape)?;
87 result.push_str(&pat_str);
89 // String that is placed within the assignment pattern and expression.
91 let mut infix = String::with_capacity(32);
93 if let Some(ref ty) = self.ty {
94 let separator = type_annotation_separator(context.config);
95 let indent = shape.indent + last_line_width(&result) + separator.len();
97 let budget = shape.width.checked_sub(indent.width() + 1)?;
98 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
100 infix.push_str(separator);
101 infix.push_str(&rewrite);
104 if self.init.is_some() {
105 infix.push_str(" =");
111 result.push_str(&infix);
113 if let Some(ref ex) = self.init {
114 // 1 = trailing semicolon;
115 let nested_shape = shape.sub_width(1)?;
117 result = rewrite_assign_rhs(context, result, ex, nested_shape)?;
125 // TODO convert to using rewrite style rather than visitor
126 // TODO format modules in this style
129 keyword: &'static str,
130 abi: Cow<'static, str>,
131 vis: Option<&'a ast::Visibility>,
132 body: Vec<BodyElement<'a>>,
137 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
140 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
144 .map(|i| BodyElement::ForeignItem(i))
151 enum BodyElement<'a> {
152 // Stmt(&'a ast::Stmt),
153 // Field(&'a ast::Field),
154 // Variant(&'a ast::Variant),
155 // Item(&'a ast::Item),
156 ForeignItem(&'a ast::ForeignItem),
159 /// Represents a fn's signature.
160 pub struct FnSig<'a> {
161 decl: &'a ast::FnDecl,
162 generics: &'a ast::Generics,
164 constness: ast::Constness,
165 defaultness: ast::Defaultness,
166 unsafety: ast::Unsafety,
167 visibility: ast::Visibility,
172 decl: &'a ast::FnDecl,
173 generics: &'a ast::Generics,
174 vis: ast::Visibility,
180 constness: ast::Constness::NotConst,
181 defaultness: ast::Defaultness::Final,
182 unsafety: ast::Unsafety::Normal,
187 pub fn from_method_sig(
188 method_sig: &'a ast::MethodSig,
189 generics: &'a ast::Generics,
192 unsafety: method_sig.unsafety,
193 constness: method_sig.constness.node,
194 defaultness: ast::Defaultness::Final,
196 decl: &*method_sig.decl,
198 visibility: ast::Visibility::Inherited,
203 fn_kind: &'a visit::FnKind,
204 generics: &'a ast::Generics,
205 decl: &'a ast::FnDecl,
206 defualtness: ast::Defaultness,
209 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
213 constness: constness.node,
214 defaultness: defualtness,
216 visibility: visibility.clone(),
218 visit::FnKind::Method(_, method_sig, vis, _) => {
219 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
220 fn_sig.defaultness = defualtness;
221 if let Some(vis) = vis {
222 fn_sig.visibility = vis.clone();
230 fn to_str(&self, context: &RewriteContext) -> String {
231 let mut result = String::with_capacity(128);
232 // Vis defaultness constness unsafety abi.
233 result.push_str(&*format_visibility(&self.visibility));
234 result.push_str(format_defaultness(self.defaultness));
235 result.push_str(format_constness(self.constness));
236 result.push_str(format_unsafety(self.unsafety));
237 result.push_str(&format_abi(
239 context.config.force_explicit_abi(),
246 impl<'a> FmtVisitor<'a> {
247 fn format_item(&mut self, item: Item) {
248 self.buffer.push_str(&item.abi);
250 let snippet = self.snippet(item.span);
251 let brace_pos = snippet.find_uncommented("{").unwrap();
253 self.buffer.push_str("{");
254 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
255 // FIXME: this skips comments between the extern keyword and the opening
257 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
258 self.block_indent = self.block_indent.block_indent(self.config);
260 if item.body.is_empty() {
261 self.format_missing_no_indent(item.span.hi() - BytePos(1));
262 self.block_indent = self.block_indent.block_unindent(self.config);
265 .push_str(&self.block_indent.to_string(self.config));
267 for item in &item.body {
268 self.format_body_element(item);
271 self.block_indent = self.block_indent.block_unindent(self.config);
272 self.format_missing_with_indent(item.span.hi() - BytePos(1));
276 self.buffer.push_str("}");
277 self.last_pos = item.span.hi();
280 fn format_body_element(&mut self, element: &BodyElement) {
282 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
286 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
287 let item = Item::from_foreign_mod(fm, span, self.config);
288 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 ) -> Option<String> {
306 let context = self.get_context();
309 !is_empty_block(block, self.codemap) || !context.config.fn_empty_single_line();
310 let mut newline_brace =
311 newline_for_brace(self.config, &fn_sig.generics.where_clause, has_body);
313 let (mut result, force_newline_brace) =
314 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
317 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || 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
332 result.push_str(&indent.to_string(self.config));
337 self.single_line_fn(&result, block).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
368 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
369 if fn_str.contains('\n') {
373 let codemap = self.get_context().codemap;
375 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
376 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
378 return Some(format!("{}{{}}", fn_str));
381 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
383 if let Some(stmt) = block.stmts.first() {
384 match stmt_expr(stmt) {
386 let suffix = if semicolon_for_expr(&self.get_context(), e) {
392 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
394 .or_else(|| Some(self.snippet(e.span)))
396 None => stmt.rewrite(&self.get_context(), self.shape()),
403 if let Some(res) = rewrite {
404 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
405 if !res.contains('\n') && width <= self.config.max_width() {
406 return Some(format!("{}{{ {} }}", fn_str, res));
417 vis: &ast::Visibility,
418 enum_def: &ast::EnumDef,
419 generics: &ast::Generics,
422 let enum_header = format_header("enum ", ident, vis);
423 self.buffer.push_str(&enum_header);
425 let enum_snippet = self.snippet(span);
426 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
427 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
428 let generics_str = format_generics(
431 self.config.item_brace_style(),
432 enum_def.variants.is_empty(),
434 mk_sp(span.lo(), body_start),
435 last_line_width(&enum_header),
437 self.buffer.push_str(&generics_str);
439 self.last_pos = body_start;
441 self.block_indent = self.block_indent.block_indent(self.config);
442 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
444 Some(ref body_str) => self.buffer.push_str(body_str),
445 None => if contains_comment(&enum_snippet[brace_pos..]) {
446 self.format_missing_no_indent(span.hi() - BytePos(1))
449 self.block_indent = self.block_indent.block_unindent(self.config);
451 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
453 .push_str(&self.block_indent.to_string(self.config));
455 self.buffer.push_str("}");
456 self.last_pos = span.hi();
459 // Format the body of an enum definition
460 fn format_variant_list(
462 enum_def: &ast::EnumDef,
465 ) -> Option<String> {
466 if enum_def.variants.is_empty() {
469 let mut result = String::with_capacity(1024);
471 let indentation = self.block_indent.to_string(self.config);
472 result.push_str(&indentation);
474 let items = itemize_list(
476 enum_def.variants.iter(),
478 |f| if !f.node.attrs.is_empty() {
479 f.node.attrs[0].span.lo()
484 |f| self.format_variant(f),
490 let shape = self.shape().sub_width(2).unwrap();
491 let fmt = ListFormatting {
492 tactic: DefinitiveListTactic::Vertical,
494 trailing_separator: self.config.trailing_comma(),
495 separator_place: SeparatorPlace::Back,
497 ends_with_newline: true,
498 preserve_newline: true,
502 let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
503 result.push_str(&list);
508 // Variant of an enum.
509 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
510 if contains_skip(&field.node.attrs) {
511 let lo = field.node.attrs[0].span.lo();
512 let span = mk_sp(lo, field.span.hi());
513 return Some(self.snippet(span));
516 let context = self.get_context();
517 let indent = self.block_indent;
518 let shape = self.shape();
519 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
524 .map_or(field.span.lo(), |attr| attr.span.hi());
525 let span = mk_sp(lo, field.span.lo());
527 let variant_body = match field.node.data {
528 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
529 // FIXME: Should limit the width, as we have a trailing comma
534 &ast::Visibility::Inherited,
539 Some(self.config.struct_variant_width()),
542 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
543 let lhs = format!("{} =", field.node.name);
545 rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
547 field.node.name.to_string()
551 let attrs_extendable = attrs_str.is_empty()
552 || (context.config.attributes_on_same_line_as_variant()
553 && is_attributes_extendable(&attrs_str));
554 combine_strs_with_missing_comments(
566 context: &RewriteContext,
569 where_span_end: Option<BytePos>,
570 ) -> Option<String> {
571 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
572 let mut result = String::with_capacity(128);
573 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
574 let indent_str = offset.to_string(context.config);
575 let sep = format!("\n{}", &indent_str);
576 result.push_str(&ref_and_type);
578 let where_budget = if result.contains('\n') {
579 context.config.max_width()
581 context.budget(last_line_width(&result))
583 let option = WhereClauseOption::snuggled(&ref_and_type);
584 let where_clause_str = rewrite_where_clause(
586 &generics.where_clause,
587 context.config.item_brace_style(),
588 Shape::legacy(where_budget, offset.block_only()),
589 context.config.where_density(),
597 // If there is no where clause, we may have missing comments between the trait name and
598 // the opening brace.
599 if generics.where_clause.predicates.is_empty() {
600 if let Some(hi) = where_span_end {
601 match recover_missing_comment_in_span(
602 mk_sp(self_ty.span.hi(), hi),
603 Shape::indented(offset, context.config),
605 last_line_width(&result),
607 Some(ref missing_comment) if !missing_comment.is_empty() => {
608 result.push_str(missing_comment);
615 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
616 result.push_str(&where_clause_str);
617 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
618 result.push_str(&format!("{}{{{}}}", &sep, &sep));
620 result.push_str(" {}");
625 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
627 let width = offset.block_indent + context.config.tab_spaces() - 1;
628 let where_indent = Indent::new(0, width);
629 result.push_str(&where_indent.to_string(context.config));
631 result.push_str(&where_clause_str);
633 match context.config.item_brace_style() {
634 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
635 BraceStyle::AlwaysNextLine => result.push_str(&sep),
636 BraceStyle::PreferSameLine => result.push(' '),
637 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
638 result.push_str(&sep);
646 let snippet = context.snippet(item.span);
647 let open_pos = snippet.find_uncommented("{")? + 1;
649 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
650 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
651 visitor.block_indent = offset.block_only().block_indent(context.config);
652 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
654 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
656 visitor.visit_impl_item(item);
659 visitor.format_missing(item.span.hi() - BytePos(1));
661 let inner_indent_str = visitor.block_indent.to_string(context.config);
662 let outer_indent_str = offset.block_only().to_string(context.config);
665 result.push_str(&inner_indent_str);
666 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
668 result.push_str(&outer_indent_str);
671 if result.ends_with('{') {
672 result.push_str(&sep);
682 fn is_impl_single_line(
683 context: &RewriteContext,
686 where_clause_str: &str,
689 let snippet = context.snippet(item.span);
690 let open_pos = snippet.find_uncommented("{")? + 1;
693 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
694 && result.len() + where_clause_str.len() <= context.config.max_width()
695 && !contains_comment(&snippet[open_pos..]),
699 fn format_impl_ref_and_type(
700 context: &RewriteContext,
703 ) -> Option<String> {
704 if let ast::ItemKind::Impl(
714 let mut result = String::with_capacity(128);
716 result.push_str(&format_visibility(&item.vis));
717 result.push_str(format_defaultness(defaultness));
718 result.push_str(format_unsafety(unsafety));
719 result.push_str("impl");
721 let lo = context.codemap.span_after(item.span, "impl");
722 let hi = match *trait_ref {
723 Some(ref tr) => tr.path.span.lo(),
724 None => self_ty.span.lo(),
726 let shape = generics_shape_from_config(
728 Shape::indented(offset + last_line_width(&result), context.config),
731 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
733 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
735 let polarity_str = if polarity == ast::ImplPolarity::Negative {
741 if let Some(ref trait_ref) = *trait_ref {
742 let result_len = result.len();
743 if let Some(trait_ref_str) = rewrite_trait_ref(
752 result.push_str(&trait_ref_str);
755 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
756 result.push_str(&rewrite_trait_ref(
767 result.push_str(&generics_str);
770 // Try to put the self type in a single line.
772 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
773 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
774 // If there is no where clause adapt budget for type formatting to take space and curly
775 // brace into account.
776 match context.config.item_brace_style() {
777 BraceStyle::AlwaysNextLine => 0,
783 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
784 // 1 = space before the type.
785 let budget = context.budget(used_space + 1);
786 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
787 if !self_ty_str.contains('\n') {
788 if trait_ref.is_some() {
789 result.push_str(" for ");
793 result.push_str(&self_ty_str);
798 // Couldn't fit the self type on a single line, put it on a new line.
800 // Add indentation of one additional tab.
801 let new_line_offset = offset.block_indent(context.config);
802 result.push_str(&new_line_offset.to_string(context.config));
803 if trait_ref.is_some() {
804 result.push_str("for ");
806 let budget = context.budget(last_line_width(&result));
807 let type_offset = match context.config.where_style() {
808 Style::Legacy => new_line_offset + trait_ref_overhead,
809 Style::Rfc => new_line_offset,
811 result.push_str(&*self_ty
812 .rewrite(context, Shape::legacy(budget, type_offset))?);
819 fn rewrite_trait_ref(
820 context: &RewriteContext,
821 trait_ref: &ast::TraitRef,
827 ) -> Option<String> {
828 // 1 = space between generics and trait_ref
829 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
830 let shape = Shape::indented(offset + used_space, context.config);
831 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
832 if !(retry && trait_ref_str.contains('\n')) {
841 // We could not make enough space for trait_ref, so put it on new line.
843 let offset = offset.block_indent(context.config);
844 let shape = Shape::indented(offset, context.config);
845 let trait_ref_str = trait_ref.rewrite(context, shape)?;
849 &offset.to_string(context.config),
858 pub fn format_struct(
859 context: &RewriteContext,
862 vis: &ast::Visibility,
863 struct_def: &ast::VariantData,
864 generics: Option<&ast::Generics>,
867 one_line_width: Option<usize>,
868 ) -> Option<String> {
870 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
871 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
881 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
895 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
896 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
899 let mut result = String::with_capacity(128);
900 let header = format!(
902 format_visibility(&item.vis),
903 format_unsafety(unsafety),
907 result.push_str(&header);
909 let body_lo = context.codemap.span_after(item.span, "{");
911 let shape = Shape::indented(offset + last_line_width(&result), context.config);
913 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
914 result.push_str(&generics_str);
916 let trait_bound_str = rewrite_trait_bounds(
919 Shape::indented(offset, context.config),
921 // If the trait, generics, and trait bound cannot fit on the same line,
922 // put the trait bounds on an indented new line
923 if offset.width() + last_line_width(&result) + trait_bound_str.len()
924 > context.config.comment_width()
927 let trait_indent = offset.block_only().block_indent(context.config);
928 result.push_str(&trait_indent.to_string(context.config));
930 result.push_str(&trait_bound_str);
932 let has_body = !trait_items.is_empty();
934 let where_density = if (context.config.where_density() == Density::Compressed
935 && (!result.contains('\n') || context.config.fn_args_indent() == IndentStyle::Block))
936 || (context.config.fn_args_indent() == IndentStyle::Block && result.is_empty())
937 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
938 && !result.contains('\n'))
945 let where_budget = context.budget(last_line_width(&result));
946 let pos_before_where = if type_param_bounds.is_empty() {
947 generics.where_clause.span.lo()
949 type_param_bounds[type_param_bounds.len() - 1].span().hi()
951 let option = WhereClauseOption::snuggled(&generics_str);
952 let where_clause_str = rewrite_where_clause(
954 &generics.where_clause,
955 context.config.item_brace_style(),
956 Shape::legacy(where_budget, offset.block_only()),
964 // If the where clause cannot fit on the same line,
965 // put the where clause on a new line
966 if !where_clause_str.contains('\n')
967 && last_line_width(&result) + where_clause_str.len() + offset.width()
968 > context.config.comment_width()
971 let width = offset.block_indent + context.config.tab_spaces() - 1;
972 let where_indent = Indent::new(0, width);
973 result.push_str(&where_indent.to_string(context.config));
975 result.push_str(&where_clause_str);
977 if generics.where_clause.predicates.is_empty() {
978 let item_snippet = context.snippet(item.span);
979 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
981 let comment_hi = body_lo - BytePos(1);
982 let comment_lo = item.span.lo() + BytePos(lo as u32);
983 if comment_lo < comment_hi {
984 match recover_missing_comment_in_span(
985 mk_sp(comment_lo, comment_hi),
986 Shape::indented(offset, context.config),
988 last_line_width(&result),
990 Some(ref missing_comment) if !missing_comment.is_empty() => {
991 result.push_str(missing_comment);
999 match context.config.item_brace_style() {
1000 _ if last_line_contains_single_line_comment(&result) => {
1002 result.push_str(&offset.to_string(context.config));
1004 BraceStyle::AlwaysNextLine => {
1006 result.push_str(&offset.to_string(context.config));
1008 BraceStyle::PreferSameLine => result.push(' '),
1009 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1010 && (!trait_items.is_empty() || result.contains('\n'))
1013 result.push_str(&offset.to_string(context.config));
1020 let snippet = context.snippet(item.span);
1021 let open_pos = snippet.find_uncommented("{")? + 1;
1023 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1024 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1025 visitor.block_indent = offset.block_only().block_indent(context.config);
1026 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1028 for item in trait_items {
1029 visitor.visit_trait_item(item);
1032 visitor.format_missing(item.span.hi() - BytePos(1));
1034 let inner_indent_str = visitor.block_indent.to_string(context.config);
1035 let outer_indent_str = offset.block_only().to_string(context.config);
1038 result.push_str(&inner_indent_str);
1039 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1041 result.push_str(&outer_indent_str);
1042 } else if result.contains('\n') {
1053 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1054 format!("{};", format_header(item_name, ident, vis))
1057 pub fn format_struct_struct(
1058 context: &RewriteContext,
1061 vis: &ast::Visibility,
1062 fields: &[ast::StructField],
1063 generics: Option<&ast::Generics>,
1066 one_line_width: Option<usize>,
1067 ) -> Option<String> {
1068 let mut result = String::with_capacity(1024);
1070 let header_str = format_header(item_name, ident, vis);
1071 result.push_str(&header_str);
1073 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1074 let body_lo = context.codemap.span_after(span, "{");
1076 let generics_str = match generics {
1077 Some(g) => format_generics(
1080 context.config.item_brace_style(),
1083 mk_sp(header_hi, body_lo),
1084 last_line_width(&result),
1087 // 3 = ` {}`, 2 = ` {`.
1088 let overhead = if fields.is_empty() { 3 } else { 2 };
1089 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1090 && !fields.is_empty())
1091 || context.config.max_width() < overhead + result.len()
1093 format!("\n{}{{", offset.block_only().to_string(context.config))
1100 let overhead = if fields.is_empty() { 1 } else { 0 };
1101 let total_width = result.len() + generics_str.len() + overhead;
1102 if !generics_str.is_empty() && !generics_str.contains('\n')
1103 && total_width > context.config.max_width()
1106 result.push_str(&offset.to_string(context.config));
1107 result.push_str(generics_str.trim_left());
1109 result.push_str(&generics_str);
1112 if fields.is_empty() {
1113 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1114 if snippet.trim().is_empty() {
1116 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1118 result.push_str(snippet.trim_right());
1120 result.push_str(&offset.to_string(context.config));
1122 result.push_str(&snippet);
1125 return Some(result);
1129 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1130 let one_line_budget =
1131 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1133 let items_str = rewrite_with_alignment(
1136 Shape::indented(offset, context.config),
1137 mk_sp(body_lo, span.hi()),
1141 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1142 Some(format!("{} {} }}", result, items_str))
1148 .block_indent(context.config)
1149 .to_string(context.config),
1151 offset.to_string(context.config)
1156 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1157 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1158 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1159 fn get_bytepos_after_visibility(
1160 context: &RewriteContext,
1161 vis: &ast::Visibility,
1166 ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1168 .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1169 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1170 ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1171 _ => default_span.lo(),
1175 fn format_tuple_struct(
1176 context: &RewriteContext,
1179 vis: &ast::Visibility,
1180 fields: &[ast::StructField],
1181 generics: Option<&ast::Generics>,
1184 ) -> Option<String> {
1185 let mut result = String::with_capacity(1024);
1187 let header_str = format_header(item_name, ident, vis);
1188 result.push_str(&header_str);
1190 let body_lo = if fields.is_empty() {
1191 let lo = get_bytepos_after_visibility(context, vis, span, ")");
1192 context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1196 let body_hi = if fields.is_empty() {
1197 context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1199 // This is a dirty hack to work around a missing `)` from the span of the last field.
1200 let last_arg_span = fields[fields.len() - 1].span;
1201 if context.snippet(last_arg_span).ends_with(')') {
1206 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1210 let where_clause_str = match generics {
1212 let budget = context.budget(last_line_width(&header_str));
1213 let shape = Shape::legacy(budget, offset);
1214 let g_span = mk_sp(span.lo(), body_lo);
1215 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1216 result.push_str(&generics_str);
1218 let where_budget = context.budget(last_line_width(&result));
1219 let option = WhereClauseOption::new(true, false);
1220 rewrite_where_clause(
1222 &generics.where_clause,
1223 context.config.item_brace_style(),
1224 Shape::legacy(where_budget, offset.block_only()),
1225 Density::Compressed,
1233 None => "".to_owned(),
1236 if fields.is_empty() {
1238 let used_width = last_line_used_width(&result, offset.width()) + 3;
1239 if used_width > context.config.max_width() {
1241 result.push_str(&offset
1242 .block_indent(context.config)
1243 .to_string(context.config))
1246 let snippet = context.snippet(mk_sp(
1248 context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1250 if snippet.is_empty() {
1252 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1253 result.push_str(snippet.trim_right());
1255 result.push_str(&offset.to_string(context.config));
1257 result.push_str(&snippet);
1262 let body = rewrite_call_inner(
1265 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1267 Shape::indented(offset, context.config).sub_width(1)?,
1268 context.config.fn_call_width(),
1271 result.push_str(&body);
1274 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1275 && (result.contains('\n')
1276 || offset.block_indent + result.len() + where_clause_str.len() + 1
1277 > context.config.max_width())
1279 // We need to put the where clause on a new line, but we didn't
1280 // know that earlier, so the where clause will not be indented properly.
1282 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1283 .to_string(context.config));
1285 result.push_str(&where_clause_str);
1290 pub fn rewrite_type_alias(
1291 context: &RewriteContext,
1295 generics: &ast::Generics,
1296 vis: &ast::Visibility,
1298 ) -> Option<String> {
1299 let mut result = String::with_capacity(128);
1301 result.push_str(&format_visibility(vis));
1302 result.push_str("type ");
1303 result.push_str(&ident.to_string());
1306 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1307 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1308 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1309 result.push_str(&generics_str);
1311 let where_budget = context.budget(last_line_width(&result));
1312 let option = WhereClauseOption::snuggled(&result);
1313 let where_clause_str = rewrite_where_clause(
1315 &generics.where_clause,
1316 context.config.item_brace_style(),
1317 Shape::legacy(where_budget, indent),
1318 context.config.where_density(),
1325 result.push_str(&where_clause_str);
1326 if where_clause_str.is_empty() {
1327 result.push_str(" = ");
1329 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1332 let line_width = last_line_width(&result);
1333 // This checked_sub may fail as the extra space after '=' is not taken into account
1334 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1335 let budget = context.budget(indent.width() + line_width + ";".len());
1336 let type_indent = indent + line_width;
1337 // Try to fit the type on the same line
1338 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1340 // The line was too short, try to put the type on the next line
1342 // Remove the space after '='
1344 let type_indent = indent.block_indent(context.config);
1346 result.push_str(&type_indent.to_string(context.config));
1347 let budget = context.budget(type_indent.width() + ";".len());
1348 ty.rewrite(context, Shape::legacy(budget, type_indent))
1350 result.push_str(&ty_str);
1351 result.push_str(";");
1355 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1357 if config.space_before_type_annotation() {
1362 if config.space_after_type_annotation_colon() {
1370 pub fn rewrite_struct_field_prefix(
1371 context: &RewriteContext,
1372 field: &ast::StructField,
1373 ) -> Option<String> {
1374 let vis = format_visibility(&field.vis);
1375 let type_annotation_spacing = type_annotation_spacing(context.config);
1376 Some(match field.ident {
1377 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1378 None => format!("{}", vis),
1382 impl Rewrite for ast::StructField {
1383 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1384 rewrite_struct_field(context, self, shape, 0)
1388 pub fn rewrite_struct_field(
1389 context: &RewriteContext,
1390 field: &ast::StructField,
1392 lhs_max_width: usize,
1393 ) -> Option<String> {
1394 if contains_skip(&field.attrs) {
1395 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1398 let type_annotation_spacing = type_annotation_spacing(context.config);
1399 let prefix = rewrite_struct_field_prefix(context, field)?;
1401 let attrs_str = field.attrs.rewrite(context, shape)?;
1402 let attrs_extendable = attrs_str.is_empty()
1403 || (context.config.attributes_on_same_line_as_field()
1404 && is_attributes_extendable(&attrs_str));
1405 let missing_span = if field.attrs.is_empty() {
1406 mk_sp(field.span.lo(), field.span.lo())
1408 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1410 let mut spacing = String::from(if field.ident.is_some() {
1411 type_annotation_spacing.1
1415 // Try to put everything on a single line.
1416 let attr_prefix = combine_strs_with_missing_comments(
1424 let overhead = last_line_width(&attr_prefix);
1425 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1426 for _ in 0..lhs_offset {
1429 // In this extreme case we will be missing a space betweeen an attribute and a field.
1430 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1433 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1434 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1435 if !ty.contains('\n') {
1436 return Some(attr_prefix + &spacing + ty);
1440 // We must use multiline.
1441 let new_shape = shape.with_max_width(context.config);
1442 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1444 let field_str = if prefix.is_empty() {
1446 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1447 prefix + " " + &ty_rewritten
1449 let type_offset = shape.indent.block_indent(context.config);
1450 let nested_shape = Shape::indented(type_offset, context.config);
1451 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1452 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1454 combine_strs_with_missing_comments(
1464 pub fn rewrite_static(
1466 vis: &ast::Visibility,
1469 mutability: ast::Mutability,
1470 expr_opt: Option<&ptr::P<ast::Expr>>,
1473 context: &RewriteContext,
1474 ) -> Option<String> {
1475 let colon = colon_spaces(
1476 context.config.space_before_type_annotation(),
1477 context.config.space_after_type_annotation_colon(),
1479 let prefix = format!(
1481 format_visibility(vis),
1483 format_mutability(mutability),
1488 let ty_str = ty.rewrite(
1490 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1493 if let Some(expr) = expr_opt {
1494 let lhs = format!("{}{} =", prefix, ty_str);
1496 let remaining_width = context.budget(offset.block_indent + 1);
1501 Shape::legacy(remaining_width, offset.block_only()),
1502 ).and_then(|res| recover_comment_removed(res, span, context))
1503 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1505 Some(format!("{}{};", prefix, ty_str))
1509 pub fn rewrite_associated_type(
1511 ty_opt: Option<&ptr::P<ast::Ty>>,
1512 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1513 context: &RewriteContext,
1515 ) -> Option<String> {
1516 let prefix = format!("type {}", ident);
1518 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1520 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1521 let bounds: &[_] = ty_param_bounds;
1522 let bound_str = bounds
1524 .map(|ty_bound| ty_bound.rewrite(context, shape))
1525 .collect::<Option<Vec<_>>>()?;
1526 if !bounds.is_empty() {
1527 format!(": {}", join_bounds(context, shape, &bound_str))
1535 if let Some(ty) = ty_opt {
1536 let ty_str = ty.rewrite(
1539 context.budget(indent.block_indent + prefix.len() + 2),
1540 indent.block_only(),
1543 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1545 Some(format!("{}{};", prefix, type_bounds_str))
1549 pub fn rewrite_associated_impl_type(
1551 defaultness: ast::Defaultness,
1552 ty_opt: Option<&ptr::P<ast::Ty>>,
1553 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1554 context: &RewriteContext,
1556 ) -> Option<String> {
1557 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1560 ast::Defaultness::Default => Some(format!("default {}", result)),
1565 impl Rewrite for ast::FunctionRetTy {
1566 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1568 ast::FunctionRetTy::Default(_) => Some(String::new()),
1569 ast::FunctionRetTy::Ty(ref ty) => {
1570 let inner_width = shape.width.checked_sub(3)?;
1571 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1572 .map(|r| format!("-> {}", r))
1578 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1580 ast::TyKind::Infer => {
1581 let original = context.snippet(ty.span);
1588 impl Rewrite for ast::Arg {
1589 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1590 if is_named_arg(self) {
1591 let mut result = self.pat
1592 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1594 if !is_empty_infer(context, &*self.ty) {
1595 if context.config.space_before_type_annotation() {
1596 result.push_str(" ");
1598 result.push_str(":");
1599 if context.config.space_after_type_annotation_colon() {
1600 result.push_str(" ");
1602 let overhead = last_line_width(&result);
1603 let max_width = shape.width.checked_sub(overhead)?;
1604 let ty_str = self.ty
1605 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1606 result.push_str(&ty_str);
1611 self.ty.rewrite(context, shape)
1616 fn rewrite_explicit_self(
1617 explicit_self: &ast::ExplicitSelf,
1619 context: &RewriteContext,
1620 ) -> Option<String> {
1621 match explicit_self.node {
1622 ast::SelfKind::Region(lt, m) => {
1623 let mut_str = format_mutability(m);
1626 let lifetime_str = l.rewrite(
1628 Shape::legacy(context.config.max_width(), Indent::empty()),
1630 Some(format!("&{} {}self", lifetime_str, mut_str))
1632 None => Some(format!("&{}self", mut_str)),
1635 ast::SelfKind::Explicit(ref ty, _) => {
1636 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1638 let mutability = explicit_self_mutability(&args[0]);
1639 let type_str = ty.rewrite(
1641 Shape::legacy(context.config.max_width(), Indent::empty()),
1646 format_mutability(mutability),
1650 ast::SelfKind::Value(_) => {
1651 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1653 let mutability = explicit_self_mutability(&args[0]);
1655 Some(format!("{}self", format_mutability(mutability)))
1660 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1661 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1662 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1663 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1670 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1671 if is_named_arg(arg) {
1678 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1680 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1681 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1682 _ => arg.ty.span.hi(),
1686 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1687 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1688 ident.node != symbol::keywords::Invalid.ident()
1694 // Return type is (result, force_new_line_for_brace)
1696 context: &RewriteContext,
1701 newline_brace: bool,
1703 ) -> Option<(String, bool)> {
1704 let mut force_new_line_for_brace = false;
1706 let where_clause = &fn_sig.generics.where_clause;
1708 let mut result = String::with_capacity(1024);
1709 result.push_str(&fn_sig.to_str(context));
1712 result.push_str("fn ");
1713 result.push_str(&ident.to_string());
1716 let overhead = if has_body && !newline_brace {
1723 let used_width = last_line_used_width(&result, indent.width());
1724 let one_line_budget = context.budget(used_width + overhead);
1726 width: one_line_budget,
1730 let fd = fn_sig.decl;
1731 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1732 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1733 result.push_str(&generics_str);
1735 let snuggle_angle_bracket = generics_str
1738 .map_or(false, |l| l.trim_left().len() == 1);
1740 // Note that the width and indent don't really matter, we'll re-layout the
1741 // return type later anyway.
1742 let ret_str = fd.output
1743 .rewrite(context, Shape::indented(indent, context.config))?;
1745 let multi_line_ret_str = ret_str.contains('\n');
1746 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1749 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1760 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1766 // Check if vertical layout was forced.
1767 if one_line_budget == 0 {
1768 if snuggle_angle_bracket {
1770 } else if context.config.fn_args_paren_newline() {
1772 result.push_str(&arg_indent.to_string(context.config));
1773 if context.config.fn_args_indent() == IndentStyle::Visual {
1774 arg_indent = arg_indent + 1; // extra space for `(`
1778 result.push_str("(");
1779 if context.config.fn_args_indent() == IndentStyle::Visual {
1781 result.push_str(&arg_indent.to_string(context.config));
1787 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1791 // Skip `pub(crate)`.
1792 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1793 // A conservative estimation, to goal is to be over all parens in generics
1794 let args_start = fn_sig
1798 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1799 let args_end = if fd.inputs.is_empty() {
1802 .span_after(mk_sp(args_start, span.hi()), ")")
1804 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1805 context.codemap.span_after(last_span, ")")
1807 let args_span = mk_sp(
1810 .span_after(mk_sp(args_start, span.hi()), "("),
1813 let arg_str = rewrite_args(
1816 fd.get_self().as_ref(),
1823 generics_str.contains('\n'),
1826 let put_args_in_block = match context.config.fn_args_indent() {
1827 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1829 } && !fd.inputs.is_empty();
1831 let mut args_last_line_contains_comment = false;
1832 if put_args_in_block {
1833 arg_indent = indent.block_indent(context.config);
1835 result.push_str(&arg_indent.to_string(context.config));
1836 result.push_str(&arg_str);
1838 result.push_str(&indent.to_string(context.config));
1841 result.push_str(&arg_str);
1842 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1843 // Put the closing brace on the next line if it overflows the max width.
1845 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1848 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1851 // If the last line of args contains comment, we cannot put the closing paren
1852 // on the same line.
1856 .map_or(false, |last_line| last_line.contains("//"))
1858 args_last_line_contains_comment = true;
1860 result.push_str(&arg_indent.to_string(context.config));
1866 if let ast::FunctionRetTy::Ty(..) = fd.output {
1867 let ret_should_indent = match context.config.fn_args_indent() {
1868 // If our args are block layout then we surely must have space.
1869 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1870 _ if args_last_line_contains_comment => false,
1871 _ if result.contains('\n') || multi_line_ret_str => true,
1873 // If the return type would push over the max width, then put the return type on
1874 // a new line. With the +1 for the signature length an additional space between
1875 // the closing parenthesis of the argument and the arrow '->' is considered.
1876 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1878 // If there is no where clause, take into account the space after the return type
1880 if where_clause.predicates.is_empty() {
1884 sig_length > context.config.max_width()
1887 let ret_indent = if ret_should_indent {
1888 let indent = match context.config.fn_return_indent() {
1889 ReturnIndent::WithWhereClause => indent + 4,
1890 // Aligning with non-existent args looks silly.
1891 _ if arg_str.is_empty() => {
1892 force_new_line_for_brace = true;
1895 // FIXME: we might want to check that using the arg indent
1896 // doesn't blow our budget, and if it does, then fallback to
1897 // the where clause indent.
1902 result.push_str(&indent.to_string(context.config));
1906 Indent::new(indent.block_indent, last_line_width(&result))
1909 if multi_line_ret_str || ret_should_indent {
1910 // Now that we know the proper indent and width, we need to
1911 // re-layout the return type.
1912 let ret_str = fd.output
1913 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1914 result.push_str(&ret_str);
1916 result.push_str(&ret_str);
1919 // Comment between return type and the end of the decl.
1920 let snippet_lo = fd.output.span().hi();
1921 if where_clause.predicates.is_empty() {
1922 let snippet_hi = span.hi();
1923 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1924 // Try to preserve the layout of the original snippet.
1925 let original_starts_with_newline = snippet
1927 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1928 let original_ends_with_newline = snippet
1929 .rfind(|c| c != ' ')
1930 .map_or(false, |i| snippet[i..].ends_with('\n'));
1931 let snippet = snippet.trim();
1932 if !snippet.is_empty() {
1933 result.push(if original_starts_with_newline {
1938 result.push_str(snippet);
1939 if original_ends_with_newline {
1940 force_new_line_for_brace = true;
1946 let should_compress_where = match context.config.where_density() {
1947 Density::Compressed => !result.contains('\n'),
1948 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1952 let pos_before_where = match fd.output {
1953 ast::FunctionRetTy::Default(..) => args_span.hi(),
1954 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1957 let is_args_multi_lined = arg_str.contains('\n');
1959 if where_clause.predicates.len() == 1 && should_compress_where {
1960 let budget = context.budget(last_line_used_width(&result, indent.width()));
1961 if let Some(where_clause_str) = rewrite_where_clause(
1964 context.config.fn_brace_style(),
1965 Shape::legacy(budget, indent),
1966 Density::Compressed,
1970 WhereClauseOption::compressed(),
1971 is_args_multi_lined,
1973 result.push_str(&where_clause_str);
1974 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1975 return Some((result, force_new_line_for_brace));
1979 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1980 let where_clause_str = rewrite_where_clause(
1983 context.config.fn_brace_style(),
1984 Shape::indented(indent, context.config),
1990 is_args_multi_lined,
1992 // If there are neither where clause nor return type, we may be missing comments between
1994 if where_clause_str.is_empty() {
1995 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1996 match recover_missing_comment_in_span(
1997 mk_sp(args_span.hi(), ret_span.hi()),
2000 last_line_width(&result),
2002 Some(ref missing_comment) if !missing_comment.is_empty() => {
2003 result.push_str(missing_comment);
2004 force_new_line_for_brace = true;
2011 result.push_str(&where_clause_str);
2013 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2014 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2015 Some((result, force_new_line_for_brace))
2018 #[derive(Copy, Clone)]
2019 struct WhereClauseOption {
2020 suppress_comma: bool, // Force no trailing comma
2021 snuggle: bool, // Do not insert newline before `where`
2022 compress_where: bool, // Try single line where clause instead of vertical layout
2025 impl WhereClauseOption {
2026 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2028 suppress_comma: suppress_comma,
2030 compress_where: false,
2034 pub fn compressed() -> WhereClauseOption {
2036 suppress_comma: true,
2038 compress_where: true,
2042 pub fn snuggled(current: &str) -> WhereClauseOption {
2044 suppress_comma: false,
2045 snuggle: trimmed_last_line_width(current) == 1,
2046 compress_where: false,
2052 context: &RewriteContext,
2054 explicit_self: Option<&ast::ExplicitSelf>,
2055 one_line_budget: usize,
2056 multi_line_budget: usize,
2061 generics_str_contains_newline: bool,
2062 ) -> Option<String> {
2063 let mut arg_item_strs = args.iter()
2064 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2065 .collect::<Option<Vec<_>>>()?;
2067 // Account for sugary self.
2068 // FIXME: the comment for the self argument is dropped. This is blocked
2069 // on rust issue #27522.
2070 let min_args = explicit_self
2071 .and_then(|explicit_self| {
2072 rewrite_explicit_self(explicit_self, args, context)
2074 .map_or(1, |self_str| {
2075 arg_item_strs[0] = self_str;
2079 // Comments between args.
2080 let mut arg_items = Vec::new();
2082 arg_items.push(ListItem::from_str(""));
2085 // FIXME(#21): if there are no args, there might still be a comment, but
2086 // without spans for the comment or parens, there is no chance of
2087 // getting it right. You also don't get to put a comment on self, unless
2089 if args.len() >= min_args || variadic {
2090 let comment_span_start = if min_args == 2 {
2091 let second_arg_start = if arg_has_pattern(&args[1]) {
2092 args[1].pat.span.lo()
2094 args[1].ty.span.lo()
2096 let reduced_span = mk_sp(span.lo(), second_arg_start);
2098 context.codemap.span_after_last(reduced_span, ",")
2103 enum ArgumentKind<'a> {
2104 Regular(&'a ast::Arg),
2108 let variadic_arg = if variadic {
2109 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2110 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2111 Some(ArgumentKind::Variadic(variadic_start))
2116 let more_items = itemize_list(
2118 args[min_args - 1..]
2120 .map(ArgumentKind::Regular)
2121 .chain(variadic_arg),
2124 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2125 ArgumentKind::Variadic(start) => start,
2128 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2129 ArgumentKind::Variadic(start) => start + BytePos(3),
2132 ArgumentKind::Regular(..) => None,
2133 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2140 arg_items.extend(more_items);
2143 let fits_in_one_line = !generics_str_contains_newline
2144 && (arg_items.is_empty()
2145 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2147 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2148 item.item = Some(arg);
2151 let last_line_ends_with_comment = arg_items
2154 .and_then(|item| item.post_comment.as_ref())
2155 .map_or(false, |s| s.trim().starts_with("//"));
2157 let (indent, trailing_comma) = match context.config.fn_args_indent() {
2158 IndentStyle::Block if fits_in_one_line => {
2159 (indent.block_indent(context.config), SeparatorTactic::Never)
2161 IndentStyle::Block => (
2162 indent.block_indent(context.config),
2163 context.config.trailing_comma(),
2165 IndentStyle::Visual if last_line_ends_with_comment => {
2166 (arg_indent, context.config.trailing_comma())
2168 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2171 let tactic = definitive_tactic(
2173 context.config.fn_args_density().to_list_tactic(),
2177 let budget = match tactic {
2178 DefinitiveListTactic::Horizontal => one_line_budget,
2179 _ => multi_line_budget,
2182 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2184 let fmt = ListFormatting {
2187 trailing_separator: if variadic {
2188 SeparatorTactic::Never
2192 separator_place: SeparatorPlace::Back,
2193 shape: Shape::legacy(budget, indent),
2194 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_indent()),
2195 preserve_newline: true,
2196 config: context.config,
2199 write_list(&arg_items, &fmt)
2202 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2203 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2204 ident.node != symbol::keywords::Invalid.ident()
2210 fn compute_budgets_for_args(
2211 context: &RewriteContext,
2215 newline_brace: bool,
2217 force_vertical_layout: bool,
2218 ) -> Option<((usize, usize, Indent))> {
2220 "compute_budgets_for_args {} {:?}, {}, {}",
2226 // Try keeping everything on the same line.
2227 if !result.contains('\n') && !force_vertical_layout {
2228 // 2 = `()`, 3 = `() `, space is before ret_string.
2229 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2230 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2240 let one_line_budget = context.budget(used_space);
2242 if one_line_budget > 0 {
2244 let (indent, multi_line_budget) = match context.config.fn_args_indent() {
2245 IndentStyle::Block => {
2246 let indent = indent.block_indent(context.config);
2247 (indent, context.budget(indent.width() + 1))
2249 IndentStyle::Visual => {
2250 let indent = indent + result.len() + 1;
2251 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2252 (indent, context.budget(multi_line_overhead))
2256 return Some((one_line_budget, multi_line_budget, indent));
2260 // Didn't work. we must force vertical layout and put args on a newline.
2261 let new_indent = indent.block_indent(context.config);
2262 let used_space = match context.config.fn_args_indent() {
2264 IndentStyle::Block => new_indent.width() + 1,
2265 // Account for `)` and possibly ` {`.
2266 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2268 Some((0, context.budget(used_space), new_indent))
2271 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2272 let predicate_count = where_clause.predicates.len();
2274 if config.where_single_line() && predicate_count == 1 {
2277 match (config.fn_brace_style(), config.where_density()) {
2278 (BraceStyle::AlwaysNextLine, _) => true,
2279 (_, Density::Compressed) if predicate_count == 1 => false,
2280 (_, Density::CompressedIfEmpty) if predicate_count == 1 && !has_body => false,
2281 (BraceStyle::SameLineWhere, _) if predicate_count > 0 => true,
2286 fn rewrite_generics(
2287 context: &RewriteContext,
2288 generics: &ast::Generics,
2291 ) -> Option<String> {
2292 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2293 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2294 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2295 rewrite_generics_inner(context, generics, g_shape, 0, span)
2299 fn rewrite_generics_inner(
2300 context: &RewriteContext,
2301 generics: &ast::Generics,
2303 one_line_width: usize,
2305 ) -> Option<String> {
2306 // FIXME: convert bounds to where clauses where they get too big or if
2307 // there is a where clause at all.
2310 enum GenericsArg<'a> {
2311 Lifetime(&'a ast::LifetimeDef),
2312 TyParam(&'a ast::TyParam),
2314 impl<'a> Rewrite for GenericsArg<'a> {
2315 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2317 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2318 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2322 impl<'a> Spanned for GenericsArg<'a> {
2323 fn span(&self) -> Span {
2325 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2326 GenericsArg::TyParam(ty) => ty.span(),
2331 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2332 return Some(String::new());
2335 let generics_args = generics
2338 .map(|lt| GenericsArg::Lifetime(lt))
2339 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2340 let items = itemize_list(
2344 |arg| arg.span().lo(),
2345 |arg| arg.span().hi(),
2346 |arg| arg.rewrite(context, shape),
2347 context.codemap.span_after(span, "<"),
2351 format_generics_item_list(context, items, shape, one_line_width)
2354 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2355 match config.generics_indent() {
2356 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2357 IndentStyle::Block => {
2361 .block_indent(config.tab_spaces())
2362 .with_max_width(config)
2368 pub fn format_generics_item_list<I>(
2369 context: &RewriteContext,
2372 one_line_budget: usize,
2375 I: Iterator<Item = ListItem>,
2377 let item_vec = items.collect::<Vec<_>>();
2379 let tactic = definitive_tactic(
2381 ListTactic::HorizontalVertical,
2385 let fmt = ListFormatting {
2388 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2389 SeparatorTactic::Never
2391 context.config.trailing_comma()
2393 separator_place: SeparatorPlace::Back,
2395 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2396 preserve_newline: true,
2397 config: context.config,
2400 let list_str = write_list(&item_vec, &fmt)?;
2402 Some(wrap_generics_with_angle_brackets(
2409 pub fn wrap_generics_with_angle_brackets(
2410 context: &RewriteContext,
2412 list_offset: Indent,
2414 if context.config.generics_indent() == IndentStyle::Block
2415 && (list_str.contains('\n') || list_str.ends_with(','))
2419 list_offset.to_string(context.config),
2422 .block_unindent(context.config)
2423 .to_string(context.config)
2425 } else if context.config.spaces_within_angle_brackets() {
2426 format!("< {} >", list_str)
2428 format!("<{}>", list_str)
2432 fn rewrite_trait_bounds(
2433 context: &RewriteContext,
2434 type_param_bounds: &ast::TyParamBounds,
2436 ) -> Option<String> {
2437 let bounds: &[_] = type_param_bounds;
2439 if bounds.is_empty() {
2440 return Some(String::new());
2442 let bound_str = bounds
2444 .map(|ty_bound| ty_bound.rewrite(context, shape))
2445 .collect::<Option<Vec<_>>>()?;
2446 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2449 fn rewrite_where_clause_rfc_style(
2450 context: &RewriteContext,
2451 where_clause: &ast::WhereClause,
2454 span_end: Option<BytePos>,
2455 span_end_before_where: BytePos,
2456 where_clause_option: WhereClauseOption,
2457 is_args_multi_line: bool,
2458 ) -> Option<String> {
2459 let block_shape = shape.block().with_max_width(context.config);
2461 let (span_before, span_after) =
2462 missing_span_before_after_where(span_end_before_where, where_clause);
2463 let (comment_before, comment_after) =
2464 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2466 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2469 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2472 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2474 let clause_shape = clause_shape.sub_width(1)?;
2475 // each clause on one line, trailing comma (except if suppress_comma)
2476 let span_start = where_clause.predicates[0].span().lo();
2477 // If we don't have the start of the next span, then use the end of the
2478 // predicates, but that means we miss comments.
2479 let len = where_clause.predicates.len();
2480 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2481 let span_end = span_end.unwrap_or(end_of_preds);
2482 let items = itemize_list(
2484 where_clause.predicates.iter(),
2486 |pred| pred.span().lo(),
2487 |pred| pred.span().hi(),
2488 |pred| pred.rewrite(context, clause_shape),
2493 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2494 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2495 SeparatorTactic::Never
2497 context.config.trailing_comma()
2500 // shape should be vertical only and only if we have `where_single_line` option enabled
2501 // and the number of items of the where clause is equal to 1
2502 let shape_tactic = if where_single_line {
2503 DefinitiveListTactic::Horizontal
2505 DefinitiveListTactic::Vertical
2508 let fmt = ListFormatting {
2509 tactic: shape_tactic,
2511 trailing_separator: comma_tactic,
2512 separator_place: SeparatorPlace::Back,
2513 shape: clause_shape,
2514 ends_with_newline: true,
2515 preserve_newline: true,
2516 config: context.config,
2518 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2520 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2523 format!("\n{}", shape.indent.to_string(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 && comment_before.is_empty()
2530 && comment_after.is_empty() && !preds_str.contains('\n')
2531 && 6 + preds_str.len() <= shape.width || where_single_line
2535 format!("\n{}", clause_shape.indent.to_string(context.config))
2538 "{}{}{}where{}{}{}{}",
2541 newline_before_where,
2542 newline_after_where,
2549 fn rewrite_where_clause(
2550 context: &RewriteContext,
2551 where_clause: &ast::WhereClause,
2552 brace_style: BraceStyle,
2556 span_end: Option<BytePos>,
2557 span_end_before_where: BytePos,
2558 where_clause_option: WhereClauseOption,
2559 is_args_multi_line: bool,
2560 ) -> Option<String> {
2561 if where_clause.predicates.is_empty() {
2562 return Some(String::new());
2565 if context.config.where_style() == Style::Rfc {
2566 return rewrite_where_clause_rfc_style(
2572 span_end_before_where,
2573 where_clause_option,
2578 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2580 let offset = match context.config.where_pred_indent() {
2581 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2582 // 6 = "where ".len()
2583 IndentStyle::Visual => shape.indent + extra_indent + 6,
2585 // FIXME: if where_pred_indent != Visual, then the budgets below might
2586 // be out by a char or two.
2588 let budget = context.config.max_width() - offset.width();
2589 let span_start = where_clause.predicates[0].span().lo();
2590 // If we don't have the start of the next span, then use the end of the
2591 // predicates, but that means we miss comments.
2592 let len = where_clause.predicates.len();
2593 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2594 let span_end = span_end.unwrap_or(end_of_preds);
2595 let items = itemize_list(
2597 where_clause.predicates.iter(),
2599 |pred| pred.span().lo(),
2600 |pred| pred.span().hi(),
2601 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2606 let item_vec = items.collect::<Vec<_>>();
2607 // FIXME: we don't need to collect here if the where_layout isn't
2608 // HorizontalVertical.
2609 let tactic = definitive_tactic(
2611 context.config.where_layout(),
2616 let mut comma_tactic = context.config.trailing_comma();
2617 // Kind of a hack because we don't usually have trailing commas in where clauses.
2618 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2619 comma_tactic = SeparatorTactic::Never;
2622 let fmt = ListFormatting {
2625 trailing_separator: comma_tactic,
2626 separator_place: SeparatorPlace::Back,
2627 shape: Shape::legacy(budget, offset),
2628 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2629 preserve_newline: true,
2630 config: context.config,
2632 let preds_str = write_list(&item_vec, &fmt)?;
2634 let end_length = if terminator == "{" {
2635 // If the brace is on the next line we don't need to count it otherwise it needs two
2638 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2639 BraceStyle::PreferSameLine => 2,
2641 } else if terminator == "=" {
2646 if density == Density::Tall || preds_str.contains('\n')
2647 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2651 (shape.indent + extra_indent).to_string(context.config),
2655 Some(format!(" where {}", preds_str))
2659 fn missing_span_before_after_where(
2660 before_item_span_end: BytePos,
2661 where_clause: &ast::WhereClause,
2663 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2665 let pos_after_where = where_clause.span.lo() + BytePos(5);
2666 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2667 (missing_span_before, missing_span_after)
2670 fn rewrite_comments_before_after_where(
2671 context: &RewriteContext,
2672 span_before_where: Span,
2673 span_after_where: Span,
2675 ) -> Option<(String, String)> {
2676 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2677 let after_comment = rewrite_missing_comment(
2679 shape.block_indent(context.config.tab_spaces()),
2682 Some((before_comment, after_comment))
2685 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2686 format!("{}{}{}", format_visibility(vis), item_name, ident)
2690 context: &RewriteContext,
2691 generics: &ast::Generics,
2692 brace_style: BraceStyle,
2693 force_same_line_brace: bool,
2697 ) -> Option<String> {
2698 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2699 let mut result = rewrite_generics(context, generics, shape, span)?;
2701 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2702 let budget = context.budget(last_line_used_width(&result, offset.width()));
2703 let option = WhereClauseOption::snuggled(&result);
2704 // If the generics are not parameterized then generics.span.hi() == 0,
2705 // so we use span.lo(), which is the position after `struct Foo`.
2706 let span_end_before_where = if generics.is_parameterized() {
2711 let where_clause_str = rewrite_where_clause(
2713 &generics.where_clause,
2715 Shape::legacy(budget, offset.block_only()),
2719 span_end_before_where,
2723 result.push_str(&where_clause_str);
2724 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2725 || (generics.where_clause.predicates.is_empty()
2726 && trimmed_last_line_width(&result) == 1)
2728 force_same_line_brace || trimmed_last_line_width(&result) == 1
2729 || brace_style != BraceStyle::AlwaysNextLine
2731 let total_used_width = last_line_used_width(&result, used_width);
2732 let remaining_budget = context.budget(total_used_width);
2733 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2734 // and hence we take the closer into account as well for one line budget.
2735 // We assume that the closer has the same length as the opener.
2736 let overhead = if force_same_line_brace {
2743 let forbid_same_line_brace = overhead > remaining_budget;
2744 if !forbid_same_line_brace && same_line_brace {
2748 result.push_str(&offset.block_only().to_string(context.config));
2755 impl Rewrite for ast::ForeignItem {
2756 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2757 let attrs_str = self.attrs.rewrite(context, shape)?;
2758 // Drop semicolon or it will be interpreted as comment.
2759 // FIXME: this may be a faulty span from libsyntax.
2760 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2762 let item_str = match self.node {
2763 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2767 &FnSig::new(fn_decl, generics, self.vis.clone()),
2771 ).map(|(s, _)| format!("{};", s)),
2772 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2773 // FIXME(#21): we're dropping potential comments in between the
2774 // function keywords here.
2775 let vis = format_visibility(&self.vis);
2776 let mut_str = if is_mutable { "mut " } else { "" };
2777 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2779 let shape = shape.sub_width(1)?;
2780 ty.rewrite(context, shape).map(|ty_str| {
2781 // 1 = space between prefix and type.
2782 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2785 let nested_indent = shape.indent.block_indent(context.config);
2786 format!("\n{}", nested_indent.to_string(context.config))
2788 format!("{}{}{};", prefix, sep, ty_str)
2791 ast::ForeignItemKind::Ty => {
2792 let vis = format_visibility(&self.vis);
2793 Some(format!("{}type {};", vis, self.ident))
2797 let missing_span = if self.attrs.is_empty() {
2798 mk_sp(self.span.lo(), self.span.lo())
2800 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2802 combine_strs_with_missing_comments(