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 struct StaticParts<'a> {
1465 vis: &'a ast::Visibility,
1468 mutability: ast::Mutability,
1469 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1472 impl<'a> StaticParts<'a> {
1474 vis: &'a ast::Visibility,
1477 mutability: ast::Mutability,
1478 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1479 ) -> StaticParts<'a> {
1490 pub fn rewrite_static(
1492 static_parts: &StaticParts,
1495 context: &RewriteContext,
1496 ) -> Option<String> {
1504 let colon = colon_spaces(
1505 context.config.space_before_type_annotation(),
1506 context.config.space_after_type_annotation_colon(),
1508 let prefix = format!(
1510 format_visibility(vis),
1512 format_mutability(mutability),
1517 let ty_str = ty.rewrite(
1519 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1522 if let Some(expr) = expr_opt {
1523 let lhs = format!("{}{} =", prefix, ty_str);
1525 let remaining_width = context.budget(offset.block_indent + 1);
1530 Shape::legacy(remaining_width, offset.block_only()),
1531 ).and_then(|res| recover_comment_removed(res, span, context))
1532 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1534 Some(format!("{}{};", prefix, ty_str))
1538 pub fn rewrite_associated_type(
1540 ty_opt: Option<&ptr::P<ast::Ty>>,
1541 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1542 context: &RewriteContext,
1544 ) -> Option<String> {
1545 let prefix = format!("type {}", ident);
1547 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1549 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1550 let bounds: &[_] = ty_param_bounds;
1551 let bound_str = bounds
1553 .map(|ty_bound| ty_bound.rewrite(context, shape))
1554 .collect::<Option<Vec<_>>>()?;
1555 if !bounds.is_empty() {
1556 format!(": {}", join_bounds(context, shape, &bound_str))
1564 if let Some(ty) = ty_opt {
1565 let ty_str = ty.rewrite(
1568 context.budget(indent.block_indent + prefix.len() + 2),
1569 indent.block_only(),
1572 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1574 Some(format!("{}{};", prefix, type_bounds_str))
1578 pub fn rewrite_associated_impl_type(
1580 defaultness: ast::Defaultness,
1581 ty_opt: Option<&ptr::P<ast::Ty>>,
1582 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1583 context: &RewriteContext,
1585 ) -> Option<String> {
1586 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1589 ast::Defaultness::Default => Some(format!("default {}", result)),
1594 impl Rewrite for ast::FunctionRetTy {
1595 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1597 ast::FunctionRetTy::Default(_) => Some(String::new()),
1598 ast::FunctionRetTy::Ty(ref ty) => {
1599 let inner_width = shape.width.checked_sub(3)?;
1600 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1601 .map(|r| format!("-> {}", r))
1607 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1609 ast::TyKind::Infer => {
1610 let original = context.snippet(ty.span);
1617 impl Rewrite for ast::Arg {
1618 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1619 if is_named_arg(self) {
1620 let mut result = self.pat
1621 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1623 if !is_empty_infer(context, &*self.ty) {
1624 if context.config.space_before_type_annotation() {
1625 result.push_str(" ");
1627 result.push_str(":");
1628 if context.config.space_after_type_annotation_colon() {
1629 result.push_str(" ");
1631 let overhead = last_line_width(&result);
1632 let max_width = shape.width.checked_sub(overhead)?;
1633 let ty_str = self.ty
1634 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1635 result.push_str(&ty_str);
1640 self.ty.rewrite(context, shape)
1645 fn rewrite_explicit_self(
1646 explicit_self: &ast::ExplicitSelf,
1648 context: &RewriteContext,
1649 ) -> Option<String> {
1650 match explicit_self.node {
1651 ast::SelfKind::Region(lt, m) => {
1652 let mut_str = format_mutability(m);
1655 let lifetime_str = l.rewrite(
1657 Shape::legacy(context.config.max_width(), Indent::empty()),
1659 Some(format!("&{} {}self", lifetime_str, mut_str))
1661 None => Some(format!("&{}self", mut_str)),
1664 ast::SelfKind::Explicit(ref ty, _) => {
1665 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1667 let mutability = explicit_self_mutability(&args[0]);
1668 let type_str = ty.rewrite(
1670 Shape::legacy(context.config.max_width(), Indent::empty()),
1675 format_mutability(mutability),
1679 ast::SelfKind::Value(_) => {
1680 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1682 let mutability = explicit_self_mutability(&args[0]);
1684 Some(format!("{}self", format_mutability(mutability)))
1689 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1690 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1691 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1692 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1699 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1700 if is_named_arg(arg) {
1707 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1709 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1710 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1711 _ => arg.ty.span.hi(),
1715 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1716 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1717 ident.node != symbol::keywords::Invalid.ident()
1723 // Return type is (result, force_new_line_for_brace)
1725 context: &RewriteContext,
1730 newline_brace: bool,
1732 ) -> Option<(String, bool)> {
1733 let mut force_new_line_for_brace = false;
1735 let where_clause = &fn_sig.generics.where_clause;
1737 let mut result = String::with_capacity(1024);
1738 result.push_str(&fn_sig.to_str(context));
1741 result.push_str("fn ");
1742 result.push_str(&ident.to_string());
1745 let overhead = if has_body && !newline_brace {
1752 let used_width = last_line_used_width(&result, indent.width());
1753 let one_line_budget = context.budget(used_width + overhead);
1755 width: one_line_budget,
1759 let fd = fn_sig.decl;
1760 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1761 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1762 result.push_str(&generics_str);
1764 let snuggle_angle_bracket = generics_str
1767 .map_or(false, |l| l.trim_left().len() == 1);
1769 // Note that the width and indent don't really matter, we'll re-layout the
1770 // return type later anyway.
1771 let ret_str = fd.output
1772 .rewrite(context, Shape::indented(indent, context.config))?;
1774 let multi_line_ret_str = ret_str.contains('\n');
1775 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1778 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1789 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1795 // Check if vertical layout was forced.
1796 if one_line_budget == 0 {
1797 if snuggle_angle_bracket {
1799 } else if context.config.fn_args_paren_newline() {
1801 result.push_str(&arg_indent.to_string(context.config));
1802 if context.config.fn_args_indent() == IndentStyle::Visual {
1803 arg_indent = arg_indent + 1; // extra space for `(`
1807 result.push_str("(");
1808 if context.config.fn_args_indent() == IndentStyle::Visual {
1810 result.push_str(&arg_indent.to_string(context.config));
1816 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1820 // Skip `pub(crate)`.
1821 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1822 // A conservative estimation, to goal is to be over all parens in generics
1823 let args_start = fn_sig
1827 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1828 let args_end = if fd.inputs.is_empty() {
1831 .span_after(mk_sp(args_start, span.hi()), ")")
1833 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1834 context.codemap.span_after(last_span, ")")
1836 let args_span = mk_sp(
1839 .span_after(mk_sp(args_start, span.hi()), "("),
1842 let arg_str = rewrite_args(
1845 fd.get_self().as_ref(),
1852 generics_str.contains('\n'),
1855 let put_args_in_block = match context.config.fn_args_indent() {
1856 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1858 } && !fd.inputs.is_empty();
1860 let mut args_last_line_contains_comment = false;
1861 if put_args_in_block {
1862 arg_indent = indent.block_indent(context.config);
1864 result.push_str(&arg_indent.to_string(context.config));
1865 result.push_str(&arg_str);
1867 result.push_str(&indent.to_string(context.config));
1870 result.push_str(&arg_str);
1871 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1872 // Put the closing brace on the next line if it overflows the max width.
1874 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1877 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1880 // If the last line of args contains comment, we cannot put the closing paren
1881 // on the same line.
1885 .map_or(false, |last_line| last_line.contains("//"))
1887 args_last_line_contains_comment = true;
1889 result.push_str(&arg_indent.to_string(context.config));
1895 if let ast::FunctionRetTy::Ty(..) = fd.output {
1896 let ret_should_indent = match context.config.fn_args_indent() {
1897 // If our args are block layout then we surely must have space.
1898 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1899 _ if args_last_line_contains_comment => false,
1900 _ if result.contains('\n') || multi_line_ret_str => true,
1902 // If the return type would push over the max width, then put the return type on
1903 // a new line. With the +1 for the signature length an additional space between
1904 // the closing parenthesis of the argument and the arrow '->' is considered.
1905 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1907 // If there is no where clause, take into account the space after the return type
1909 if where_clause.predicates.is_empty() {
1913 sig_length > context.config.max_width()
1916 let ret_indent = if ret_should_indent {
1917 let indent = match context.config.fn_return_indent() {
1918 ReturnIndent::WithWhereClause => indent + 4,
1919 // Aligning with non-existent args looks silly.
1920 _ if arg_str.is_empty() => {
1921 force_new_line_for_brace = true;
1924 // FIXME: we might want to check that using the arg indent
1925 // doesn't blow our budget, and if it does, then fallback to
1926 // the where clause indent.
1931 result.push_str(&indent.to_string(context.config));
1935 Indent::new(indent.block_indent, last_line_width(&result))
1938 if multi_line_ret_str || ret_should_indent {
1939 // Now that we know the proper indent and width, we need to
1940 // re-layout the return type.
1941 let ret_str = fd.output
1942 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1943 result.push_str(&ret_str);
1945 result.push_str(&ret_str);
1948 // Comment between return type and the end of the decl.
1949 let snippet_lo = fd.output.span().hi();
1950 if where_clause.predicates.is_empty() {
1951 let snippet_hi = span.hi();
1952 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1953 // Try to preserve the layout of the original snippet.
1954 let original_starts_with_newline = snippet
1956 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1957 let original_ends_with_newline = snippet
1958 .rfind(|c| c != ' ')
1959 .map_or(false, |i| snippet[i..].ends_with('\n'));
1960 let snippet = snippet.trim();
1961 if !snippet.is_empty() {
1962 result.push(if original_starts_with_newline {
1967 result.push_str(snippet);
1968 if original_ends_with_newline {
1969 force_new_line_for_brace = true;
1975 let should_compress_where = match context.config.where_density() {
1976 Density::Compressed => !result.contains('\n'),
1977 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1981 let pos_before_where = match fd.output {
1982 ast::FunctionRetTy::Default(..) => args_span.hi(),
1983 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1986 let is_args_multi_lined = arg_str.contains('\n');
1988 if where_clause.predicates.len() == 1 && should_compress_where {
1989 let budget = context.budget(last_line_used_width(&result, indent.width()));
1990 if let Some(where_clause_str) = rewrite_where_clause(
1993 context.config.fn_brace_style(),
1994 Shape::legacy(budget, indent),
1995 Density::Compressed,
1999 WhereClauseOption::compressed(),
2000 is_args_multi_lined,
2002 result.push_str(&where_clause_str);
2003 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2004 return Some((result, force_new_line_for_brace));
2008 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2009 let where_clause_str = rewrite_where_clause(
2012 context.config.fn_brace_style(),
2013 Shape::indented(indent, context.config),
2019 is_args_multi_lined,
2021 // If there are neither where clause nor return type, we may be missing comments between
2023 if where_clause_str.is_empty() {
2024 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2025 match recover_missing_comment_in_span(
2026 mk_sp(args_span.hi(), ret_span.hi()),
2029 last_line_width(&result),
2031 Some(ref missing_comment) if !missing_comment.is_empty() => {
2032 result.push_str(missing_comment);
2033 force_new_line_for_brace = true;
2040 result.push_str(&where_clause_str);
2042 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2043 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2044 Some((result, force_new_line_for_brace))
2047 #[derive(Copy, Clone)]
2048 struct WhereClauseOption {
2049 suppress_comma: bool, // Force no trailing comma
2050 snuggle: bool, // Do not insert newline before `where`
2051 compress_where: bool, // Try single line where clause instead of vertical layout
2054 impl WhereClauseOption {
2055 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2057 suppress_comma: suppress_comma,
2059 compress_where: false,
2063 pub fn compressed() -> WhereClauseOption {
2065 suppress_comma: true,
2067 compress_where: true,
2071 pub fn snuggled(current: &str) -> WhereClauseOption {
2073 suppress_comma: false,
2074 snuggle: trimmed_last_line_width(current) == 1,
2075 compress_where: false,
2081 context: &RewriteContext,
2083 explicit_self: Option<&ast::ExplicitSelf>,
2084 one_line_budget: usize,
2085 multi_line_budget: usize,
2090 generics_str_contains_newline: bool,
2091 ) -> Option<String> {
2092 let mut arg_item_strs = args.iter()
2093 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2094 .collect::<Option<Vec<_>>>()?;
2096 // Account for sugary self.
2097 // FIXME: the comment for the self argument is dropped. This is blocked
2098 // on rust issue #27522.
2099 let min_args = explicit_self
2100 .and_then(|explicit_self| {
2101 rewrite_explicit_self(explicit_self, args, context)
2103 .map_or(1, |self_str| {
2104 arg_item_strs[0] = self_str;
2108 // Comments between args.
2109 let mut arg_items = Vec::new();
2111 arg_items.push(ListItem::from_str(""));
2114 // FIXME(#21): if there are no args, there might still be a comment, but
2115 // without spans for the comment or parens, there is no chance of
2116 // getting it right. You also don't get to put a comment on self, unless
2118 if args.len() >= min_args || variadic {
2119 let comment_span_start = if min_args == 2 {
2120 let second_arg_start = if arg_has_pattern(&args[1]) {
2121 args[1].pat.span.lo()
2123 args[1].ty.span.lo()
2125 let reduced_span = mk_sp(span.lo(), second_arg_start);
2127 context.codemap.span_after_last(reduced_span, ",")
2132 enum ArgumentKind<'a> {
2133 Regular(&'a ast::Arg),
2137 let variadic_arg = if variadic {
2138 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2139 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2140 Some(ArgumentKind::Variadic(variadic_start))
2145 let more_items = itemize_list(
2147 args[min_args - 1..]
2149 .map(ArgumentKind::Regular)
2150 .chain(variadic_arg),
2153 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2154 ArgumentKind::Variadic(start) => start,
2157 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2158 ArgumentKind::Variadic(start) => start + BytePos(3),
2161 ArgumentKind::Regular(..) => None,
2162 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2169 arg_items.extend(more_items);
2172 let fits_in_one_line = !generics_str_contains_newline
2173 && (arg_items.is_empty()
2174 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2176 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2177 item.item = Some(arg);
2180 let last_line_ends_with_comment = arg_items
2183 .and_then(|item| item.post_comment.as_ref())
2184 .map_or(false, |s| s.trim().starts_with("//"));
2186 let (indent, trailing_comma) = match context.config.fn_args_indent() {
2187 IndentStyle::Block if fits_in_one_line => {
2188 (indent.block_indent(context.config), SeparatorTactic::Never)
2190 IndentStyle::Block => (
2191 indent.block_indent(context.config),
2192 context.config.trailing_comma(),
2194 IndentStyle::Visual if last_line_ends_with_comment => {
2195 (arg_indent, context.config.trailing_comma())
2197 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2200 let tactic = definitive_tactic(
2202 context.config.fn_args_density().to_list_tactic(),
2206 let budget = match tactic {
2207 DefinitiveListTactic::Horizontal => one_line_budget,
2208 _ => multi_line_budget,
2211 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2213 let fmt = ListFormatting {
2216 trailing_separator: if variadic {
2217 SeparatorTactic::Never
2221 separator_place: SeparatorPlace::Back,
2222 shape: Shape::legacy(budget, indent),
2223 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_indent()),
2224 preserve_newline: true,
2225 config: context.config,
2228 write_list(&arg_items, &fmt)
2231 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2232 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2233 ident.node != symbol::keywords::Invalid.ident()
2239 fn compute_budgets_for_args(
2240 context: &RewriteContext,
2244 newline_brace: bool,
2246 force_vertical_layout: bool,
2247 ) -> Option<((usize, usize, Indent))> {
2249 "compute_budgets_for_args {} {:?}, {}, {}",
2255 // Try keeping everything on the same line.
2256 if !result.contains('\n') && !force_vertical_layout {
2257 // 2 = `()`, 3 = `() `, space is before ret_string.
2258 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2259 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2269 let one_line_budget = context.budget(used_space);
2271 if one_line_budget > 0 {
2273 let (indent, multi_line_budget) = match context.config.fn_args_indent() {
2274 IndentStyle::Block => {
2275 let indent = indent.block_indent(context.config);
2276 (indent, context.budget(indent.width() + 1))
2278 IndentStyle::Visual => {
2279 let indent = indent + result.len() + 1;
2280 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2281 (indent, context.budget(multi_line_overhead))
2285 return Some((one_line_budget, multi_line_budget, indent));
2289 // Didn't work. we must force vertical layout and put args on a newline.
2290 let new_indent = indent.block_indent(context.config);
2291 let used_space = match context.config.fn_args_indent() {
2293 IndentStyle::Block => new_indent.width() + 1,
2294 // Account for `)` and possibly ` {`.
2295 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2297 Some((0, context.budget(used_space), new_indent))
2300 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2301 let predicate_count = where_clause.predicates.len();
2303 if config.where_single_line() && predicate_count == 1 {
2306 match (config.fn_brace_style(), config.where_density()) {
2307 (BraceStyle::AlwaysNextLine, _) => true,
2308 (_, Density::Compressed) if predicate_count == 1 => false,
2309 (_, Density::CompressedIfEmpty) if predicate_count == 1 && !has_body => false,
2310 (BraceStyle::SameLineWhere, _) if predicate_count > 0 => true,
2315 fn rewrite_generics(
2316 context: &RewriteContext,
2317 generics: &ast::Generics,
2320 ) -> Option<String> {
2321 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2322 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2323 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2324 rewrite_generics_inner(context, generics, g_shape, 0, span)
2328 fn rewrite_generics_inner(
2329 context: &RewriteContext,
2330 generics: &ast::Generics,
2332 one_line_width: usize,
2334 ) -> Option<String> {
2335 // FIXME: convert bounds to where clauses where they get too big or if
2336 // there is a where clause at all.
2339 enum GenericsArg<'a> {
2340 Lifetime(&'a ast::LifetimeDef),
2341 TyParam(&'a ast::TyParam),
2343 impl<'a> Rewrite for GenericsArg<'a> {
2344 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2346 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2347 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2351 impl<'a> Spanned for GenericsArg<'a> {
2352 fn span(&self) -> Span {
2354 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2355 GenericsArg::TyParam(ty) => ty.span(),
2360 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2361 return Some(String::new());
2364 let generics_args = generics
2367 .map(|lt| GenericsArg::Lifetime(lt))
2368 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2369 let items = itemize_list(
2373 |arg| arg.span().lo(),
2374 |arg| arg.span().hi(),
2375 |arg| arg.rewrite(context, shape),
2376 context.codemap.span_after(span, "<"),
2380 format_generics_item_list(context, items, shape, one_line_width)
2383 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2384 match config.generics_indent() {
2385 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2386 IndentStyle::Block => {
2390 .block_indent(config.tab_spaces())
2391 .with_max_width(config)
2397 pub fn format_generics_item_list<I>(
2398 context: &RewriteContext,
2401 one_line_budget: usize,
2404 I: Iterator<Item = ListItem>,
2406 let item_vec = items.collect::<Vec<_>>();
2408 let tactic = definitive_tactic(
2410 ListTactic::HorizontalVertical,
2414 let fmt = ListFormatting {
2417 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2418 SeparatorTactic::Never
2420 context.config.trailing_comma()
2422 separator_place: SeparatorPlace::Back,
2424 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2425 preserve_newline: true,
2426 config: context.config,
2429 let list_str = write_list(&item_vec, &fmt)?;
2431 Some(wrap_generics_with_angle_brackets(
2438 pub fn wrap_generics_with_angle_brackets(
2439 context: &RewriteContext,
2441 list_offset: Indent,
2443 if context.config.generics_indent() == IndentStyle::Block
2444 && (list_str.contains('\n') || list_str.ends_with(','))
2448 list_offset.to_string(context.config),
2451 .block_unindent(context.config)
2452 .to_string(context.config)
2454 } else if context.config.spaces_within_angle_brackets() {
2455 format!("< {} >", list_str)
2457 format!("<{}>", list_str)
2461 fn rewrite_trait_bounds(
2462 context: &RewriteContext,
2463 type_param_bounds: &ast::TyParamBounds,
2465 ) -> Option<String> {
2466 let bounds: &[_] = type_param_bounds;
2468 if bounds.is_empty() {
2469 return Some(String::new());
2471 let bound_str = bounds
2473 .map(|ty_bound| ty_bound.rewrite(context, shape))
2474 .collect::<Option<Vec<_>>>()?;
2475 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2478 fn rewrite_where_clause_rfc_style(
2479 context: &RewriteContext,
2480 where_clause: &ast::WhereClause,
2483 span_end: Option<BytePos>,
2484 span_end_before_where: BytePos,
2485 where_clause_option: WhereClauseOption,
2486 is_args_multi_line: bool,
2487 ) -> Option<String> {
2488 let block_shape = shape.block().with_max_width(context.config);
2490 let (span_before, span_after) =
2491 missing_span_before_after_where(span_end_before_where, where_clause);
2492 let (comment_before, comment_after) =
2493 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2495 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2498 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2501 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2503 let clause_shape = clause_shape.sub_width(1)?;
2504 // each clause on one line, trailing comma (except if suppress_comma)
2505 let span_start = where_clause.predicates[0].span().lo();
2506 // If we don't have the start of the next span, then use the end of the
2507 // predicates, but that means we miss comments.
2508 let len = where_clause.predicates.len();
2509 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2510 let span_end = span_end.unwrap_or(end_of_preds);
2511 let items = itemize_list(
2513 where_clause.predicates.iter(),
2515 |pred| pred.span().lo(),
2516 |pred| pred.span().hi(),
2517 |pred| pred.rewrite(context, clause_shape),
2522 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2523 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2524 SeparatorTactic::Never
2526 context.config.trailing_comma()
2529 // shape should be vertical only and only if we have `where_single_line` option enabled
2530 // and the number of items of the where clause is equal to 1
2531 let shape_tactic = if where_single_line {
2532 DefinitiveListTactic::Horizontal
2534 DefinitiveListTactic::Vertical
2537 let fmt = ListFormatting {
2538 tactic: shape_tactic,
2540 trailing_separator: comma_tactic,
2541 separator_place: SeparatorPlace::Back,
2542 shape: clause_shape,
2543 ends_with_newline: true,
2544 preserve_newline: true,
2545 config: context.config,
2547 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2549 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2552 format!("\n{}", shape.indent.to_string(context.config))
2554 let newline_before_where = comment_separator(&comment_before, shape);
2555 let newline_after_where = comment_separator(&comment_after, clause_shape);
2558 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2559 && comment_after.is_empty() && !preds_str.contains('\n')
2560 && 6 + preds_str.len() <= shape.width || where_single_line
2564 format!("\n{}", clause_shape.indent.to_string(context.config))
2567 "{}{}{}where{}{}{}{}",
2570 newline_before_where,
2571 newline_after_where,
2578 fn rewrite_where_clause(
2579 context: &RewriteContext,
2580 where_clause: &ast::WhereClause,
2581 brace_style: BraceStyle,
2585 span_end: Option<BytePos>,
2586 span_end_before_where: BytePos,
2587 where_clause_option: WhereClauseOption,
2588 is_args_multi_line: bool,
2589 ) -> Option<String> {
2590 if where_clause.predicates.is_empty() {
2591 return Some(String::new());
2594 if context.config.where_style() == Style::Rfc {
2595 return rewrite_where_clause_rfc_style(
2601 span_end_before_where,
2602 where_clause_option,
2607 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2609 let offset = match context.config.where_pred_indent() {
2610 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2611 // 6 = "where ".len()
2612 IndentStyle::Visual => shape.indent + extra_indent + 6,
2614 // FIXME: if where_pred_indent != Visual, then the budgets below might
2615 // be out by a char or two.
2617 let budget = context.config.max_width() - offset.width();
2618 let span_start = where_clause.predicates[0].span().lo();
2619 // If we don't have the start of the next span, then use the end of the
2620 // predicates, but that means we miss comments.
2621 let len = where_clause.predicates.len();
2622 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2623 let span_end = span_end.unwrap_or(end_of_preds);
2624 let items = itemize_list(
2626 where_clause.predicates.iter(),
2628 |pred| pred.span().lo(),
2629 |pred| pred.span().hi(),
2630 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2635 let item_vec = items.collect::<Vec<_>>();
2636 // FIXME: we don't need to collect here if the where_layout isn't
2637 // HorizontalVertical.
2638 let tactic = definitive_tactic(
2640 context.config.where_layout(),
2645 let mut comma_tactic = context.config.trailing_comma();
2646 // Kind of a hack because we don't usually have trailing commas in where clauses.
2647 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2648 comma_tactic = SeparatorTactic::Never;
2651 let fmt = ListFormatting {
2654 trailing_separator: comma_tactic,
2655 separator_place: SeparatorPlace::Back,
2656 shape: Shape::legacy(budget, offset),
2657 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2658 preserve_newline: true,
2659 config: context.config,
2661 let preds_str = write_list(&item_vec, &fmt)?;
2663 let end_length = if terminator == "{" {
2664 // If the brace is on the next line we don't need to count it otherwise it needs two
2667 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2668 BraceStyle::PreferSameLine => 2,
2670 } else if terminator == "=" {
2675 if density == Density::Tall || preds_str.contains('\n')
2676 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2680 (shape.indent + extra_indent).to_string(context.config),
2684 Some(format!(" where {}", preds_str))
2688 fn missing_span_before_after_where(
2689 before_item_span_end: BytePos,
2690 where_clause: &ast::WhereClause,
2692 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2694 let pos_after_where = where_clause.span.lo() + BytePos(5);
2695 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2696 (missing_span_before, missing_span_after)
2699 fn rewrite_comments_before_after_where(
2700 context: &RewriteContext,
2701 span_before_where: Span,
2702 span_after_where: Span,
2704 ) -> Option<(String, String)> {
2705 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2706 let after_comment = rewrite_missing_comment(
2708 shape.block_indent(context.config.tab_spaces()),
2711 Some((before_comment, after_comment))
2714 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2715 format!("{}{}{}", format_visibility(vis), item_name, ident)
2719 context: &RewriteContext,
2720 generics: &ast::Generics,
2721 brace_style: BraceStyle,
2722 force_same_line_brace: bool,
2726 ) -> Option<String> {
2727 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2728 let mut result = rewrite_generics(context, generics, shape, span)?;
2730 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2731 let budget = context.budget(last_line_used_width(&result, offset.width()));
2732 let option = WhereClauseOption::snuggled(&result);
2733 // If the generics are not parameterized then generics.span.hi() == 0,
2734 // so we use span.lo(), which is the position after `struct Foo`.
2735 let span_end_before_where = if generics.is_parameterized() {
2740 let where_clause_str = rewrite_where_clause(
2742 &generics.where_clause,
2744 Shape::legacy(budget, offset.block_only()),
2748 span_end_before_where,
2752 result.push_str(&where_clause_str);
2753 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2754 || (generics.where_clause.predicates.is_empty()
2755 && trimmed_last_line_width(&result) == 1)
2757 force_same_line_brace || trimmed_last_line_width(&result) == 1
2758 || brace_style != BraceStyle::AlwaysNextLine
2760 let total_used_width = last_line_used_width(&result, used_width);
2761 let remaining_budget = context.budget(total_used_width);
2762 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2763 // and hence we take the closer into account as well for one line budget.
2764 // We assume that the closer has the same length as the opener.
2765 let overhead = if force_same_line_brace {
2772 let forbid_same_line_brace = overhead > remaining_budget;
2773 if !forbid_same_line_brace && same_line_brace {
2777 result.push_str(&offset.block_only().to_string(context.config));
2784 impl Rewrite for ast::ForeignItem {
2785 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2786 let attrs_str = self.attrs.rewrite(context, shape)?;
2787 // Drop semicolon or it will be interpreted as comment.
2788 // FIXME: this may be a faulty span from libsyntax.
2789 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2791 let item_str = match self.node {
2792 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2796 &FnSig::new(fn_decl, generics, self.vis.clone()),
2800 ).map(|(s, _)| format!("{};", s)),
2801 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2802 // FIXME(#21): we're dropping potential comments in between the
2803 // function keywords here.
2804 let vis = format_visibility(&self.vis);
2805 let mut_str = if is_mutable { "mut " } else { "" };
2806 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2808 let shape = shape.sub_width(1)?;
2809 ty.rewrite(context, shape).map(|ty_str| {
2810 // 1 = space between prefix and type.
2811 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2814 let nested_indent = shape.indent.block_indent(context.config);
2815 format!("\n{}", nested_indent.to_string(context.config))
2817 format!("{}{}{};", prefix, sep, ty_str)
2820 ast::ForeignItemKind::Ty => {
2821 let vis = format_visibility(&self.vis);
2822 Some(format!("{}type {};", vis, self.ident))
2826 let missing_span = if self.attrs.is_empty() {
2827 mk_sp(self.span.lo(), self.span.lo())
2829 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2831 combine_strs_with_missing_comments(