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(_, ref 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)?;
316 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
317 newline_brace = true;
318 } else if 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(
433 self.config.item_brace_style(),
434 enum_def.variants.is_empty(),
436 mk_sp(span.lo(), body_start),
437 last_line_width(&enum_header),
439 self.buffer.push_str(&generics_str);
441 self.last_pos = body_start;
443 self.block_indent = self.block_indent.block_indent(self.config);
444 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
446 Some(ref body_str) => self.buffer.push_str(body_str),
447 None => if contains_comment(&enum_snippet[brace_pos..]) {
448 self.format_missing_no_indent(span.hi() - BytePos(1))
451 self.block_indent = self.block_indent.block_unindent(self.config);
453 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
455 .push_str(&self.block_indent.to_string(self.config));
457 self.buffer.push_str("}");
458 self.last_pos = span.hi();
461 // Format the body of an enum definition
462 fn format_variant_list(
464 enum_def: &ast::EnumDef,
467 ) -> Option<String> {
468 if enum_def.variants.is_empty() {
471 let mut result = String::with_capacity(1024);
473 let indentation = self.block_indent.to_string(self.config);
474 result.push_str(&indentation);
476 let items = itemize_list(
478 enum_def.variants.iter(),
480 |f| if !f.node.attrs.is_empty() {
481 f.node.attrs[0].span.lo()
486 |f| self.format_variant(f),
492 let shape = self.shape().sub_width(2).unwrap();
493 let fmt = ListFormatting {
494 tactic: DefinitiveListTactic::Vertical,
496 trailing_separator: self.config.trailing_comma(),
497 separator_place: SeparatorPlace::Back,
499 ends_with_newline: true,
500 preserve_newline: true,
504 let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
505 result.push_str(&list);
510 // Variant of an enum.
511 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
512 if contains_skip(&field.node.attrs) {
513 let lo = field.node.attrs[0].span.lo();
514 let span = mk_sp(lo, field.span.hi());
515 return Some(self.snippet(span));
518 let context = self.get_context();
519 let indent = self.block_indent;
520 let shape = self.shape();
521 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
526 .map_or(field.span.lo(), |attr| attr.span.hi());
527 let span = mk_sp(lo, field.span.lo());
529 let variant_body = match field.node.data {
530 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
531 // FIXME: Should limit the width, as we have a trailing comma
536 &ast::Visibility::Inherited,
541 Some(self.config.struct_variant_width()),
544 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
545 let lhs = format!("{} =", field.node.name);
547 rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
549 String::from(field.node.name.to_string())
553 let attrs_extendable = attrs_str.is_empty()
554 || (context.config.attributes_on_same_line_as_variant()
555 && is_attributes_extendable(&attrs_str));
556 combine_strs_with_missing_comments(
568 context: &RewriteContext,
571 where_span_end: Option<BytePos>,
572 ) -> Option<String> {
573 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
574 let mut result = String::with_capacity(128);
575 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
576 let indent_str = offset.to_string(context.config);
577 let sep = format!("\n{}", &indent_str);
578 result.push_str(&ref_and_type);
580 let where_budget = if result.contains('\n') {
581 context.config.max_width()
583 context.budget(last_line_width(&result))
585 let option = WhereClauseOption::snuggled(&ref_and_type);
586 let where_clause_str = rewrite_where_clause(
588 &generics.where_clause,
589 context.config.item_brace_style(),
590 Shape::legacy(where_budget, offset.block_only()),
591 context.config.where_density(),
599 // If there is no where clause, we may have missing comments between the trait name and
600 // the opening brace.
601 if generics.where_clause.predicates.is_empty() {
602 if let Some(hi) = where_span_end {
603 match recover_missing_comment_in_span(
604 mk_sp(self_ty.span.hi(), hi),
605 Shape::indented(offset, context.config),
607 last_line_width(&result),
609 Some(ref missing_comment) if !missing_comment.is_empty() => {
610 result.push_str(missing_comment);
617 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
618 result.push_str(&where_clause_str);
619 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
620 result.push_str(&format!("{}{{{}}}", &sep, &sep));
622 result.push_str(" {}");
627 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
629 let width = offset.block_indent + context.config.tab_spaces() - 1;
630 let where_indent = Indent::new(0, width);
631 result.push_str(&where_indent.to_string(context.config));
633 result.push_str(&where_clause_str);
635 match context.config.item_brace_style() {
636 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
637 BraceStyle::AlwaysNextLine => result.push_str(&sep),
638 BraceStyle::PreferSameLine => result.push(' '),
639 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
640 result.push_str(&sep);
648 let snippet = context.snippet(item.span);
649 let open_pos = snippet.find_uncommented("{")? + 1;
651 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
652 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
653 visitor.block_indent = offset.block_only().block_indent(context.config);
654 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
656 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
658 visitor.visit_impl_item(item);
661 visitor.format_missing(item.span.hi() - BytePos(1));
663 let inner_indent_str = visitor.block_indent.to_string(context.config);
664 let outer_indent_str = offset.block_only().to_string(context.config);
667 result.push_str(&inner_indent_str);
668 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
670 result.push_str(&outer_indent_str);
673 if result.chars().last().unwrap() == '{' {
674 result.push_str(&sep);
684 fn is_impl_single_line(
685 context: &RewriteContext,
688 where_clause_str: &str,
691 let snippet = context.snippet(item.span);
692 let open_pos = snippet.find_uncommented("{")? + 1;
695 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
696 && result.len() + where_clause_str.len() <= context.config.max_width()
697 && !contains_comment(&snippet[open_pos..]),
701 fn format_impl_ref_and_type(
702 context: &RewriteContext,
705 ) -> Option<String> {
706 if let ast::ItemKind::Impl(
716 let mut result = String::with_capacity(128);
718 result.push_str(&format_visibility(&item.vis));
719 result.push_str(format_defaultness(defaultness));
720 result.push_str(format_unsafety(unsafety));
721 result.push_str("impl");
723 let lo = context.codemap.span_after(item.span, "impl");
724 let hi = match *trait_ref {
725 Some(ref tr) => tr.path.span.lo(),
726 None => self_ty.span.lo(),
728 let shape = generics_shape_from_config(
730 Shape::indented(offset + last_line_width(&result), context.config),
733 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
735 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
737 let polarity_str = if polarity == ast::ImplPolarity::Negative {
743 if let Some(ref trait_ref) = *trait_ref {
744 let result_len = result.len();
745 if let Some(trait_ref_str) = rewrite_trait_ref(
754 result.push_str(&trait_ref_str);
757 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
758 result.push_str(&rewrite_trait_ref(
769 result.push_str(&generics_str);
772 // Try to put the self type in a single line.
774 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
775 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
776 // If there is no where clause adapt budget for type formatting to take space and curly
777 // brace into account.
778 match context.config.item_brace_style() {
779 BraceStyle::AlwaysNextLine => 0,
785 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
786 // 1 = space before the type.
787 let budget = context.budget(used_space + 1);
788 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
789 if !self_ty_str.contains('\n') {
790 if trait_ref.is_some() {
791 result.push_str(" for ");
795 result.push_str(&self_ty_str);
800 // Couldn't fit the self type on a single line, put it on a new line.
802 // Add indentation of one additional tab.
803 let new_line_offset = offset.block_indent(context.config);
804 result.push_str(&new_line_offset.to_string(context.config));
805 if trait_ref.is_some() {
806 result.push_str("for ");
808 let budget = context.budget(last_line_width(&result));
809 let type_offset = match context.config.where_style() {
810 Style::Legacy => new_line_offset + trait_ref_overhead,
811 Style::Rfc => new_line_offset,
813 result.push_str(&*self_ty
814 .rewrite(context, Shape::legacy(budget, type_offset))?);
821 fn rewrite_trait_ref(
822 context: &RewriteContext,
823 trait_ref: &ast::TraitRef,
829 ) -> Option<String> {
830 // 1 = space between generics and trait_ref
831 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
832 let shape = Shape::indented(offset + used_space, context.config);
833 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
834 if !(retry && trait_ref_str.contains('\n')) {
843 // We could not make enough space for trait_ref, so put it on new line.
845 let offset = offset.block_indent(context.config);
846 let shape = Shape::indented(offset, context.config);
847 let trait_ref_str = trait_ref.rewrite(context, shape)?;
851 &offset.to_string(context.config),
860 pub fn format_struct(
861 context: &RewriteContext,
864 vis: &ast::Visibility,
865 struct_def: &ast::VariantData,
866 generics: Option<&ast::Generics>,
869 one_line_width: Option<usize>,
870 ) -> Option<String> {
872 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
873 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
883 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
897 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
898 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
901 let mut result = String::with_capacity(128);
902 let header = format!(
904 format_visibility(&item.vis),
905 format_unsafety(unsafety),
909 result.push_str(&header);
911 let body_lo = context.codemap.span_after(item.span, "{");
913 let shape = Shape::indented(offset + last_line_width(&result), context.config);
915 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
916 result.push_str(&generics_str);
918 let trait_bound_str = rewrite_trait_bounds(
921 Shape::indented(offset, context.config),
923 // If the trait, generics, and trait bound cannot fit on the same line,
924 // put the trait bounds on an indented new line
925 if offset.width() + last_line_width(&result) + trait_bound_str.len()
926 > context.config.comment_width()
929 let trait_indent = offset.block_only().block_indent(context.config);
930 result.push_str(&trait_indent.to_string(context.config));
932 result.push_str(&trait_bound_str);
934 let has_body = !trait_items.is_empty();
936 let where_density = if (context.config.where_density() == Density::Compressed
937 && (!result.contains('\n') || context.config.fn_args_indent() == IndentStyle::Block))
938 || (context.config.fn_args_indent() == IndentStyle::Block && result.is_empty())
939 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
940 && !result.contains('\n'))
947 let where_budget = context.budget(last_line_width(&result));
948 let pos_before_where = if type_param_bounds.is_empty() {
949 generics.where_clause.span.lo()
951 type_param_bounds[type_param_bounds.len() - 1].span().hi()
953 let option = WhereClauseOption::snuggled(&generics_str);
954 let where_clause_str = rewrite_where_clause(
956 &generics.where_clause,
957 context.config.item_brace_style(),
958 Shape::legacy(where_budget, offset.block_only()),
966 // If the where clause cannot fit on the same line,
967 // put the where clause on a new line
968 if !where_clause_str.contains('\n')
969 && last_line_width(&result) + where_clause_str.len() + offset.width()
970 > context.config.comment_width()
973 let width = offset.block_indent + context.config.tab_spaces() - 1;
974 let where_indent = Indent::new(0, width);
975 result.push_str(&where_indent.to_string(context.config));
977 result.push_str(&where_clause_str);
979 if generics.where_clause.predicates.is_empty() {
980 let item_snippet = context.snippet(item.span);
981 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
983 let comment_hi = body_lo - BytePos(1);
984 let comment_lo = item.span.lo() + BytePos(lo as u32);
985 if comment_lo < comment_hi {
986 match recover_missing_comment_in_span(
987 mk_sp(comment_lo, comment_hi),
988 Shape::indented(offset, context.config),
990 last_line_width(&result),
992 Some(ref missing_comment) if !missing_comment.is_empty() => {
993 result.push_str(missing_comment);
1001 match context.config.item_brace_style() {
1002 _ if last_line_contains_single_line_comment(&result) => {
1004 result.push_str(&offset.to_string(context.config));
1006 BraceStyle::AlwaysNextLine => {
1008 result.push_str(&offset.to_string(context.config));
1010 BraceStyle::PreferSameLine => result.push(' '),
1011 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1012 && (!trait_items.is_empty() || result.contains('\n'))
1015 result.push_str(&offset.to_string(context.config));
1022 let snippet = context.snippet(item.span);
1023 let open_pos = snippet.find_uncommented("{")? + 1;
1025 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1026 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1027 visitor.block_indent = offset.block_only().block_indent(context.config);
1028 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1030 for item in trait_items {
1031 visitor.visit_trait_item(item);
1034 visitor.format_missing(item.span.hi() - BytePos(1));
1036 let inner_indent_str = visitor.block_indent.to_string(context.config);
1037 let outer_indent_str = offset.block_only().to_string(context.config);
1040 result.push_str(&inner_indent_str);
1041 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1043 result.push_str(&outer_indent_str);
1044 } else if result.contains('\n') {
1055 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1056 format!("{};", format_header(item_name, ident, vis))
1059 pub fn format_struct_struct(
1060 context: &RewriteContext,
1063 vis: &ast::Visibility,
1064 fields: &[ast::StructField],
1065 generics: Option<&ast::Generics>,
1068 one_line_width: Option<usize>,
1069 ) -> Option<String> {
1070 let mut result = String::with_capacity(1024);
1072 let header_str = format_header(item_name, ident, vis);
1073 result.push_str(&header_str);
1075 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1076 let body_lo = context.codemap.span_after(span, "{");
1078 let generics_str = match generics {
1079 Some(g) => format_generics(
1084 context.config.item_brace_style(),
1087 mk_sp(header_hi, body_lo),
1088 last_line_width(&result),
1091 // 3 = ` {}`, 2 = ` {`.
1092 let overhead = if fields.is_empty() { 3 } else { 2 };
1093 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1094 && !fields.is_empty())
1095 || context.config.max_width() < overhead + result.len()
1097 format!("\n{}{{", offset.block_only().to_string(context.config))
1104 let overhead = if fields.is_empty() { 1 } else { 0 };
1105 let total_width = result.len() + generics_str.len() + overhead;
1106 if !generics_str.is_empty() && !generics_str.contains('\n')
1107 && total_width > context.config.max_width()
1110 result.push_str(&offset.to_string(context.config));
1111 result.push_str(generics_str.trim_left());
1113 result.push_str(&generics_str);
1116 if fields.is_empty() {
1117 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1118 if snippet.trim().is_empty() {
1120 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1122 result.push_str(snippet.trim_right());
1124 result.push_str(&offset.to_string(context.config));
1126 result.push_str(&snippet);
1129 return Some(result);
1133 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1134 let one_line_budget =
1135 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1137 let items_str = rewrite_with_alignment(
1140 Shape::indented(offset, context.config),
1141 mk_sp(body_lo, span.hi()),
1145 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1146 Some(format!("{} {} }}", result, items_str))
1152 .block_indent(context.config)
1153 .to_string(context.config),
1155 offset.to_string(context.config)
1160 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1161 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1162 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1163 fn get_bytepos_after_visibility(
1164 context: &RewriteContext,
1165 vis: &ast::Visibility,
1170 ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1172 .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1173 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1174 ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1175 _ => default_span.lo(),
1179 fn format_tuple_struct(
1180 context: &RewriteContext,
1183 vis: &ast::Visibility,
1184 fields: &[ast::StructField],
1185 generics: Option<&ast::Generics>,
1188 ) -> Option<String> {
1189 let mut result = String::with_capacity(1024);
1191 let header_str = format_header(item_name, ident, vis);
1192 result.push_str(&header_str);
1194 let body_lo = if fields.is_empty() {
1195 let lo = get_bytepos_after_visibility(context, vis, span, ")");
1196 context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1200 let body_hi = if fields.is_empty() {
1201 context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1203 // This is a dirty hack to work around a missing `)` from the span of the last field.
1204 let last_arg_span = fields[fields.len() - 1].span;
1205 if context.snippet(last_arg_span).ends_with(')') {
1210 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1214 let where_clause_str = match generics {
1216 let budget = context.budget(last_line_width(&header_str));
1217 let shape = Shape::legacy(budget, offset);
1218 let g_span = mk_sp(span.lo(), body_lo);
1219 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1220 result.push_str(&generics_str);
1222 let where_budget = context.budget(last_line_width(&result));
1223 let option = WhereClauseOption::new(true, false);
1224 rewrite_where_clause(
1226 &generics.where_clause,
1227 context.config.item_brace_style(),
1228 Shape::legacy(where_budget, offset.block_only()),
1229 Density::Compressed,
1237 None => "".to_owned(),
1240 if fields.is_empty() {
1242 let used_width = last_line_used_width(&result, offset.width()) + 3;
1243 if used_width > context.config.max_width() {
1245 result.push_str(&offset
1246 .block_indent(context.config)
1247 .to_string(context.config))
1250 let snippet = context.snippet(mk_sp(
1252 context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1254 if snippet.is_empty() {
1256 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1257 result.push_str(snippet.trim_right());
1259 result.push_str(&offset.to_string(context.config));
1261 result.push_str(&snippet);
1266 let body = rewrite_call_inner(
1269 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1271 Shape::indented(offset, context.config).sub_width(1)?,
1272 context.config.fn_call_width(),
1275 result.push_str(&body);
1278 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1279 && (result.contains('\n')
1280 || offset.block_indent + result.len() + where_clause_str.len() + 1
1281 > context.config.max_width())
1283 // We need to put the where clause on a new line, but we didn't
1284 // know that earlier, so the where clause will not be indented properly.
1286 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1287 .to_string(context.config));
1289 result.push_str(&where_clause_str);
1294 pub fn rewrite_type_alias(
1295 context: &RewriteContext,
1299 generics: &ast::Generics,
1300 vis: &ast::Visibility,
1302 ) -> Option<String> {
1303 let mut result = String::with_capacity(128);
1305 result.push_str(&format_visibility(vis));
1306 result.push_str("type ");
1307 result.push_str(&ident.to_string());
1310 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1311 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1312 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1313 result.push_str(&generics_str);
1315 let where_budget = context.budget(last_line_width(&result));
1316 let option = WhereClauseOption::snuggled(&result);
1317 let where_clause_str = rewrite_where_clause(
1319 &generics.where_clause,
1320 context.config.item_brace_style(),
1321 Shape::legacy(where_budget, indent),
1322 context.config.where_density(),
1329 result.push_str(&where_clause_str);
1330 if where_clause_str.is_empty() {
1331 result.push_str(" = ");
1333 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1336 let line_width = last_line_width(&result);
1337 // This checked_sub may fail as the extra space after '=' is not taken into account
1338 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1339 let budget = context.budget(indent.width() + line_width + ";".len());
1340 let type_indent = indent + line_width;
1341 // Try to fit the type on the same line
1342 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1344 // The line was too short, try to put the type on the next line
1346 // Remove the space after '='
1348 let type_indent = indent.block_indent(context.config);
1350 result.push_str(&type_indent.to_string(context.config));
1351 let budget = context.budget(type_indent.width() + ";".len());
1352 ty.rewrite(context, Shape::legacy(budget, type_indent))
1354 result.push_str(&ty_str);
1355 result.push_str(";");
1359 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1361 if config.space_before_type_annotation() {
1366 if config.space_after_type_annotation_colon() {
1374 pub fn rewrite_struct_field_prefix(
1375 context: &RewriteContext,
1376 field: &ast::StructField,
1377 ) -> Option<String> {
1378 let vis = format_visibility(&field.vis);
1379 let type_annotation_spacing = type_annotation_spacing(context.config);
1380 Some(match field.ident {
1381 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1382 None => format!("{}", vis),
1386 impl Rewrite for ast::StructField {
1387 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1388 rewrite_struct_field(context, self, shape, 0)
1392 pub fn rewrite_struct_field(
1393 context: &RewriteContext,
1394 field: &ast::StructField,
1396 lhs_max_width: usize,
1397 ) -> Option<String> {
1398 if contains_skip(&field.attrs) {
1399 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1402 let type_annotation_spacing = type_annotation_spacing(context.config);
1403 let prefix = rewrite_struct_field_prefix(context, field)?;
1405 let attrs_str = field.attrs.rewrite(context, shape)?;
1406 let attrs_extendable = attrs_str.is_empty()
1407 || (context.config.attributes_on_same_line_as_field()
1408 && is_attributes_extendable(&attrs_str));
1409 let missing_span = if field.attrs.is_empty() {
1410 mk_sp(field.span.lo(), field.span.lo())
1412 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1414 let mut spacing = String::from(if field.ident.is_some() {
1415 type_annotation_spacing.1
1419 // Try to put everything on a single line.
1420 let attr_prefix = combine_strs_with_missing_comments(
1428 let overhead = last_line_width(&attr_prefix);
1429 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1430 for _ in 0..lhs_offset {
1433 // In this extreme case we will be missing a space betweeen an attribute and a field.
1434 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1437 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1438 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1439 if !ty.contains('\n') {
1440 return Some(attr_prefix + &spacing + ty);
1444 // We must use multiline.
1445 let new_shape = shape.with_max_width(context.config);
1446 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1448 let field_str = if prefix.is_empty() {
1450 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1451 prefix + " " + &ty_rewritten
1453 let type_offset = shape.indent.block_indent(context.config);
1454 let nested_shape = Shape::indented(type_offset, context.config);
1455 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1456 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1458 combine_strs_with_missing_comments(
1468 pub fn rewrite_static(
1470 vis: &ast::Visibility,
1473 mutability: ast::Mutability,
1474 expr_opt: Option<&ptr::P<ast::Expr>>,
1477 context: &RewriteContext,
1478 ) -> Option<String> {
1479 let colon = colon_spaces(
1480 context.config.space_before_type_annotation(),
1481 context.config.space_after_type_annotation_colon(),
1483 let prefix = format!(
1485 format_visibility(vis),
1487 format_mutability(mutability),
1492 let ty_str = ty.rewrite(
1494 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1497 if let Some(expr) = expr_opt {
1498 let lhs = format!("{}{} =", prefix, ty_str);
1500 let remaining_width = context.budget(offset.block_indent + 1);
1505 Shape::legacy(remaining_width, offset.block_only()),
1506 ).and_then(|res| recover_comment_removed(res, span, context))
1507 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1509 Some(format!("{}{};", prefix, ty_str))
1513 pub fn rewrite_associated_type(
1515 ty_opt: Option<&ptr::P<ast::Ty>>,
1516 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1517 context: &RewriteContext,
1519 ) -> Option<String> {
1520 let prefix = format!("type {}", ident);
1522 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1524 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1525 let bounds: &[_] = ty_param_bounds;
1526 let bound_str = bounds
1528 .map(|ty_bound| ty_bound.rewrite(context, shape))
1529 .collect::<Option<Vec<_>>>()?;
1530 if !bounds.is_empty() {
1531 format!(": {}", join_bounds(context, shape, &bound_str))
1539 if let Some(ty) = ty_opt {
1540 let ty_str = ty.rewrite(
1543 context.budget(indent.block_indent + prefix.len() + 2),
1544 indent.block_only(),
1547 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1549 Some(format!("{}{};", prefix, type_bounds_str))
1553 pub fn rewrite_associated_impl_type(
1555 defaultness: ast::Defaultness,
1556 ty_opt: Option<&ptr::P<ast::Ty>>,
1557 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1558 context: &RewriteContext,
1560 ) -> Option<String> {
1561 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1564 ast::Defaultness::Default => Some(format!("default {}", result)),
1569 impl Rewrite for ast::FunctionRetTy {
1570 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1572 ast::FunctionRetTy::Default(_) => Some(String::new()),
1573 ast::FunctionRetTy::Ty(ref ty) => {
1574 let inner_width = shape.width.checked_sub(3)?;
1575 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1576 .map(|r| format!("-> {}", r))
1582 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1584 ast::TyKind::Infer => {
1585 let original = context.snippet(ty.span);
1592 impl Rewrite for ast::Arg {
1593 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1594 if is_named_arg(self) {
1595 let mut result = self.pat
1596 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1598 if !is_empty_infer(context, &*self.ty) {
1599 if context.config.space_before_type_annotation() {
1600 result.push_str(" ");
1602 result.push_str(":");
1603 if context.config.space_after_type_annotation_colon() {
1604 result.push_str(" ");
1606 let overhead = last_line_width(&result);
1607 let max_width = shape.width.checked_sub(overhead)?;
1608 let ty_str = self.ty
1609 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1610 result.push_str(&ty_str);
1615 self.ty.rewrite(context, shape)
1620 fn rewrite_explicit_self(
1621 explicit_self: &ast::ExplicitSelf,
1623 context: &RewriteContext,
1624 ) -> Option<String> {
1625 match explicit_self.node {
1626 ast::SelfKind::Region(lt, m) => {
1627 let mut_str = format_mutability(m);
1630 let lifetime_str = l.rewrite(
1632 Shape::legacy(context.config.max_width(), Indent::empty()),
1634 Some(format!("&{} {}self", lifetime_str, mut_str))
1636 None => Some(format!("&{}self", mut_str)),
1639 ast::SelfKind::Explicit(ref ty, _) => {
1640 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1642 let mutability = explicit_self_mutability(&args[0]);
1643 let type_str = ty.rewrite(
1645 Shape::legacy(context.config.max_width(), Indent::empty()),
1650 format_mutability(mutability),
1654 ast::SelfKind::Value(_) => {
1655 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1657 let mutability = explicit_self_mutability(&args[0]);
1659 Some(format!("{}self", format_mutability(mutability)))
1664 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1665 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1666 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1667 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1674 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1675 if is_named_arg(arg) {
1682 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1684 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1685 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1686 _ => arg.ty.span.hi(),
1690 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1691 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1692 ident.node != symbol::keywords::Invalid.ident()
1698 // Return type is (result, force_new_line_for_brace)
1700 context: &RewriteContext,
1705 newline_brace: bool,
1707 ) -> Option<(String, bool)> {
1708 let mut force_new_line_for_brace = false;
1710 let where_clause = &fn_sig.generics.where_clause;
1712 let mut result = String::with_capacity(1024);
1713 result.push_str(&fn_sig.to_str(context));
1716 result.push_str("fn ");
1717 result.push_str(&ident.to_string());
1720 let overhead = if has_body && !newline_brace {
1727 let used_width = last_line_used_width(&result, indent.width());
1728 let one_line_budget = context.budget(used_width + overhead);
1730 width: one_line_budget,
1734 let fd = fn_sig.decl;
1735 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1736 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1737 result.push_str(&generics_str);
1739 let snuggle_angle_bracket = generics_str
1742 .map_or(false, |l| l.trim_left().len() == 1);
1744 // Note that the width and indent don't really matter, we'll re-layout the
1745 // return type later anyway.
1746 let ret_str = fd.output
1747 .rewrite(context, Shape::indented(indent, context.config))?;
1749 let multi_line_ret_str = ret_str.contains('\n');
1750 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1753 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1764 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1770 // Check if vertical layout was forced.
1771 if one_line_budget == 0 {
1772 if snuggle_angle_bracket {
1774 } else if context.config.fn_args_paren_newline() {
1776 result.push_str(&arg_indent.to_string(context.config));
1777 if context.config.fn_args_indent() == IndentStyle::Visual {
1778 arg_indent = arg_indent + 1; // extra space for `(`
1782 result.push_str("(");
1783 if context.config.fn_args_indent() == IndentStyle::Visual {
1785 result.push_str(&arg_indent.to_string(context.config));
1791 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1795 // Skip `pub(crate)`.
1796 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1797 // A conservative estimation, to goal is to be over all parens in generics
1798 let args_start = fn_sig
1802 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1803 let args_end = if fd.inputs.is_empty() {
1806 .span_after(mk_sp(args_start, span.hi()), ")")
1808 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1809 context.codemap.span_after(last_span, ")")
1811 let args_span = mk_sp(
1814 .span_after(mk_sp(args_start, span.hi()), "("),
1817 let arg_str = rewrite_args(
1820 fd.get_self().as_ref(),
1827 generics_str.contains('\n'),
1830 let put_args_in_block = match context.config.fn_args_indent() {
1831 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1833 } && !fd.inputs.is_empty();
1835 let mut args_last_line_contains_comment = false;
1836 if put_args_in_block {
1837 arg_indent = indent.block_indent(context.config);
1839 result.push_str(&arg_indent.to_string(context.config));
1840 result.push_str(&arg_str);
1842 result.push_str(&indent.to_string(context.config));
1845 result.push_str(&arg_str);
1846 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1847 // Put the closing brace on the next line if it overflows the max width.
1849 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1852 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1855 // If the last line of args contains comment, we cannot put the closing paren
1856 // on the same line.
1860 .map_or(false, |last_line| last_line.contains("//"))
1862 args_last_line_contains_comment = true;
1864 result.push_str(&arg_indent.to_string(context.config));
1870 if let ast::FunctionRetTy::Ty(..) = fd.output {
1871 let ret_should_indent = match context.config.fn_args_indent() {
1872 // If our args are block layout then we surely must have space.
1873 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1874 _ if args_last_line_contains_comment => false,
1875 _ if result.contains('\n') || multi_line_ret_str => true,
1877 // If the return type would push over the max width, then put the return type on
1878 // a new line. With the +1 for the signature length an additional space between
1879 // the closing parenthesis of the argument and the arrow '->' is considered.
1880 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1882 // If there is no where clause, take into account the space after the return type
1884 if where_clause.predicates.is_empty() {
1888 sig_length > context.config.max_width()
1891 let ret_indent = if ret_should_indent {
1892 let indent = match context.config.fn_return_indent() {
1893 ReturnIndent::WithWhereClause => indent + 4,
1894 // Aligning with non-existent args looks silly.
1895 _ if arg_str.is_empty() => {
1896 force_new_line_for_brace = true;
1899 // FIXME: we might want to check that using the arg indent
1900 // doesn't blow our budget, and if it does, then fallback to
1901 // the where clause indent.
1906 result.push_str(&indent.to_string(context.config));
1910 Indent::new(indent.block_indent, last_line_width(&result))
1913 if multi_line_ret_str || ret_should_indent {
1914 // Now that we know the proper indent and width, we need to
1915 // re-layout the return type.
1916 let ret_str = fd.output
1917 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1918 result.push_str(&ret_str);
1920 result.push_str(&ret_str);
1923 // Comment between return type and the end of the decl.
1924 let snippet_lo = fd.output.span().hi();
1925 if where_clause.predicates.is_empty() {
1926 let snippet_hi = span.hi();
1927 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1928 // Try to preserve the layout of the original snippet.
1929 let original_starts_with_newline = snippet
1931 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1932 let original_ends_with_newline = snippet
1933 .rfind(|c| c != ' ')
1934 .map_or(false, |i| snippet[i..].ends_with('\n'));
1935 let snippet = snippet.trim();
1936 if !snippet.is_empty() {
1937 result.push(if original_starts_with_newline {
1942 result.push_str(snippet);
1943 if original_ends_with_newline {
1944 force_new_line_for_brace = true;
1950 let should_compress_where = match context.config.where_density() {
1951 Density::Compressed => !result.contains('\n'),
1952 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1956 let pos_before_where = match fd.output {
1957 ast::FunctionRetTy::Default(..) => args_span.hi(),
1958 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1961 let is_args_multi_lined = arg_str.contains('\n');
1963 if where_clause.predicates.len() == 1 && should_compress_where {
1964 let budget = context.budget(last_line_used_width(&result, indent.width()));
1965 if let Some(where_clause_str) = rewrite_where_clause(
1968 context.config.fn_brace_style(),
1969 Shape::legacy(budget, indent),
1970 Density::Compressed,
1974 WhereClauseOption::compressed(),
1975 is_args_multi_lined,
1977 result.push_str(&where_clause_str);
1978 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1979 return Some((result, force_new_line_for_brace));
1983 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1984 let where_clause_str = rewrite_where_clause(
1987 context.config.fn_brace_style(),
1988 Shape::indented(indent, context.config),
1994 is_args_multi_lined,
1996 // If there are neither where clause nor return type, we may be missing comments between
1998 if where_clause_str.is_empty() {
1999 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2000 match recover_missing_comment_in_span(
2001 mk_sp(args_span.hi(), ret_span.hi()),
2004 last_line_width(&result),
2006 Some(ref missing_comment) if !missing_comment.is_empty() => {
2007 result.push_str(missing_comment);
2008 force_new_line_for_brace = true;
2015 result.push_str(&where_clause_str);
2017 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2018 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2019 Some((result, force_new_line_for_brace))
2022 #[derive(Copy, Clone)]
2023 struct WhereClauseOption {
2024 suppress_comma: bool, // Force no trailing comma
2025 snuggle: bool, // Do not insert newline before `where`
2026 compress_where: bool, // Try single line where clause instead of vertical layout
2029 impl WhereClauseOption {
2030 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2032 suppress_comma: suppress_comma,
2034 compress_where: false,
2038 pub fn compressed() -> WhereClauseOption {
2040 suppress_comma: true,
2042 compress_where: true,
2046 pub fn snuggled(current: &str) -> WhereClauseOption {
2048 suppress_comma: false,
2049 snuggle: trimmed_last_line_width(current) == 1,
2050 compress_where: false,
2056 context: &RewriteContext,
2058 explicit_self: Option<&ast::ExplicitSelf>,
2059 one_line_budget: usize,
2060 multi_line_budget: usize,
2065 generics_str_contains_newline: bool,
2066 ) -> Option<String> {
2067 let mut arg_item_strs = args.iter()
2068 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2069 .collect::<Option<Vec<_>>>()?;
2071 // Account for sugary self.
2072 // FIXME: the comment for the self argument is dropped. This is blocked
2073 // on rust issue #27522.
2074 let min_args = explicit_self
2075 .and_then(|explicit_self| {
2076 rewrite_explicit_self(explicit_self, args, context)
2078 .map_or(1, |self_str| {
2079 arg_item_strs[0] = self_str;
2083 // Comments between args.
2084 let mut arg_items = Vec::new();
2086 arg_items.push(ListItem::from_str(""));
2089 // FIXME(#21): if there are no args, there might still be a comment, but
2090 // without spans for the comment or parens, there is no chance of
2091 // getting it right. You also don't get to put a comment on self, unless
2093 if args.len() >= min_args || variadic {
2094 let comment_span_start = if min_args == 2 {
2095 let second_arg_start = if arg_has_pattern(&args[1]) {
2096 args[1].pat.span.lo()
2098 args[1].ty.span.lo()
2100 let reduced_span = mk_sp(span.lo(), second_arg_start);
2102 context.codemap.span_after_last(reduced_span, ",")
2107 enum ArgumentKind<'a> {
2108 Regular(&'a ast::Arg),
2112 let variadic_arg = if variadic {
2113 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2114 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2115 Some(ArgumentKind::Variadic(variadic_start))
2120 let more_items = itemize_list(
2122 args[min_args - 1..]
2124 .map(ArgumentKind::Regular)
2125 .chain(variadic_arg),
2128 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2129 ArgumentKind::Variadic(start) => start,
2132 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2133 ArgumentKind::Variadic(start) => start + BytePos(3),
2136 ArgumentKind::Regular(..) => None,
2137 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2144 arg_items.extend(more_items);
2147 let fits_in_one_line = !generics_str_contains_newline
2148 && (arg_items.is_empty()
2149 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2151 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2152 item.item = Some(arg);
2155 let last_line_ends_with_comment = arg_items
2158 .and_then(|item| item.post_comment.as_ref())
2159 .map_or(false, |s| s.trim().starts_with("//"));
2161 let (indent, trailing_comma) = match context.config.fn_args_indent() {
2162 IndentStyle::Block if fits_in_one_line => {
2163 (indent.block_indent(context.config), SeparatorTactic::Never)
2165 IndentStyle::Block => (
2166 indent.block_indent(context.config),
2167 context.config.trailing_comma(),
2169 IndentStyle::Visual if last_line_ends_with_comment => {
2170 (arg_indent, context.config.trailing_comma())
2172 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2175 let tactic = definitive_tactic(
2177 context.config.fn_args_density().to_list_tactic(),
2181 let budget = match tactic {
2182 DefinitiveListTactic::Horizontal => one_line_budget,
2183 _ => multi_line_budget,
2186 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2188 let fmt = ListFormatting {
2191 trailing_separator: if variadic {
2192 SeparatorTactic::Never
2196 separator_place: SeparatorPlace::Back,
2197 shape: Shape::legacy(budget, indent),
2198 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_indent()),
2199 preserve_newline: true,
2200 config: context.config,
2203 write_list(&arg_items, &fmt)
2206 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2207 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2208 ident.node != symbol::keywords::Invalid.ident()
2214 fn compute_budgets_for_args(
2215 context: &RewriteContext,
2219 newline_brace: bool,
2221 force_vertical_layout: bool,
2222 ) -> Option<((usize, usize, Indent))> {
2224 "compute_budgets_for_args {} {:?}, {}, {}",
2230 // Try keeping everything on the same line.
2231 if !result.contains('\n') && !force_vertical_layout {
2232 // 2 = `()`, 3 = `() `, space is before ret_string.
2233 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2234 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2244 let one_line_budget = context.budget(used_space);
2246 if one_line_budget > 0 {
2248 let (indent, multi_line_budget) = match context.config.fn_args_indent() {
2249 IndentStyle::Block => {
2250 let indent = indent.block_indent(context.config);
2251 (indent, context.budget(indent.width() + 1))
2253 IndentStyle::Visual => {
2254 let indent = indent + result.len() + 1;
2255 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2256 (indent, context.budget(multi_line_overhead))
2260 return Some((one_line_budget, multi_line_budget, indent));
2264 // Didn't work. we must force vertical layout and put args on a newline.
2265 let new_indent = indent.block_indent(context.config);
2266 let used_space = match context.config.fn_args_indent() {
2268 IndentStyle::Block => new_indent.width() + 1,
2269 // Account for `)` and possibly ` {`.
2270 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2272 Some((0, context.budget(used_space), new_indent))
2275 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2276 let predicate_count = where_clause.predicates.len();
2278 if config.where_single_line() && predicate_count == 1 {
2281 match (config.fn_brace_style(), config.where_density()) {
2282 (BraceStyle::AlwaysNextLine, _) => true,
2283 (_, Density::Compressed) if predicate_count == 1 => false,
2284 (_, Density::CompressedIfEmpty) if predicate_count == 1 && !has_body => false,
2285 (BraceStyle::SameLineWhere, _) if predicate_count > 0 => true,
2290 fn rewrite_generics(
2291 context: &RewriteContext,
2292 generics: &ast::Generics,
2295 ) -> Option<String> {
2296 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2297 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2298 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2299 rewrite_generics_inner(context, generics, g_shape, 0, span)
2303 fn rewrite_generics_inner(
2304 context: &RewriteContext,
2305 generics: &ast::Generics,
2307 one_line_width: usize,
2309 ) -> Option<String> {
2310 // FIXME: convert bounds to where clauses where they get too big or if
2311 // there is a where clause at all.
2314 enum GenericsArg<'a> {
2315 Lifetime(&'a ast::LifetimeDef),
2316 TyParam(&'a ast::TyParam),
2318 impl<'a> Rewrite for GenericsArg<'a> {
2319 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2321 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2322 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2326 impl<'a> Spanned for GenericsArg<'a> {
2327 fn span(&self) -> Span {
2329 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2330 GenericsArg::TyParam(ref ty) => ty.span(),
2335 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2336 return Some(String::new());
2339 let generics_args = generics
2342 .map(|lt| GenericsArg::Lifetime(lt))
2343 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2344 let items = itemize_list(
2348 |arg| arg.span().lo(),
2349 |arg| arg.span().hi(),
2350 |arg| arg.rewrite(context, shape),
2351 context.codemap.span_after(span, "<"),
2355 format_generics_item_list(context, items, shape, one_line_width)
2358 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2359 match config.generics_indent() {
2360 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2361 IndentStyle::Block => {
2365 .block_indent(config.tab_spaces())
2366 .with_max_width(config)
2372 pub fn format_generics_item_list<I>(
2373 context: &RewriteContext,
2376 one_line_budget: usize,
2379 I: Iterator<Item = ListItem>,
2381 let item_vec = items.collect::<Vec<_>>();
2383 let tactic = definitive_tactic(
2385 ListTactic::HorizontalVertical,
2389 let fmt = ListFormatting {
2392 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2393 SeparatorTactic::Never
2395 context.config.trailing_comma()
2397 separator_place: SeparatorPlace::Back,
2399 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2400 preserve_newline: true,
2401 config: context.config,
2404 let list_str = write_list(&item_vec, &fmt)?;
2406 Some(wrap_generics_with_angle_brackets(
2413 pub fn wrap_generics_with_angle_brackets(
2414 context: &RewriteContext,
2416 list_offset: Indent,
2418 if context.config.generics_indent() == IndentStyle::Block
2419 && (list_str.contains('\n') || list_str.ends_with(','))
2423 list_offset.to_string(context.config),
2426 .block_unindent(context.config)
2427 .to_string(context.config)
2429 } else if context.config.spaces_within_angle_brackets() {
2430 format!("< {} >", list_str)
2432 format!("<{}>", list_str)
2436 fn rewrite_trait_bounds(
2437 context: &RewriteContext,
2438 type_param_bounds: &ast::TyParamBounds,
2440 ) -> Option<String> {
2441 let bounds: &[_] = type_param_bounds;
2443 if bounds.is_empty() {
2444 return Some(String::new());
2446 let bound_str = bounds
2448 .map(|ty_bound| ty_bound.rewrite(context, shape))
2449 .collect::<Option<Vec<_>>>()?;
2450 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2453 fn rewrite_where_clause_rfc_style(
2454 context: &RewriteContext,
2455 where_clause: &ast::WhereClause,
2458 span_end: Option<BytePos>,
2459 span_end_before_where: BytePos,
2460 where_clause_option: WhereClauseOption,
2461 is_args_multi_line: bool,
2462 ) -> Option<String> {
2463 let block_shape = shape.block().with_max_width(context.config);
2465 let (span_before, span_after) =
2466 missing_span_before_after_where(span_end_before_where, where_clause);
2467 let (comment_before, comment_after) =
2468 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2470 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2473 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2476 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2478 let clause_shape = clause_shape.sub_width(1)?;
2479 // each clause on one line, trailing comma (except if suppress_comma)
2480 let span_start = where_clause.predicates[0].span().lo();
2481 // If we don't have the start of the next span, then use the end of the
2482 // predicates, but that means we miss comments.
2483 let len = where_clause.predicates.len();
2484 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2485 let span_end = span_end.unwrap_or(end_of_preds);
2486 let items = itemize_list(
2488 where_clause.predicates.iter(),
2490 |pred| pred.span().lo(),
2491 |pred| pred.span().hi(),
2492 |pred| pred.rewrite(context, clause_shape),
2497 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2498 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2499 SeparatorTactic::Never
2501 context.config.trailing_comma()
2504 // shape should be vertical only and only if we have `where_single_line` option enabled
2505 // and the number of items of the where clause is equal to 1
2506 let shape_tactic = if where_single_line {
2507 DefinitiveListTactic::Horizontal
2509 DefinitiveListTactic::Vertical
2512 let fmt = ListFormatting {
2513 tactic: shape_tactic,
2515 trailing_separator: comma_tactic,
2516 separator_place: SeparatorPlace::Back,
2517 shape: clause_shape,
2518 ends_with_newline: true,
2519 preserve_newline: true,
2520 config: context.config,
2522 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2524 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2527 format!("\n{}", shape.indent.to_string(context.config))
2529 let newline_before_where = comment_separator(&comment_before, shape);
2530 let newline_after_where = comment_separator(&comment_after, clause_shape);
2533 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2534 && comment_after.is_empty() && !preds_str.contains('\n')
2535 && 6 + preds_str.len() <= shape.width || where_single_line
2539 format!("\n{}", clause_shape.indent.to_string(context.config))
2542 "{}{}{}where{}{}{}{}",
2545 newline_before_where,
2546 newline_after_where,
2553 fn rewrite_where_clause(
2554 context: &RewriteContext,
2555 where_clause: &ast::WhereClause,
2556 brace_style: BraceStyle,
2560 span_end: Option<BytePos>,
2561 span_end_before_where: BytePos,
2562 where_clause_option: WhereClauseOption,
2563 is_args_multi_line: bool,
2564 ) -> Option<String> {
2565 if where_clause.predicates.is_empty() {
2566 return Some(String::new());
2569 if context.config.where_style() == Style::Rfc {
2570 return rewrite_where_clause_rfc_style(
2576 span_end_before_where,
2577 where_clause_option,
2582 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2584 let offset = match context.config.where_pred_indent() {
2585 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2586 // 6 = "where ".len()
2587 IndentStyle::Visual => shape.indent + extra_indent + 6,
2589 // FIXME: if where_pred_indent != Visual, then the budgets below might
2590 // be out by a char or two.
2592 let budget = context.config.max_width() - offset.width();
2593 let span_start = where_clause.predicates[0].span().lo();
2594 // If we don't have the start of the next span, then use the end of the
2595 // predicates, but that means we miss comments.
2596 let len = where_clause.predicates.len();
2597 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2598 let span_end = span_end.unwrap_or(end_of_preds);
2599 let items = itemize_list(
2601 where_clause.predicates.iter(),
2603 |pred| pred.span().lo(),
2604 |pred| pred.span().hi(),
2605 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2610 let item_vec = items.collect::<Vec<_>>();
2611 // FIXME: we don't need to collect here if the where_layout isn't
2612 // HorizontalVertical.
2613 let tactic = definitive_tactic(
2615 context.config.where_layout(),
2620 let mut comma_tactic = context.config.trailing_comma();
2621 // Kind of a hack because we don't usually have trailing commas in where clauses.
2622 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2623 comma_tactic = SeparatorTactic::Never;
2626 let fmt = ListFormatting {
2629 trailing_separator: comma_tactic,
2630 separator_place: SeparatorPlace::Back,
2631 shape: Shape::legacy(budget, offset),
2632 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2633 preserve_newline: true,
2634 config: context.config,
2636 let preds_str = write_list(&item_vec, &fmt)?;
2638 let end_length = if terminator == "{" {
2639 // If the brace is on the next line we don't need to count it otherwise it needs two
2642 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2643 BraceStyle::PreferSameLine => 2,
2645 } else if terminator == "=" {
2650 if density == Density::Tall || preds_str.contains('\n')
2651 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2655 (shape.indent + extra_indent).to_string(context.config),
2659 Some(format!(" where {}", preds_str))
2663 fn missing_span_before_after_where(
2664 before_item_span_end: BytePos,
2665 where_clause: &ast::WhereClause,
2667 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2669 let pos_after_where = where_clause.span.lo() + BytePos(5);
2670 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2671 (missing_span_before, missing_span_after)
2674 fn rewrite_comments_before_after_where(
2675 context: &RewriteContext,
2676 span_before_where: Span,
2677 span_after_where: Span,
2679 ) -> Option<(String, String)> {
2680 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2681 let after_comment = rewrite_missing_comment(
2683 shape.block_indent(context.config.tab_spaces()),
2686 Some((before_comment, after_comment))
2689 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2690 format!("{}{}{}", format_visibility(vis), item_name, ident)
2694 context: &RewriteContext,
2695 generics: &ast::Generics,
2698 brace_style: BraceStyle,
2699 force_same_line_brace: bool,
2703 ) -> Option<String> {
2704 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2705 let mut result = rewrite_generics(context, generics, shape, span)?;
2707 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2708 let budget = context.budget(last_line_used_width(&result, offset.width()));
2709 let option = WhereClauseOption::snuggled(&result);
2710 // If the generics are not parameterized then generics.span.hi() == 0,
2711 // so we use span.lo(), which is the position after `struct Foo`.
2712 let span_end_before_where = if generics.is_parameterized() {
2717 let where_clause_str = rewrite_where_clause(
2719 &generics.where_clause,
2721 Shape::legacy(budget, offset.block_only()),
2725 span_end_before_where,
2729 result.push_str(&where_clause_str);
2730 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2731 || (generics.where_clause.predicates.is_empty()
2732 && trimmed_last_line_width(&result) == 1)
2734 force_same_line_brace || trimmed_last_line_width(&result) == 1
2735 || brace_style != BraceStyle::AlwaysNextLine
2737 let total_used_width = last_line_used_width(&result, used_width);
2738 let remaining_budget = context.budget(total_used_width);
2739 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2740 // and hence we take the closer into account as well for one line budget.
2741 // We assume that the closer has the same length as the opener.
2742 let overhead = if force_same_line_brace {
2743 1 + opener.len() + opener.len()
2747 let forbid_same_line_brace = overhead > remaining_budget;
2748 if !forbid_same_line_brace && same_line_brace {
2752 result.push_str(&offset.block_only().to_string(context.config));
2754 result.push_str(opener);
2759 impl Rewrite for ast::ForeignItem {
2760 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2761 let attrs_str = self.attrs.rewrite(context, shape)?;
2762 // Drop semicolon or it will be interpreted as comment.
2763 // FIXME: this may be a faulty span from libsyntax.
2764 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2766 let item_str = match self.node {
2767 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2771 &FnSig::new(fn_decl, generics, self.vis.clone()),
2775 ).map(|(s, _)| format!("{};", s)),
2776 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2777 // FIXME(#21): we're dropping potential comments in between the
2778 // function keywords here.
2779 let vis = format_visibility(&self.vis);
2780 let mut_str = if is_mutable { "mut " } else { "" };
2781 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2783 let shape = shape.sub_width(1)?;
2784 ty.rewrite(context, shape).map(|ty_str| {
2785 // 1 = space between prefix and type.
2786 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2789 let nested_indent = shape.indent.block_indent(context.config);
2790 format!("\n{}", nested_indent.to_string(context.config))
2792 format!("{}{}{};", prefix, sep, ty_str)
2795 ast::ForeignItemKind::Ty => {
2796 let vis = format_visibility(&self.vis);
2797 Some(format!("{}type {};", vis, self.ident))
2801 let missing_span = if self.attrs.is_empty() {
2802 mk_sp(self.span.lo(), self.span.lo())
2804 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2806 combine_strs_with_missing_comments(