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(),
598 // If there is no where clause, we may have missing comments between the trait name and
599 // the opening brace.
600 if generics.where_clause.predicates.is_empty() {
601 if let Some(hi) = where_span_end {
602 match recover_missing_comment_in_span(
603 mk_sp(self_ty.span.hi(), hi),
604 Shape::indented(offset, context.config),
606 last_line_width(&result),
608 Some(ref missing_comment) if !missing_comment.is_empty() => {
609 result.push_str(missing_comment);
616 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
617 result.push_str(&where_clause_str);
618 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
619 result.push_str(&format!("{}{{{}}}", &sep, &sep));
621 result.push_str(" {}");
626 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
628 let width = offset.block_indent + context.config.tab_spaces() - 1;
629 let where_indent = Indent::new(0, width);
630 result.push_str(&where_indent.to_string(context.config));
632 result.push_str(&where_clause_str);
634 match context.config.item_brace_style() {
635 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
636 BraceStyle::AlwaysNextLine => result.push_str(&sep),
637 BraceStyle::PreferSameLine => result.push(' '),
638 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
639 result.push_str(&sep);
647 let snippet = context.snippet(item.span);
648 let open_pos = snippet.find_uncommented("{")? + 1;
650 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
651 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
652 visitor.block_indent = offset.block_only().block_indent(context.config);
653 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
655 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
657 visitor.visit_impl_item(item);
660 visitor.format_missing(item.span.hi() - BytePos(1));
662 let inner_indent_str = visitor.block_indent.to_string(context.config);
663 let outer_indent_str = offset.block_only().to_string(context.config);
666 result.push_str(&inner_indent_str);
667 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
669 result.push_str(&outer_indent_str);
672 if result.chars().last().unwrap() == '{' {
673 result.push_str(&sep);
683 fn is_impl_single_line(
684 context: &RewriteContext,
687 where_clause_str: &str,
690 let snippet = context.snippet(item.span);
691 let open_pos = snippet.find_uncommented("{")? + 1;
694 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
695 && result.len() + where_clause_str.len() <= context.config.max_width()
696 && !contains_comment(&snippet[open_pos..]),
700 fn format_impl_ref_and_type(
701 context: &RewriteContext,
704 ) -> Option<String> {
705 if let ast::ItemKind::Impl(
715 let mut result = String::with_capacity(128);
717 result.push_str(&format_visibility(&item.vis));
718 result.push_str(format_defaultness(defaultness));
719 result.push_str(format_unsafety(unsafety));
720 result.push_str("impl");
722 let lo = context.codemap.span_after(item.span, "impl");
723 let hi = match *trait_ref {
724 Some(ref tr) => tr.path.span.lo(),
725 None => self_ty.span.lo(),
727 let shape = generics_shape_from_config(
729 Shape::indented(offset + last_line_width(&result), context.config),
732 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
734 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
736 let polarity_str = if polarity == ast::ImplPolarity::Negative {
742 if let Some(ref trait_ref) = *trait_ref {
743 let result_len = result.len();
744 if let Some(trait_ref_str) = rewrite_trait_ref(
753 result.push_str(&trait_ref_str);
756 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
757 result.push_str(&rewrite_trait_ref(
768 result.push_str(&generics_str);
771 // Try to put the self type in a single line.
773 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
774 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
775 // If there is no where clause adapt budget for type formatting to take space and curly
776 // brace into account.
777 match context.config.item_brace_style() {
778 BraceStyle::AlwaysNextLine => 0,
784 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
785 // 1 = space before the type.
786 let budget = context.budget(used_space + 1);
787 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
788 if !self_ty_str.contains('\n') {
789 if trait_ref.is_some() {
790 result.push_str(" for ");
794 result.push_str(&self_ty_str);
799 // Couldn't fit the self type on a single line, put it on a new line.
801 // Add indentation of one additional tab.
802 let new_line_offset = offset.block_indent(context.config);
803 result.push_str(&new_line_offset.to_string(context.config));
804 if trait_ref.is_some() {
805 result.push_str("for ");
807 let budget = context.budget(last_line_width(&result));
808 let type_offset = match context.config.where_style() {
809 Style::Legacy => new_line_offset + trait_ref_overhead,
810 Style::Rfc => new_line_offset,
812 result.push_str(&*self_ty
813 .rewrite(context, Shape::legacy(budget, type_offset))?);
820 fn rewrite_trait_ref(
821 context: &RewriteContext,
822 trait_ref: &ast::TraitRef,
828 ) -> Option<String> {
829 // 1 = space between generics and trait_ref
830 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
831 let shape = Shape::indented(offset + used_space, context.config);
832 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
833 if !(retry && trait_ref_str.contains('\n')) {
842 // We could not make enough space for trait_ref, so put it on new line.
844 let offset = offset.block_indent(context.config);
845 let shape = Shape::indented(offset, context.config);
846 let trait_ref_str = trait_ref.rewrite(context, shape)?;
850 &offset.to_string(context.config),
859 pub fn format_struct(
860 context: &RewriteContext,
863 vis: &ast::Visibility,
864 struct_def: &ast::VariantData,
865 generics: Option<&ast::Generics>,
868 one_line_width: Option<usize>,
869 ) -> Option<String> {
871 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
872 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
882 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
896 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
897 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
900 let mut result = String::with_capacity(128);
901 let header = format!(
903 format_visibility(&item.vis),
904 format_unsafety(unsafety),
908 result.push_str(&header);
910 let body_lo = context.codemap.span_after(item.span, "{");
912 let shape = Shape::indented(offset + last_line_width(&result), context.config);
914 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
915 result.push_str(&generics_str);
917 let trait_bound_str = rewrite_trait_bounds(
920 Shape::indented(offset, context.config),
922 // If the trait, generics, and trait bound cannot fit on the same line,
923 // put the trait bounds on an indented new line
924 if offset.width() + last_line_width(&result) + trait_bound_str.len()
925 > context.config.comment_width()
928 let trait_indent = offset.block_only().block_indent(context.config);
929 result.push_str(&trait_indent.to_string(context.config));
931 result.push_str(&trait_bound_str);
933 let has_body = !trait_items.is_empty();
935 let where_density = if (context.config.where_density() == Density::Compressed
936 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
937 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
938 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
939 && !result.contains('\n'))
946 let where_budget = context.budget(last_line_width(&result));
947 let pos_before_where = if type_param_bounds.is_empty() {
948 generics.where_clause.span.lo()
950 type_param_bounds[type_param_bounds.len() - 1].span().hi()
952 let option = WhereClauseOption::snuggled(&generics_str);
953 let where_clause_str = rewrite_where_clause(
955 &generics.where_clause,
956 context.config.item_brace_style(),
957 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(
1082 context.config.item_brace_style(),
1085 mk_sp(header_hi, body_lo),
1086 last_line_width(&result),
1089 // 3 = ` {}`, 2 = ` {`.
1090 let overhead = if fields.is_empty() { 3 } else { 2 };
1091 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1092 && !fields.is_empty())
1093 || context.config.max_width() < overhead + result.len()
1095 format!("\n{}{{", offset.block_only().to_string(context.config))
1102 let overhead = if fields.is_empty() { 1 } else { 0 };
1103 let total_width = result.len() + generics_str.len() + overhead;
1104 if !generics_str.is_empty() && !generics_str.contains('\n')
1105 && total_width > context.config.max_width()
1108 result.push_str(&offset.to_string(context.config));
1109 result.push_str(generics_str.trim_left());
1111 result.push_str(&generics_str);
1114 if fields.is_empty() {
1115 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1116 if snippet.trim().is_empty() {
1118 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1120 result.push_str(snippet.trim_right());
1122 result.push_str(&offset.to_string(context.config));
1124 result.push_str(&snippet);
1127 return Some(result);
1131 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1132 let one_line_budget =
1133 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1135 let items_str = rewrite_with_alignment(
1138 Shape::indented(offset, context.config),
1139 mk_sp(body_lo, span.hi()),
1143 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1144 Some(format!("{} {} }}", result, items_str))
1150 .block_indent(context.config)
1151 .to_string(context.config),
1153 offset.to_string(context.config)
1158 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1159 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1160 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1161 fn get_bytepos_after_visibility(
1162 context: &RewriteContext,
1163 vis: &ast::Visibility,
1168 ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1170 .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1171 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1172 ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1173 _ => default_span.lo(),
1177 fn format_tuple_struct(
1178 context: &RewriteContext,
1181 vis: &ast::Visibility,
1182 fields: &[ast::StructField],
1183 generics: Option<&ast::Generics>,
1186 ) -> Option<String> {
1187 let mut result = String::with_capacity(1024);
1189 let header_str = format_header(item_name, ident, vis);
1190 result.push_str(&header_str);
1192 let body_lo = if fields.is_empty() {
1193 let lo = get_bytepos_after_visibility(context, vis, span, ")");
1194 context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1198 let body_hi = if fields.is_empty() {
1199 context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1201 // This is a dirty hack to work around a missing `)` from the span of the last field.
1202 let last_arg_span = fields[fields.len() - 1].span;
1203 if context.snippet(last_arg_span).ends_with(')') {
1208 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1212 let where_clause_str = match generics {
1214 let budget = context.budget(last_line_width(&header_str));
1215 let shape = Shape::legacy(budget, offset);
1216 let g_span = mk_sp(span.lo(), body_lo);
1217 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1218 result.push_str(&generics_str);
1220 let where_budget = context.budget(last_line_width(&result));
1221 let option = WhereClauseOption::new(true, false);
1222 rewrite_where_clause(
1224 &generics.where_clause,
1225 context.config.item_brace_style(),
1226 Shape::legacy(where_budget, offset.block_only()),
1227 Density::Compressed,
1234 None => "".to_owned(),
1237 if fields.is_empty() {
1239 let used_width = last_line_used_width(&result, offset.width()) + 3;
1240 if used_width > context.config.max_width() {
1242 result.push_str(&offset
1243 .block_indent(context.config)
1244 .to_string(context.config))
1247 let snippet = context.snippet(mk_sp(
1249 context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1251 if snippet.is_empty() {
1253 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1254 result.push_str(snippet.trim_right());
1256 result.push_str(&offset.to_string(context.config));
1258 result.push_str(&snippet);
1263 let body = rewrite_call_inner(
1266 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1268 Shape::indented(offset, context.config).sub_width(1)?,
1269 context.config.fn_call_width(),
1272 result.push_str(&body);
1275 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1276 && (result.contains('\n')
1277 || offset.block_indent + result.len() + where_clause_str.len() + 1
1278 > context.config.max_width())
1280 // We need to put the where clause on a new line, but we didn't
1281 // know that earlier, so the where clause will not be indented properly.
1283 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1284 .to_string(context.config));
1286 result.push_str(&where_clause_str);
1291 pub fn rewrite_type_alias(
1292 context: &RewriteContext,
1296 generics: &ast::Generics,
1297 vis: &ast::Visibility,
1299 ) -> Option<String> {
1300 let mut result = String::with_capacity(128);
1302 result.push_str(&format_visibility(vis));
1303 result.push_str("type ");
1304 result.push_str(&ident.to_string());
1307 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1308 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1309 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1310 result.push_str(&generics_str);
1312 let where_budget = context.budget(last_line_width(&result));
1313 let option = WhereClauseOption::snuggled(&result);
1314 let where_clause_str = rewrite_where_clause(
1316 &generics.where_clause,
1317 context.config.item_brace_style(),
1318 Shape::legacy(where_budget, indent),
1319 context.config.where_density(),
1325 result.push_str(&where_clause_str);
1326 if where_clause_str.is_empty() {
1327 result.push_str(" = ");
1329 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1332 let line_width = last_line_width(&result);
1333 // This checked_sub may fail as the extra space after '=' is not taken into account
1334 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1335 let budget = context.budget(indent.width() + line_width + ";".len());
1336 let type_indent = indent + line_width;
1337 // Try to fit the type on the same line
1338 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1340 // The line was too short, try to put the type on the next line
1342 // Remove the space after '='
1344 let type_indent = indent.block_indent(context.config);
1346 result.push_str(&type_indent.to_string(context.config));
1347 let budget = context.budget(type_indent.width() + ";".len());
1348 ty.rewrite(context, Shape::legacy(budget, type_indent))
1350 result.push_str(&ty_str);
1351 result.push_str(";");
1355 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1357 if config.space_before_type_annotation() {
1362 if config.space_after_type_annotation_colon() {
1370 pub fn rewrite_struct_field_prefix(
1371 context: &RewriteContext,
1372 field: &ast::StructField,
1373 ) -> Option<String> {
1374 let vis = format_visibility(&field.vis);
1375 let type_annotation_spacing = type_annotation_spacing(context.config);
1376 Some(match field.ident {
1377 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1378 None => format!("{}", vis),
1382 impl Rewrite for ast::StructField {
1383 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1384 rewrite_struct_field(context, self, shape, 0)
1388 pub fn rewrite_struct_field(
1389 context: &RewriteContext,
1390 field: &ast::StructField,
1392 lhs_max_width: usize,
1393 ) -> Option<String> {
1394 if contains_skip(&field.attrs) {
1395 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1398 let type_annotation_spacing = type_annotation_spacing(context.config);
1399 let prefix = rewrite_struct_field_prefix(context, field)?;
1401 let attrs_str = field.attrs.rewrite(context, shape)?;
1402 let attrs_extendable = attrs_str.is_empty()
1403 || (context.config.attributes_on_same_line_as_field()
1404 && is_attributes_extendable(&attrs_str));
1405 let missing_span = if field.attrs.is_empty() {
1406 mk_sp(field.span.lo(), field.span.lo())
1408 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1410 let mut spacing = String::from(if field.ident.is_some() {
1411 type_annotation_spacing.1
1415 // Try to put everything on a single line.
1416 let attr_prefix = combine_strs_with_missing_comments(
1424 let overhead = last_line_width(&attr_prefix);
1425 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1426 for _ in 0..lhs_offset {
1429 // In this extreme case we will be missing a space betweeen an attribute and a field.
1430 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1433 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1434 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1435 if !ty.contains('\n') {
1436 return Some(attr_prefix + &spacing + ty);
1440 // We must use multiline.
1441 let new_shape = shape.with_max_width(context.config);
1442 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1444 let field_str = if prefix.is_empty() {
1446 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1447 prefix + " " + &ty_rewritten
1449 let type_offset = shape.indent.block_indent(context.config);
1450 let nested_shape = Shape::indented(type_offset, context.config);
1451 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1452 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1454 combine_strs_with_missing_comments(
1464 pub fn rewrite_static(
1466 vis: &ast::Visibility,
1469 mutability: ast::Mutability,
1470 expr_opt: Option<&ptr::P<ast::Expr>>,
1473 context: &RewriteContext,
1474 ) -> Option<String> {
1475 let colon = colon_spaces(
1476 context.config.space_before_type_annotation(),
1477 context.config.space_after_type_annotation_colon(),
1479 let prefix = format!(
1481 format_visibility(vis),
1483 format_mutability(mutability),
1488 let ty_str = ty.rewrite(
1490 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1493 if let Some(expr) = expr_opt {
1494 let lhs = format!("{}{} =", prefix, ty_str);
1496 let remaining_width = context.budget(offset.block_indent + 1);
1501 Shape::legacy(remaining_width, offset.block_only()),
1502 ).and_then(|res| recover_comment_removed(res, span, context))
1503 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1505 Some(format!("{}{};", prefix, ty_str))
1509 pub fn rewrite_associated_type(
1511 ty_opt: Option<&ptr::P<ast::Ty>>,
1512 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1513 context: &RewriteContext,
1515 ) -> Option<String> {
1516 let prefix = format!("type {}", ident);
1518 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1520 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1521 let bounds: &[_] = ty_param_bounds;
1522 let bound_str = bounds
1524 .map(|ty_bound| ty_bound.rewrite(context, shape))
1525 .collect::<Option<Vec<_>>>()?;
1526 if !bounds.is_empty() {
1527 format!(": {}", join_bounds(context, shape, &bound_str))
1535 if let Some(ty) = ty_opt {
1536 let ty_str = ty.rewrite(
1539 context.budget(indent.block_indent + prefix.len() + 2),
1540 indent.block_only(),
1543 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1545 Some(format!("{}{};", prefix, type_bounds_str))
1549 pub fn rewrite_associated_impl_type(
1551 defaultness: ast::Defaultness,
1552 ty_opt: Option<&ptr::P<ast::Ty>>,
1553 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1554 context: &RewriteContext,
1556 ) -> Option<String> {
1557 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1560 ast::Defaultness::Default => Some(format!("default {}", result)),
1565 impl Rewrite for ast::FunctionRetTy {
1566 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1568 ast::FunctionRetTy::Default(_) => Some(String::new()),
1569 ast::FunctionRetTy::Ty(ref ty) => {
1570 let inner_width = shape.width.checked_sub(3)?;
1571 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1572 .map(|r| format!("-> {}", r))
1578 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1580 ast::TyKind::Infer => {
1581 let original = context.snippet(ty.span);
1588 impl Rewrite for ast::Arg {
1589 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1590 if is_named_arg(self) {
1591 let mut result = self.pat
1592 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1594 if !is_empty_infer(context, &*self.ty) {
1595 if context.config.space_before_type_annotation() {
1596 result.push_str(" ");
1598 result.push_str(":");
1599 if context.config.space_after_type_annotation_colon() {
1600 result.push_str(" ");
1602 let overhead = last_line_width(&result);
1603 let max_width = shape.width.checked_sub(overhead)?;
1604 let ty_str = self.ty
1605 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1606 result.push_str(&ty_str);
1611 self.ty.rewrite(context, shape)
1616 fn rewrite_explicit_self(
1617 explicit_self: &ast::ExplicitSelf,
1619 context: &RewriteContext,
1620 ) -> Option<String> {
1621 match explicit_self.node {
1622 ast::SelfKind::Region(lt, m) => {
1623 let mut_str = format_mutability(m);
1626 let lifetime_str = l.rewrite(
1628 Shape::legacy(context.config.max_width(), Indent::empty()),
1630 Some(format!("&{} {}self", lifetime_str, mut_str))
1632 None => Some(format!("&{}self", mut_str)),
1635 ast::SelfKind::Explicit(ref ty, _) => {
1636 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1638 let mutability = explicit_self_mutability(&args[0]);
1639 let type_str = ty.rewrite(
1641 Shape::legacy(context.config.max_width(), Indent::empty()),
1646 format_mutability(mutability),
1650 ast::SelfKind::Value(_) => {
1651 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1653 let mutability = explicit_self_mutability(&args[0]);
1655 Some(format!("{}self", format_mutability(mutability)))
1660 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1661 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1662 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1663 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1670 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1671 if is_named_arg(arg) {
1678 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1680 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1681 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1682 _ => arg.ty.span.hi(),
1686 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1687 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1688 ident.node != symbol::keywords::Invalid.ident()
1694 // Return type is (result, force_new_line_for_brace)
1696 context: &RewriteContext,
1701 newline_brace: bool,
1703 ) -> Option<(String, bool)> {
1704 let mut force_new_line_for_brace = false;
1706 let where_clause = &fn_sig.generics.where_clause;
1708 let mut result = String::with_capacity(1024);
1709 result.push_str(&fn_sig.to_str(context));
1712 result.push_str("fn ");
1713 result.push_str(&ident.to_string());
1716 let overhead = if has_body && !newline_brace {
1723 let used_width = last_line_used_width(&result, indent.width());
1724 let one_line_budget = context.budget(used_width + overhead);
1726 width: one_line_budget,
1730 let fd = fn_sig.decl;
1731 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1732 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1733 result.push_str(&generics_str);
1735 let snuggle_angle_bracket = generics_str
1738 .map_or(false, |l| l.trim_left().len() == 1);
1740 // Note that the width and indent don't really matter, we'll re-layout the
1741 // return type later anyway.
1742 let ret_str = fd.output
1743 .rewrite(context, Shape::indented(indent, context.config))?;
1745 let multi_line_ret_str = ret_str.contains('\n');
1746 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1749 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1760 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1766 // Check if vertical layout was forced.
1767 if one_line_budget == 0 {
1768 if snuggle_angle_bracket {
1770 } else if context.config.fn_args_paren_newline() {
1772 result.push_str(&arg_indent.to_string(context.config));
1773 if context.config.fn_args_layout() == IndentStyle::Visual {
1774 arg_indent = arg_indent + 1; // extra space for `(`
1778 result.push_str("(");
1779 if context.config.fn_args_layout() == IndentStyle::Visual {
1781 result.push_str(&arg_indent.to_string(context.config));
1787 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1791 // Skip `pub(crate)`.
1792 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1793 // A conservative estimation, to goal is to be over all parens in generics
1794 let args_start = fn_sig
1798 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1799 let args_end = if fd.inputs.is_empty() {
1802 .span_after(mk_sp(args_start, span.hi()), ")")
1804 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1805 context.codemap.span_after(last_span, ")")
1807 let args_span = mk_sp(
1810 .span_after(mk_sp(args_start, span.hi()), "("),
1813 let arg_str = rewrite_args(
1816 fd.get_self().as_ref(),
1823 generics_str.contains('\n'),
1826 let put_args_in_block = match context.config.fn_args_layout() {
1827 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1829 } && !fd.inputs.is_empty();
1831 let mut args_last_line_contains_comment = false;
1832 if put_args_in_block {
1833 arg_indent = indent.block_indent(context.config);
1835 result.push_str(&arg_indent.to_string(context.config));
1836 result.push_str(&arg_str);
1838 result.push_str(&indent.to_string(context.config));
1841 result.push_str(&arg_str);
1842 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1843 // Put the closing brace on the next line if it overflows the max width.
1845 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1848 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1851 // If the last line of args contains comment, we cannot put the closing paren
1852 // on the same line.
1856 .map_or(false, |last_line| last_line.contains("//"))
1858 args_last_line_contains_comment = true;
1860 result.push_str(&arg_indent.to_string(context.config));
1866 if let ast::FunctionRetTy::Ty(..) = fd.output {
1867 let ret_should_indent = match context.config.fn_args_layout() {
1868 // If our args are block layout then we surely must have space.
1869 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1870 _ if args_last_line_contains_comment => false,
1871 _ if result.contains('\n') || multi_line_ret_str => true,
1873 // If the return type would push over the max width, then put the return type on
1874 // a new line. With the +1 for the signature length an additional space between
1875 // the closing parenthesis of the argument and the arrow '->' is considered.
1876 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1878 // If there is no where clause, take into account the space after the return type
1880 if where_clause.predicates.is_empty() {
1884 sig_length > context.config.max_width()
1887 let ret_indent = if ret_should_indent {
1888 let indent = match context.config.fn_return_indent() {
1889 ReturnIndent::WithWhereClause => indent + 4,
1890 // Aligning with non-existent args looks silly.
1891 _ if arg_str.is_empty() => {
1892 force_new_line_for_brace = true;
1895 // FIXME: we might want to check that using the arg indent
1896 // doesn't blow our budget, and if it does, then fallback to
1897 // the where clause indent.
1902 result.push_str(&indent.to_string(context.config));
1906 Indent::new(indent.block_indent, last_line_width(&result))
1909 if multi_line_ret_str || ret_should_indent {
1910 // Now that we know the proper indent and width, we need to
1911 // re-layout the return type.
1912 let ret_str = fd.output
1913 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1914 result.push_str(&ret_str);
1916 result.push_str(&ret_str);
1919 // Comment between return type and the end of the decl.
1920 let snippet_lo = fd.output.span().hi();
1921 if where_clause.predicates.is_empty() {
1922 let snippet_hi = span.hi();
1923 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1924 // Try to preserve the layout of the original snippet.
1925 let original_starts_with_newline = snippet
1927 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1928 let original_ends_with_newline = snippet
1929 .rfind(|c| c != ' ')
1930 .map_or(false, |i| snippet[i..].ends_with('\n'));
1931 let snippet = snippet.trim();
1932 if !snippet.is_empty() {
1933 result.push(if original_starts_with_newline {
1938 result.push_str(snippet);
1939 if original_ends_with_newline {
1940 force_new_line_for_brace = true;
1946 let should_compress_where = match context.config.where_density() {
1947 Density::Compressed => !result.contains('\n'),
1948 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1952 let pos_before_where = match fd.output {
1953 ast::FunctionRetTy::Default(..) => args_span.hi(),
1954 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1957 if where_clause.predicates.len() == 1 && should_compress_where {
1958 let budget = context.budget(last_line_used_width(&result, indent.width()));
1959 if let Some(where_clause_str) = rewrite_where_clause(
1962 context.config.fn_brace_style(),
1963 Shape::legacy(budget, indent),
1964 Density::Compressed,
1968 WhereClauseOption::compressed(),
1970 result.push_str(&where_clause_str);
1971 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1972 return Some((result, force_new_line_for_brace));
1976 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1977 let where_clause_str = rewrite_where_clause(
1980 context.config.fn_brace_style(),
1981 Shape::indented(indent, context.config),
1988 // If there are neither where clause nor return type, we may be missing comments between
1990 if where_clause_str.is_empty() {
1991 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1992 match recover_missing_comment_in_span(
1993 mk_sp(args_span.hi(), ret_span.hi()),
1996 last_line_width(&result),
1998 Some(ref missing_comment) if !missing_comment.is_empty() => {
1999 result.push_str(missing_comment);
2000 force_new_line_for_brace = true;
2007 result.push_str(&where_clause_str);
2009 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2010 Some((result, force_new_line_for_brace))
2013 #[derive(Copy, Clone)]
2014 struct WhereClauseOption {
2015 suppress_comma: bool, // Force no trailing comma
2016 snuggle: bool, // Do not insert newline before `where`
2017 compress_where: bool, // Try single line where clause instead of vertical layout
2020 impl WhereClauseOption {
2021 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2023 suppress_comma: suppress_comma,
2025 compress_where: false,
2029 pub fn compressed() -> WhereClauseOption {
2031 suppress_comma: true,
2033 compress_where: true,
2037 pub fn snuggled(current: &str) -> WhereClauseOption {
2039 suppress_comma: false,
2040 snuggle: trimmed_last_line_width(current) == 1,
2041 compress_where: false,
2047 context: &RewriteContext,
2049 explicit_self: Option<&ast::ExplicitSelf>,
2050 one_line_budget: usize,
2051 multi_line_budget: usize,
2056 generics_str_contains_newline: bool,
2057 ) -> Option<String> {
2058 let mut arg_item_strs = args.iter()
2059 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2060 .collect::<Option<Vec<_>>>()?;
2062 // Account for sugary self.
2063 // FIXME: the comment for the self argument is dropped. This is blocked
2064 // on rust issue #27522.
2065 let min_args = explicit_self
2066 .and_then(|explicit_self| {
2067 rewrite_explicit_self(explicit_self, args, context)
2069 .map_or(1, |self_str| {
2070 arg_item_strs[0] = self_str;
2074 // Comments between args.
2075 let mut arg_items = Vec::new();
2077 arg_items.push(ListItem::from_str(""));
2080 // FIXME(#21): if there are no args, there might still be a comment, but
2081 // without spans for the comment or parens, there is no chance of
2082 // getting it right. You also don't get to put a comment on self, unless
2084 if args.len() >= min_args || variadic {
2085 let comment_span_start = if min_args == 2 {
2086 let second_arg_start = if arg_has_pattern(&args[1]) {
2087 args[1].pat.span.lo()
2089 args[1].ty.span.lo()
2091 let reduced_span = mk_sp(span.lo(), second_arg_start);
2093 context.codemap.span_after_last(reduced_span, ",")
2098 enum ArgumentKind<'a> {
2099 Regular(&'a ast::Arg),
2103 let variadic_arg = if variadic {
2104 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2105 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2106 Some(ArgumentKind::Variadic(variadic_start))
2111 let more_items = itemize_list(
2113 args[min_args - 1..]
2115 .map(ArgumentKind::Regular)
2116 .chain(variadic_arg),
2119 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2120 ArgumentKind::Variadic(start) => start,
2123 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2124 ArgumentKind::Variadic(start) => start + BytePos(3),
2127 ArgumentKind::Regular(..) => None,
2128 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2135 arg_items.extend(more_items);
2138 let fits_in_one_line = !generics_str_contains_newline
2139 && (arg_items.is_empty()
2140 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2142 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2143 item.item = Some(arg);
2146 let last_line_ends_with_comment = arg_items
2149 .and_then(|item| item.post_comment.as_ref())
2150 .map_or(false, |s| s.trim().starts_with("//"));
2152 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2153 IndentStyle::Block if fits_in_one_line => {
2154 (indent.block_indent(context.config), SeparatorTactic::Never)
2156 IndentStyle::Block => (
2157 indent.block_indent(context.config),
2158 context.config.trailing_comma(),
2160 IndentStyle::Visual if last_line_ends_with_comment => {
2161 (arg_indent, context.config.trailing_comma())
2163 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2166 let tactic = definitive_tactic(
2168 context.config.fn_args_density().to_list_tactic(),
2172 let budget = match tactic {
2173 DefinitiveListTactic::Horizontal => one_line_budget,
2174 _ => multi_line_budget,
2177 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2179 let fmt = ListFormatting {
2182 trailing_separator: if variadic {
2183 SeparatorTactic::Never
2187 separator_place: SeparatorPlace::Back,
2188 shape: Shape::legacy(budget, indent),
2189 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2190 preserve_newline: true,
2191 config: context.config,
2194 write_list(&arg_items, &fmt)
2197 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2198 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2199 ident.node != symbol::keywords::Invalid.ident()
2205 fn compute_budgets_for_args(
2206 context: &RewriteContext,
2210 newline_brace: bool,
2212 force_vertical_layout: bool,
2213 ) -> Option<((usize, usize, Indent))> {
2215 "compute_budgets_for_args {} {:?}, {}, {}",
2221 // Try keeping everything on the same line.
2222 if !result.contains('\n') && !force_vertical_layout {
2223 // 2 = `()`, 3 = `() `, space is before ret_string.
2224 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2225 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2235 let one_line_budget = context.budget(used_space);
2237 if one_line_budget > 0 {
2239 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2240 IndentStyle::Block => {
2241 let indent = indent.block_indent(context.config);
2242 (indent, context.budget(indent.width() + 1))
2244 IndentStyle::Visual => {
2245 let indent = indent + result.len() + 1;
2246 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2247 (indent, context.budget(multi_line_overhead))
2251 return Some((one_line_budget, multi_line_budget, indent));
2255 // Didn't work. we must force vertical layout and put args on a newline.
2256 let new_indent = indent.block_indent(context.config);
2257 let used_space = match context.config.fn_args_layout() {
2259 IndentStyle::Block => new_indent.width() + 1,
2260 // Account for `)` and possibly ` {`.
2261 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2263 Some((0, context.budget(used_space), new_indent))
2266 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2267 match (config.fn_brace_style(), config.where_density()) {
2268 (BraceStyle::AlwaysNextLine, _) => true,
2269 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2270 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2271 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2276 fn rewrite_generics(
2277 context: &RewriteContext,
2278 generics: &ast::Generics,
2281 ) -> Option<String> {
2282 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2283 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2284 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2285 rewrite_generics_inner(context, generics, g_shape, 0, span)
2289 fn rewrite_generics_inner(
2290 context: &RewriteContext,
2291 generics: &ast::Generics,
2293 one_line_width: usize,
2295 ) -> Option<String> {
2296 // FIXME: convert bounds to where clauses where they get too big or if
2297 // there is a where clause at all.
2300 enum GenericsArg<'a> {
2301 Lifetime(&'a ast::LifetimeDef),
2302 TyParam(&'a ast::TyParam),
2304 impl<'a> Rewrite for GenericsArg<'a> {
2305 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2307 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2308 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2312 impl<'a> Spanned for GenericsArg<'a> {
2313 fn span(&self) -> Span {
2315 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2316 GenericsArg::TyParam(ref ty) => ty.span(),
2321 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2322 return Some(String::new());
2325 let generics_args = generics
2328 .map(|lt| GenericsArg::Lifetime(lt))
2329 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2330 let items = itemize_list(
2334 |arg| arg.span().lo(),
2335 |arg| arg.span().hi(),
2336 |arg| arg.rewrite(context, shape),
2337 context.codemap.span_after(span, "<"),
2341 format_generics_item_list(context, items, shape, one_line_width)
2344 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2345 match config.generics_indent() {
2346 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2347 IndentStyle::Block => {
2351 .block_indent(config.tab_spaces())
2352 .with_max_width(config)
2358 pub fn format_generics_item_list<I>(
2359 context: &RewriteContext,
2362 one_line_budget: usize,
2365 I: Iterator<Item = ListItem>,
2367 let item_vec = items.collect::<Vec<_>>();
2369 let tactic = definitive_tactic(
2371 ListTactic::HorizontalVertical,
2375 let fmt = ListFormatting {
2378 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2379 SeparatorTactic::Never
2381 context.config.trailing_comma()
2383 separator_place: SeparatorPlace::Back,
2385 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2386 preserve_newline: true,
2387 config: context.config,
2390 let list_str = write_list(&item_vec, &fmt)?;
2392 Some(wrap_generics_with_angle_brackets(
2399 pub fn wrap_generics_with_angle_brackets(
2400 context: &RewriteContext,
2402 list_offset: Indent,
2404 if context.config.generics_indent() == IndentStyle::Block
2405 && (list_str.contains('\n') || list_str.ends_with(','))
2409 list_offset.to_string(context.config),
2412 .block_unindent(context.config)
2413 .to_string(context.config)
2415 } else if context.config.spaces_within_angle_brackets() {
2416 format!("< {} >", list_str)
2418 format!("<{}>", list_str)
2422 fn rewrite_trait_bounds(
2423 context: &RewriteContext,
2424 type_param_bounds: &ast::TyParamBounds,
2426 ) -> Option<String> {
2427 let bounds: &[_] = type_param_bounds;
2429 if bounds.is_empty() {
2430 return Some(String::new());
2432 let bound_str = bounds
2434 .map(|ty_bound| ty_bound.rewrite(context, shape))
2435 .collect::<Option<Vec<_>>>()?;
2436 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2439 fn rewrite_where_clause_rfc_style(
2440 context: &RewriteContext,
2441 where_clause: &ast::WhereClause,
2444 span_end: Option<BytePos>,
2445 span_end_before_where: BytePos,
2446 where_clause_option: WhereClauseOption,
2447 ) -> Option<String> {
2448 let block_shape = shape.block().with_max_width(context.config);
2450 let (span_before, span_after) =
2451 missing_span_before_after_where(span_end_before_where, where_clause);
2452 let (comment_before, comment_after) =
2453 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2455 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2458 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2461 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2463 let clause_shape = clause_shape.sub_width(1)?;
2464 // each clause on one line, trailing comma (except if suppress_comma)
2465 let span_start = where_clause.predicates[0].span().lo();
2466 // If we don't have the start of the next span, then use the end of the
2467 // predicates, but that means we miss comments.
2468 let len = where_clause.predicates.len();
2469 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2470 let span_end = span_end.unwrap_or(end_of_preds);
2471 let items = itemize_list(
2473 where_clause.predicates.iter(),
2475 |pred| pred.span().lo(),
2476 |pred| pred.span().hi(),
2477 |pred| pred.rewrite(context, clause_shape),
2482 let comma_tactic = if where_clause_option.suppress_comma {
2483 SeparatorTactic::Never
2485 context.config.trailing_comma()
2488 let fmt = ListFormatting {
2489 tactic: DefinitiveListTactic::Vertical,
2491 trailing_separator: comma_tactic,
2492 separator_place: SeparatorPlace::Back,
2493 shape: clause_shape,
2494 ends_with_newline: true,
2495 preserve_newline: true,
2496 config: context.config,
2498 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2500 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2503 format!("\n{}", shape.indent.to_string(context.config))
2505 let newline_before_where = comment_separator(&comment_before, shape);
2506 let newline_after_where = comment_separator(&comment_after, clause_shape);
2509 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2510 && comment_after.is_empty() && !preds_str.contains('\n')
2511 && 6 + preds_str.len() <= shape.width
2515 format!("\n{}", clause_shape.indent.to_string(context.config))
2518 "{}{}{}where{}{}{}{}",
2521 newline_before_where,
2522 newline_after_where,
2529 fn rewrite_where_clause(
2530 context: &RewriteContext,
2531 where_clause: &ast::WhereClause,
2532 brace_style: BraceStyle,
2536 span_end: Option<BytePos>,
2537 span_end_before_where: BytePos,
2538 where_clause_option: WhereClauseOption,
2539 ) -> Option<String> {
2540 if where_clause.predicates.is_empty() {
2541 return Some(String::new());
2544 if context.config.where_style() == Style::Rfc {
2545 return rewrite_where_clause_rfc_style(
2551 span_end_before_where,
2552 where_clause_option,
2556 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2558 let offset = match context.config.where_pred_indent() {
2559 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2560 // 6 = "where ".len()
2561 IndentStyle::Visual => shape.indent + extra_indent + 6,
2563 // FIXME: if where_pred_indent != Visual, then the budgets below might
2564 // be out by a char or two.
2566 let budget = context.config.max_width() - offset.width();
2567 let span_start = where_clause.predicates[0].span().lo();
2568 // If we don't have the start of the next span, then use the end of the
2569 // predicates, but that means we miss comments.
2570 let len = where_clause.predicates.len();
2571 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2572 let span_end = span_end.unwrap_or(end_of_preds);
2573 let items = itemize_list(
2575 where_clause.predicates.iter(),
2577 |pred| pred.span().lo(),
2578 |pred| pred.span().hi(),
2579 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2584 let item_vec = items.collect::<Vec<_>>();
2585 // FIXME: we don't need to collect here if the where_layout isn't
2586 // HorizontalVertical.
2587 let tactic = definitive_tactic(
2589 context.config.where_layout(),
2594 let mut comma_tactic = context.config.trailing_comma();
2595 // Kind of a hack because we don't usually have trailing commas in where clauses.
2596 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2597 comma_tactic = SeparatorTactic::Never;
2600 let fmt = ListFormatting {
2603 trailing_separator: comma_tactic,
2604 separator_place: SeparatorPlace::Back,
2605 shape: Shape::legacy(budget, offset),
2606 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2607 preserve_newline: true,
2608 config: context.config,
2610 let preds_str = write_list(&item_vec, &fmt)?;
2612 let end_length = if terminator == "{" {
2613 // If the brace is on the next line we don't need to count it otherwise it needs two
2616 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2617 BraceStyle::PreferSameLine => 2,
2619 } else if terminator == "=" {
2624 if density == Density::Tall || preds_str.contains('\n')
2625 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2629 (shape.indent + extra_indent).to_string(context.config),
2633 Some(format!(" where {}", preds_str))
2637 fn missing_span_before_after_where(
2638 before_item_span_end: BytePos,
2639 where_clause: &ast::WhereClause,
2641 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2643 let pos_after_where = where_clause.span.lo() + BytePos(5);
2644 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2645 (missing_span_before, missing_span_after)
2648 fn rewrite_comments_before_after_where(
2649 context: &RewriteContext,
2650 span_before_where: Span,
2651 span_after_where: Span,
2653 ) -> Option<(String, String)> {
2654 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2655 let after_comment = rewrite_missing_comment(
2657 shape.block_indent(context.config.tab_spaces()),
2660 Some((before_comment, after_comment))
2663 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2664 format!("{}{}{}", format_visibility(vis), item_name, ident)
2668 context: &RewriteContext,
2669 generics: &ast::Generics,
2672 brace_style: BraceStyle,
2673 force_same_line_brace: bool,
2677 ) -> Option<String> {
2678 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2679 let mut result = rewrite_generics(context, generics, shape, span)?;
2681 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2682 let budget = context.budget(last_line_used_width(&result, offset.width()));
2683 let option = WhereClauseOption::snuggled(&result);
2684 // If the generics are not parameterized then generics.span.hi() == 0,
2685 // so we use span.lo(), which is the position after `struct Foo`.
2686 let span_end_before_where = if generics.is_parameterized() {
2691 let where_clause_str = rewrite_where_clause(
2693 &generics.where_clause,
2695 Shape::legacy(budget, offset.block_only()),
2699 span_end_before_where,
2702 result.push_str(&where_clause_str);
2703 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2704 || (generics.where_clause.predicates.is_empty()
2705 && trimmed_last_line_width(&result) == 1)
2707 force_same_line_brace || trimmed_last_line_width(&result) == 1
2708 || brace_style != BraceStyle::AlwaysNextLine
2710 let total_used_width = last_line_used_width(&result, used_width);
2711 let remaining_budget = context.budget(total_used_width);
2712 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2713 // and hence we take the closer into account as well for one line budget.
2714 // We assume that the closer has the same length as the opener.
2715 let overhead = if force_same_line_brace {
2716 1 + opener.len() + opener.len()
2720 let forbid_same_line_brace = overhead > remaining_budget;
2721 if !forbid_same_line_brace && same_line_brace {
2725 result.push_str(&offset.block_only().to_string(context.config));
2727 result.push_str(opener);
2732 impl Rewrite for ast::ForeignItem {
2733 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2734 let attrs_str = self.attrs.rewrite(context, shape)?;
2735 // Drop semicolon or it will be interpreted as comment.
2736 // FIXME: this may be a faulty span from libsyntax.
2737 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2739 let item_str = match self.node {
2740 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2744 &FnSig::new(fn_decl, generics, self.vis.clone()),
2748 ).map(|(s, _)| format!("{};", s)),
2749 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2750 // FIXME(#21): we're dropping potential comments in between the
2751 // function keywords here.
2752 let vis = format_visibility(&self.vis);
2753 let mut_str = if is_mutable { "mut " } else { "" };
2754 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2756 let shape = shape.sub_width(1)?;
2757 ty.rewrite(context, shape).map(|ty_str| {
2758 // 1 = space between prefix and type.
2759 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2762 let nested_indent = shape.indent.block_indent(context.config);
2763 format!("\n{}", nested_indent.to_string(context.config))
2765 format!("{}{}{};", prefix, sep, ty_str)
2768 ast::ForeignItemKind::Ty => {
2769 let vis = format_visibility(&self.vis);
2770 Some(format!("{}type {};", vis, self.ident))
2774 let missing_span = if self.attrs.is_empty() {
2775 mk_sp(self.span.lo(), self.span.lo())
2777 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2779 combine_strs_with_missing_comments(