1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16 last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
17 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
18 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
19 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use itertools::Itertools;
26 use syntax::{ast, abi, ptr, codemap};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::parse::token;
29 use syntax::ast::ImplItem;
31 // Statements of the form
32 // let pat: ty = init;
33 impl Rewrite for ast::Local {
34 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
35 let mut result = "let ".to_owned();
36 let pattern_offset = offset + result.len();
38 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
40 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
41 result.push_str(&pat_str);
43 // String that is placed within the assignment pattern and expression.
45 let mut infix = String::new();
47 if let Some(ref ty) = self.ty {
48 let separator = if context.config.space_before_type_annotation {
53 let indent = offset + last_line_width(&result) + separator.len();
55 let budget = try_opt!(width.checked_sub(indent.width() + 1));
56 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
58 infix.push_str(separator);
59 infix.push_str(&rewrite);
62 if self.init.is_some() {
69 result.push_str(&infix);
71 if let Some(ref ex) = self.init {
72 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
74 // 1 = trailing semicolon;
76 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
84 impl<'a> FmtVisitor<'a> {
85 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
86 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
87 self.buffer.push_str(&abi_str);
89 let snippet = self.snippet(span);
90 let brace_pos = snippet.find_uncommented("{").unwrap();
92 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
93 self.buffer.push_str("{");
95 // FIXME: this skips comments between the extern keyword and the opening
97 self.last_pos = span.lo + BytePos(brace_pos as u32);
98 self.block_indent = self.block_indent.block_indent(self.config);
100 for item in &fm.items {
101 self.format_foreign_item(&*item);
104 self.block_indent = self.block_indent.block_unindent(self.config);
105 self.format_missing_with_indent(span.hi - BytePos(1));
108 self.buffer.push_str("}");
109 self.last_pos = span.hi;
112 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
113 self.format_missing_with_indent(item.span.lo);
114 // Drop semicolon or it will be interpreted as comment.
115 // FIXME: this may be a faulty span from libsyntax.
116 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
119 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
120 let indent = self.block_indent;
121 let rewrite = rewrite_fn_base(&self.get_context(),
126 ast::Unsafety::Normal,
127 ast::Constness::NotConst,
128 ast::Defaultness::Final,
129 // These are not actually rust functions,
130 // but we format them as such.
138 Some((new_fn, _)) => {
139 self.buffer.push_str(&new_fn);
140 self.buffer.push_str(";");
142 None => self.format_missing(item.span.hi),
145 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
146 // FIXME(#21): we're dropping potential comments in between the
147 // function keywords here.
148 let vis = format_visibility(&item.vis);
149 let mut_str = if is_mutable { "mut " } else { "" };
150 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
151 let offset = self.block_indent + prefix.len();
153 let width = self.config.max_width - offset.width() - 1;
154 let rewrite = ty.rewrite(&self.get_context(), width, offset);
158 self.buffer.push_str(&prefix);
159 self.buffer.push_str(&result);
160 self.buffer.push_str(";");
162 None => self.format_missing(item.span.hi),
167 self.last_pos = item.span.hi;
170 pub fn rewrite_fn(&mut self,
174 generics: &ast::Generics,
175 unsafety: ast::Unsafety,
176 constness: ast::Constness,
177 defaultness: ast::Defaultness,
179 vis: &ast::Visibility,
183 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
184 let context = self.get_context();
186 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
187 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
188 !context.config.fn_empty_single_line;
190 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
204 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
205 newline_brace = false;
206 } else if force_newline_brace {
207 newline_brace = true;
210 // Prepare for the function body by possibly adding a newline and
212 // FIXME we'll miss anything between the end of the signature and the
213 // start of the body, but we need more spans from the compiler to solve
217 result.push_str(&indent.to_string(self.config));
222 self.single_line_fn(&result, block).or_else(|| Some(result))
225 pub fn rewrite_required_fn(&mut self,
228 sig: &ast::MethodSig,
231 // Drop semicolon or it will be interpreted as comment.
232 let span = mk_sp(span.lo, span.hi - BytePos(1));
233 let context = self.get_context();
235 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
242 ast::Defaultness::Final,
244 &ast::Visibility::Inherited,
249 // Re-attach semicolon
255 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
256 if fn_str.contains('\n') {
260 let codemap = self.get_context().codemap;
262 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
263 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
264 return Some(format!("{}{{}}", fn_str));
267 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
269 if let Some(ref e) = block.expr {
270 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
272 e.rewrite(&self.get_context(),
273 self.config.max_width - self.block_indent.width(),
276 .or_else(|| Some(self.snippet(e.span)))
277 } else if let Some(ref stmt) = block.stmts.first() {
278 stmt.rewrite(&self.get_context(),
279 self.config.max_width - self.block_indent.width(),
286 if let Some(res) = rewrite {
287 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
288 if !res.contains('\n') && width <= self.config.max_width {
289 return Some(format!("{}{{ {} }}", fn_str, res));
297 pub fn visit_enum(&mut self,
299 vis: &ast::Visibility,
300 enum_def: &ast::EnumDef,
301 generics: &ast::Generics,
303 self.buffer.push_str(&format_header("enum ", ident, vis));
305 let enum_snippet = self.snippet(span);
306 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
307 let generics_str = format_generics(&self.get_context(),
311 self.config.item_brace_style,
312 enum_def.variants.is_empty(),
314 self.block_indent.block_indent(self.config),
315 mk_sp(span.lo, body_start))
317 self.buffer.push_str(&generics_str);
319 self.last_pos = body_start;
321 self.block_indent = self.block_indent.block_indent(self.config);
322 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
324 Some(ref body_str) => self.buffer.push_str(&body_str),
325 None => self.format_missing(span.hi - BytePos(1)),
327 self.block_indent = self.block_indent.block_unindent(self.config);
329 if variant_list.is_some() {
330 self.buffer.push_str(&self.block_indent.to_string(self.config));
332 self.buffer.push_str("}");
333 self.last_pos = span.hi;
336 // Format the body of an enum definition
337 fn format_variant_list(&self,
338 enum_def: &ast::EnumDef,
342 if enum_def.variants.is_empty() {
345 let mut result = String::with_capacity(1024);
347 let indentation = self.block_indent.to_string(self.config);
348 result.push_str(&indentation);
350 let items = itemize_list(self.codemap,
351 enum_def.variants.iter(),
354 if !f.node.attrs.is_empty() {
355 f.node.attrs[0].span.lo
361 |f| self.format_variant(f),
365 let budget = self.config.max_width - self.block_indent.width() - 2;
366 let fmt = ListFormatting {
367 tactic: DefinitiveListTactic::Vertical,
369 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
370 indent: self.block_indent,
372 ends_with_newline: true,
376 let list = try_opt!(write_list(items, &fmt));
377 result.push_str(&list);
382 // Variant of an enum.
383 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
384 if contains_skip(&field.node.attrs) {
385 let lo = field.node.attrs[0].span.lo;
386 let span = mk_sp(lo, field.span.hi);
387 return Some(self.snippet(span));
390 let indent = self.block_indent;
391 let mut result = try_opt!(field.node
393 .rewrite(&self.get_context(),
394 self.config.max_width - indent.width(),
396 if !result.is_empty() {
398 result.push_str(&indent.to_string(self.config));
401 let context = self.get_context();
402 let variant_body = match field.node.data {
403 ast::VariantData::Tuple(..) |
404 ast::VariantData::Struct(..) => {
405 // FIXME: Should limit the width, as we have a trailing comma
406 format_struct(&context,
409 &ast::Visibility::Inherited,
414 Some(self.config.struct_variant_width))
416 ast::VariantData::Unit(..) => {
417 let tag = if let Some(ref expr) = field.node.disr_expr {
418 format!("{} = {}", field.node.name, self.snippet(expr.span))
420 field.node.name.to_string()
424 self.config.max_width,
425 self.config.max_width - indent.width(),
430 if let Some(variant_str) = variant_body {
431 result.push_str(&variant_str);
439 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
440 if let ast::ItemKind::Impl(unsafety,
445 ref items) = item.node {
446 let mut result = String::new();
448 result.push_str(&*format_visibility(&item.vis));
449 result.push_str(format_unsafety(unsafety));
450 result.push_str("impl");
452 let lo = context.codemap.span_after(item.span, "impl");
453 let hi = match *trait_ref {
454 Some(ref tr) => tr.path.span.lo,
455 None => self_ty.span.lo,
457 let generics_str = try_opt!(rewrite_generics(context,
460 context.config.max_width,
461 offset + result.len(),
463 result.push_str(&generics_str);
465 // FIXME might need to linebreak in the impl header, here would be a
468 if polarity == ast::ImplPolarity::Negative {
469 result.push_str("!");
471 if let Some(ref trait_ref) = *trait_ref {
472 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
473 let indent = offset + result.len();
474 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
475 result.push_str(" for ");
478 let mut used_space = result.len();
479 if generics.where_clause.predicates.is_empty() {
480 // If there is no where clause adapt budget for type formatting to take space and curly
481 // brace into account.
482 match context.config.item_brace_style {
483 BraceStyle::AlwaysNextLine => {}
484 BraceStyle::PreferSameLine => used_space += 2,
485 BraceStyle::SameLineWhere => used_space += 2,
489 let budget = try_opt!(context.config.max_width.checked_sub(used_space));
490 let indent = offset + result.len();
491 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
493 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
494 let where_clause_str = try_opt!(rewrite_where_clause(context,
495 &generics.where_clause,
497 context.config.item_brace_style,
498 context.block_indent,
500 context.config.where_density,
505 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
506 result.push_str(&where_clause_str);
507 if where_clause_str.contains('\n') {
508 let white_space = offset.to_string(context.config);
509 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
511 result.push_str(" {}");
516 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
518 let width = context.block_indent.width() + context.config.tab_spaces - 1;
519 let where_indent = Indent::new(0, width);
520 result.push_str(&where_indent.to_string(context.config));
522 result.push_str(&where_clause_str);
524 match context.config.item_brace_style {
525 BraceStyle::AlwaysNextLine => result.push('\n'),
526 BraceStyle::PreferSameLine => result.push(' '),
527 BraceStyle::SameLineWhere => {
528 if !where_clause_str.is_empty() {
530 result.push_str(&offset.to_string(context.config));
539 let snippet = context.snippet(item.span);
540 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
542 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
543 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
544 visitor.block_indent = context.block_indent.block_indent(context.config);
545 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
548 visitor.visit_impl_item(&item);
551 visitor.format_missing(item.span.hi - BytePos(1));
553 let inner_indent_str = visitor.block_indent.to_string(context.config);
554 let outer_indent_str = context.block_indent.to_string(context.config);
557 result.push_str(&inner_indent_str);
558 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
560 result.push_str(&outer_indent_str);
563 if result.chars().last().unwrap() == '{' {
574 fn is_impl_single_line(context: &RewriteContext,
575 items: &Vec<ImplItem>,
577 where_clause_str: &str,
580 let snippet = context.snippet(item.span);
581 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
583 Some(context.config.impl_empty_single_line && items.is_empty() &&
584 result.len() + where_clause_str.len() <= context.config.max_width &&
585 !contains_comment(&snippet[open_pos..]))
588 pub fn format_struct(context: &RewriteContext,
591 vis: &ast::Visibility,
592 struct_def: &ast::VariantData,
593 generics: Option<&ast::Generics>,
596 one_line_width: Option<usize>)
599 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
600 ast::VariantData::Tuple(ref fields, _) => {
601 format_tuple_struct(context,
610 ast::VariantData::Struct(ref fields, _) => {
611 format_struct_struct(context,
624 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
625 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
627 let mut result = String::new();
628 let header = format!("{}{}trait {}",
629 format_visibility(&item.vis),
630 format_unsafety(unsafety),
633 result.push_str(&header);
635 let body_lo = context.codemap.span_after(item.span, "{");
637 let generics_str = try_opt!(rewrite_generics(context,
640 context.config.max_width,
641 offset + result.len(),
642 mk_sp(item.span.lo, body_lo)));
643 result.push_str(&generics_str);
645 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
648 context.config.max_width));
649 // If the trait, generics, and trait bound cannot fit on the same line,
650 // put the trait bounds on an indented new line
651 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
652 context.config.ideal_width {
654 let width = context.block_indent.width() + context.config.tab_spaces;
655 let trait_indent = Indent::new(0, width);
656 result.push_str(&trait_indent.to_string(context.config));
658 result.push_str(&trait_bound_str);
660 let has_body = !trait_items.is_empty();
663 if (context.config.where_density == Density::Compressed &&
664 (!result.contains('\n') ||
665 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
666 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
667 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
668 !result.contains('\n')) {
674 let where_budget = try_opt!(context.config
676 .checked_sub(last_line_width(&result)));
677 let where_clause_str = try_opt!(rewrite_where_clause(context,
678 &generics.where_clause,
680 context.config.item_brace_style,
681 context.block_indent,
687 // If the where clause cannot fit on the same line,
688 // put the where clause on a new line
689 if !where_clause_str.contains('\n') &&
690 last_line_width(&result) + where_clause_str.len() + offset.width() >
691 context.config.ideal_width {
693 let width = context.block_indent.width() + context.config.tab_spaces - 1;
694 let where_indent = Indent::new(0, width);
695 result.push_str(&where_indent.to_string(context.config));
697 result.push_str(&where_clause_str);
699 match context.config.item_brace_style {
700 BraceStyle::AlwaysNextLine => {
702 result.push_str(&offset.to_string(context.config));
704 BraceStyle::PreferSameLine => result.push(' '),
705 BraceStyle::SameLineWhere => {
706 if !where_clause_str.is_empty() &&
707 (trait_items.len() > 0 || result.contains('\n')) {
709 result.push_str(&offset.to_string(context.config));
717 let snippet = context.snippet(item.span);
718 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
720 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
721 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
722 visitor.block_indent = context.block_indent.block_indent(context.config);
723 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
725 for item in trait_items {
726 visitor.visit_trait_item(&item);
729 visitor.format_missing(item.span.hi - BytePos(1));
731 let inner_indent_str = visitor.block_indent.to_string(context.config);
732 let outer_indent_str = context.block_indent.to_string(context.config);
735 result.push_str(&inner_indent_str);
736 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
738 result.push_str(&outer_indent_str);
739 } else if result.contains('\n') {
750 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
751 format!("{};", format_header(item_name, ident, vis))
754 fn format_struct_struct(context: &RewriteContext,
757 vis: &ast::Visibility,
758 fields: &[ast::StructField],
759 generics: Option<&ast::Generics>,
762 one_line_width: Option<usize>)
764 let mut result = String::with_capacity(1024);
766 let header_str = format_header(item_name, ident, vis);
767 result.push_str(&header_str);
769 let body_lo = context.codemap.span_after(span, "{");
771 let generics_str = match generics {
773 try_opt!(format_generics(context,
777 context.config.item_brace_style,
780 offset + header_str.len(),
781 mk_sp(span.lo, body_lo)))
784 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
785 format!("\n{}{{", context.block_indent.to_string(context.config))
791 result.push_str(&generics_str);
793 // FIXME(#919): properly format empty structs and their comments.
794 if fields.is_empty() {
795 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
799 let item_indent = offset.block_indent(context.config);
801 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
803 let items = itemize_list(context.codemap,
807 // Include attributes and doc comments, if present
808 if !field.attrs.is_empty() {
809 field.attrs[0].span.lo
814 |field| field.ty.span.hi,
815 |field| field.rewrite(context, item_budget, item_indent),
816 context.codemap.span_after(span, "{"),
818 .collect::<Vec<_>>();
820 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
822 let tactic = match one_line_width {
823 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
824 None => DefinitiveListTactic::Vertical,
827 let fmt = ListFormatting {
830 trailing_separator: context.config.struct_trailing_comma,
833 ends_with_newline: true,
834 config: context.config,
836 let items_str = try_opt!(write_list(&items, &fmt));
837 if one_line_width.is_some() && !items_str.contains('\n') {
838 Some(format!("{} {} }}", result, items_str))
840 Some(format!("{}\n{}{}\n{}}}",
842 offset.block_indent(context.config).to_string(context.config),
844 offset.to_string(context.config)))
848 fn format_tuple_struct(context: &RewriteContext,
851 vis: &ast::Visibility,
852 fields: &[ast::StructField],
853 generics: Option<&ast::Generics>,
857 let mut result = String::with_capacity(1024);
859 let header_str = format_header(item_name, ident, vis);
860 result.push_str(&header_str);
862 // FIXME(#919): don't lose comments on empty tuple structs.
863 let body_lo = if fields.is_empty() {
869 let where_clause_str = match generics {
870 Some(ref generics) => {
871 let generics_str = try_opt!(rewrite_generics(context,
874 context.config.max_width,
875 offset + header_str.len(),
876 mk_sp(span.lo, body_lo)));
877 result.push_str(&generics_str);
879 let where_budget = try_opt!(context.config
881 .checked_sub(last_line_width(&result)));
882 try_opt!(rewrite_where_clause(context,
883 &generics.where_clause,
885 context.config.item_brace_style,
886 context.block_indent,
893 None => "".to_owned(),
897 let item_indent = context.block_indent + result.len();
899 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
901 let items = itemize_list(context.codemap,
905 // Include attributes and doc comments, if present
906 if !field.attrs.is_empty() {
907 field.attrs[0].span.lo
912 |field| field.ty.span.hi,
913 |field| field.rewrite(context, item_budget, item_indent),
914 context.codemap.span_after(span, "("),
916 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
917 result.push_str(&body);
920 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
921 (result.contains('\n') ||
922 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
923 context.config.max_width) {
924 // We need to put the where clause on a new line, but we didn'to_string
925 // know that earlier, so the where clause will not be indented properly.
927 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
928 .to_string(context.config));
930 result.push_str(&where_clause_str);
935 pub fn rewrite_type_alias(context: &RewriteContext,
939 generics: &ast::Generics,
940 vis: &ast::Visibility,
943 let mut result = String::new();
945 result.push_str(&format_visibility(&vis));
946 result.push_str("type ");
947 result.push_str(&ident.to_string());
949 let generics_indent = indent + result.len();
950 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
951 let generics_width = context.config.max_width - " =".len();
952 let generics_str = try_opt!(rewrite_generics(context,
959 result.push_str(&generics_str);
961 let where_budget = try_opt!(context.config
963 .checked_sub(last_line_width(&result)));
964 let where_clause_str = try_opt!(rewrite_where_clause(context,
965 &generics.where_clause,
967 context.config.item_brace_style,
970 context.config.where_density,
974 result.push_str(&where_clause_str);
975 result.push_str(" = ");
977 let line_width = last_line_width(&result);
978 // This checked_sub may fail as the extra space after '=' is not taken into account
979 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
980 let budget = context.config
982 .checked_sub(indent.width() + line_width + ";".len())
984 let type_indent = indent + line_width;
985 // Try to fit the type on the same line
986 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
988 // The line was too short, try to put the type on the next line
990 // Remove the space after '='
992 let type_indent = indent.block_indent(context.config);
994 result.push_str(&type_indent.to_string(context.config));
995 let budget = try_opt!(context.config
997 .checked_sub(type_indent.width() + ";".len()));
998 ty.rewrite(context, budget, type_indent)
1000 result.push_str(&ty_str);
1001 result.push_str(";");
1005 fn type_annotation_spacing(config: &Config) -> &str {
1006 if config.space_before_type_annotation {
1013 impl Rewrite for ast::StructField {
1014 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1015 if contains_skip(&self.attrs) {
1016 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1017 return wrap_str(span, context.config.max_width, width, offset);
1020 let name = self.ident;
1021 let vis = format_visibility(&self.vis);
1022 let mut attr_str = try_opt!(self.attrs
1023 .rewrite(context, context.config.max_width - offset.width(), offset));
1024 if !attr_str.is_empty() {
1025 attr_str.push('\n');
1026 attr_str.push_str(&offset.to_string(context.config));
1029 let type_annotation_spacing = type_annotation_spacing(context.config);
1030 let result = match name {
1031 Some(name) => format!("{}{}{}{}: ", attr_str, vis, name, type_annotation_spacing),
1032 None => format!("{}{}", attr_str, vis),
1035 let last_line_width = last_line_width(&result);
1036 let budget = try_opt!(width.checked_sub(last_line_width));
1037 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1038 Some(result + &rewrite)
1042 pub fn rewrite_static(prefix: &str,
1043 vis: &ast::Visibility,
1046 mutability: ast::Mutability,
1047 expr_opt: Option<&ptr::P<ast::Expr>>,
1048 context: &RewriteContext)
1050 let type_annotation_spacing = type_annotation_spacing(context.config);
1051 let prefix = format!("{}{} {}{}{}: ",
1052 format_visibility(vis),
1054 format_mutability(mutability),
1056 type_annotation_spacing);
1058 let ty_str = try_opt!(ty.rewrite(context,
1059 context.config.max_width - context.block_indent.width() -
1061 context.block_indent));
1063 if let Some(ref expr) = expr_opt {
1064 let lhs = format!("{}{} =", prefix, ty_str);
1066 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1067 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1070 let lhs = format!("{}{};", prefix, ty_str);
1075 pub fn rewrite_associated_type(ident: ast::Ident,
1076 ty_opt: Option<&ptr::P<ast::Ty>>,
1077 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1078 context: &RewriteContext,
1081 let prefix = format!("type {}", ident);
1083 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1084 let bounds: &[_] = &ty_param_bounds;
1085 let bound_str = try_opt!(bounds.iter()
1086 .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1087 .intersperse(Some(" + ".to_string()))
1088 .collect::<Option<String>>());
1089 if bounds.len() > 0 {
1090 format!(": {}", bound_str)
1098 if let Some(ty) = ty_opt {
1099 let ty_str = try_opt!(ty.rewrite(context,
1100 context.config.max_width - context.block_indent.width() -
1103 context.block_indent));
1104 Some(format!("{} = {};", prefix, ty_str))
1106 Some(format!("{}{};", prefix, type_bounds_str))
1110 impl Rewrite for ast::FunctionRetTy {
1111 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1113 ast::FunctionRetTy::Default(_) => Some(String::new()),
1114 ast::FunctionRetTy::None(_) => {
1116 Some("-> !".to_owned())
1121 ast::FunctionRetTy::Ty(ref ty) => {
1122 let inner_width = try_opt!(width.checked_sub(3));
1123 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1129 impl Rewrite for ast::Arg {
1130 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1131 if is_named_arg(self) {
1132 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1134 if self.ty.node != ast::TyKind::Infer {
1135 if context.config.space_before_type_annotation {
1136 result.push_str(" ");
1138 result.push_str(": ");
1139 let max_width = try_opt!(width.checked_sub(result.len()));
1140 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1141 result.push_str(&ty_str);
1146 self.ty.rewrite(context, width, offset)
1151 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1153 context: &RewriteContext)
1155 match explicit_self.node {
1156 ast::SelfKind::Region(lt, m) => {
1157 let mut_str = format_mutability(m);
1161 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1162 Some(format!("&{} {}self", lifetime_str, mut_str))
1164 None => Some(format!("&{}self", mut_str)),
1167 ast::SelfKind::Explicit(ref ty, _) => {
1168 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1170 let mutability = explicit_self_mutability(&args[0]);
1171 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1173 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1175 ast::SelfKind::Value(_) => {
1176 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1178 let mutability = explicit_self_mutability(&args[0]);
1180 Some(format!("{}self", format_mutability(mutability)))
1185 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1186 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1187 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1188 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1195 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1196 if is_named_arg(arg) {
1203 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1205 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1206 _ => arg.ty.span.hi,
1210 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1211 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1212 ident.node != token::keywords::Invalid.ident()
1218 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1220 ast::FunctionRetTy::None(ref span) |
1221 ast::FunctionRetTy::Default(ref span) => span.clone(),
1222 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1226 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1227 // Note that ty.span is the span for ty.ident, not the whole item.
1228 let lo = ty.span.lo;
1229 if let Some(ref def) = ty.default {
1230 return mk_sp(lo, def.span.hi);
1232 if ty.bounds.is_empty() {
1235 let hi = match ty.bounds[ty.bounds.len() - 1] {
1236 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1237 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1242 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1244 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1245 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1246 ast::WherePredicate::EqPredicate(ref p) => p.span,
1250 // Return type is (result, force_new_line_for_brace)
1251 fn rewrite_fn_base(context: &RewriteContext,
1255 generics: &ast::Generics,
1256 unsafety: ast::Unsafety,
1257 constness: ast::Constness,
1258 defaultness: ast::Defaultness,
1260 vis: &ast::Visibility,
1262 newline_brace: bool,
1264 -> Option<(String, bool)> {
1265 let mut force_new_line_for_brace = false;
1266 // FIXME we'll lose any comments in between parts of the function decl, but
1267 // anyone who comments there probably deserves what they get.
1269 let where_clause = &generics.where_clause;
1271 let mut result = String::with_capacity(1024);
1272 // Vis unsafety abi.
1273 result.push_str(&*format_visibility(vis));
1275 if let ast::Defaultness::Default = defaultness {
1276 result.push_str("default ");
1279 if let ast::Constness::Const = constness {
1280 result.push_str("const ");
1283 result.push_str(::utils::format_unsafety(unsafety));
1285 if abi != abi::Abi::Rust {
1286 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1290 result.push_str("fn ");
1291 result.push_str(&ident.to_string());
1294 let generics_indent = indent + result.len();
1295 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1296 let generics_str = try_opt!(rewrite_generics(context,
1299 context.config.max_width,
1302 result.push_str(&generics_str);
1304 // Note that if the width and indent really matter, we'll re-layout the
1305 // return type later anyway.
1306 let ret_str = try_opt!(fd.output
1307 .rewrite(&context, context.config.max_width - indent.width(), indent));
1309 let multi_line_ret_str = ret_str.contains('\n');
1310 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1313 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1314 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1316 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1317 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1318 arg_indent = indent.block_indent(context.config);
1319 multi_line_budget = context.config.max_width - arg_indent.width();
1322 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1327 // Check if vertical layout was forced by compute_budget_for_args.
1328 if one_line_budget == 0 {
1329 if context.config.fn_args_paren_newline {
1331 result.push_str(&arg_indent.to_string(context.config));
1332 arg_indent = arg_indent + 1; // extra space for `(`
1335 result.push_str("(\n");
1336 result.push_str(&arg_indent.to_string(context.config));
1342 if multi_line_ret_str {
1343 one_line_budget = 0;
1346 // A conservative estimation, to goal is to be over all parens in generics
1347 let args_start = generics.ty_params
1349 .map_or(span.lo, |tp| end_typaram(tp));
1350 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1351 span_for_return(&fd.output).lo);
1352 let arg_str = try_opt!(rewrite_args(context,
1354 fd.get_self().as_ref(),
1362 let multi_line_arg_str = arg_str.contains('\n');
1364 let put_args_in_block = match context.config.fn_args_layout {
1365 FnArgLayoutStyle::Block => multi_line_arg_str,
1366 FnArgLayoutStyle::BlockAlways => true,
1368 } && fd.inputs.len() > 0;
1370 if put_args_in_block {
1371 arg_indent = indent.block_indent(context.config);
1373 result.push_str(&arg_indent.to_string(context.config));
1374 result.push_str(&arg_str);
1376 result.push_str(&indent.to_string(context.config));
1379 result.push_str(&arg_str);
1384 if !ret_str.is_empty() {
1385 let ret_should_indent = match context.config.fn_args_layout {
1386 // If our args are block layout then we surely must have space.
1387 FnArgLayoutStyle::Block if put_args_in_block => false,
1388 FnArgLayoutStyle::BlockAlways => false,
1390 // If we've already gone multi-line, or the return type would push
1391 // over the max width, then put the return type on a new line.
1392 result.contains("\n") || multi_line_ret_str ||
1393 result.len() + indent.width() + ret_str_len > context.config.max_width
1396 let ret_indent = if ret_should_indent {
1397 let indent = match context.config.fn_return_indent {
1398 ReturnIndent::WithWhereClause => indent + 4,
1399 // Aligning with non-existent args looks silly.
1400 _ if arg_str.is_empty() => {
1401 force_new_line_for_brace = true;
1404 // FIXME: we might want to check that using the arg indent
1405 // doesn't blow our budget, and if it does, then fallback to
1406 // the where clause indent.
1411 result.push_str(&indent.to_string(context.config));
1415 Indent::new(indent.width(), result.len())
1418 if multi_line_ret_str {
1419 // Now that we know the proper indent and width, we need to
1420 // re-layout the return type.
1422 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1423 let ret_str = try_opt!(fd.output
1424 .rewrite(context, budget, ret_indent));
1425 result.push_str(&ret_str);
1427 result.push_str(&ret_str);
1430 // Comment between return type and the end of the decl.
1431 let snippet_lo = fd.output.span().hi;
1432 if where_clause.predicates.is_empty() {
1433 let snippet_hi = span.hi;
1434 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1435 let snippet = snippet.trim();
1436 if !snippet.is_empty() {
1438 result.push_str(snippet);
1441 // FIXME it would be nice to catch comments between the return type
1442 // and the where clause, but we don't have a span for the where
1447 let should_compress_where = match context.config.where_density {
1448 Density::Compressed => !result.contains('\n') || put_args_in_block,
1449 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1451 } || (put_args_in_block && ret_str.is_empty());
1453 let where_density = if should_compress_where {
1460 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1461 let where_clause_str = try_opt!(rewrite_where_clause(context,
1464 context.config.fn_brace_style,
1472 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1473 !where_clause_str.contains('\n') {
1477 result.push_str(&where_clause_str);
1479 Some((result, force_new_line_for_brace))
1482 fn rewrite_args(context: &RewriteContext,
1484 explicit_self: Option<&ast::ExplicitSelf>,
1485 one_line_budget: usize,
1486 multi_line_budget: usize,
1492 let mut arg_item_strs = try_opt!(args.iter()
1493 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1494 .collect::<Option<Vec<_>>>());
1496 // Account for sugary self.
1497 // FIXME: the comment for the self argument is dropped. This is blocked
1498 // on rust issue #27522.
1500 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1501 .map_or(1, |self_str| {
1502 arg_item_strs[0] = self_str;
1506 // Comments between args.
1507 let mut arg_items = Vec::new();
1509 arg_items.push(ListItem::from_str(""));
1512 // FIXME(#21): if there are no args, there might still be a comment, but
1513 // without spans for the comment or parens, there is no chance of
1514 // getting it right. You also don't get to put a comment on self, unless
1516 if args.len() >= min_args || variadic {
1517 let comment_span_start = if min_args == 2 {
1518 let second_arg_start = if arg_has_pattern(&args[1]) {
1523 let reduced_span = mk_sp(span.lo, second_arg_start);
1525 context.codemap.span_after_last(reduced_span, ",")
1530 enum ArgumentKind<'a> {
1531 Regular(&'a ast::Arg),
1535 let variadic_arg = if variadic {
1536 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1537 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1538 Some(ArgumentKind::Variadic(variadic_start))
1543 let more_items = itemize_list(context.codemap,
1544 args[min_args - 1..]
1546 .map(ArgumentKind::Regular)
1547 .chain(variadic_arg),
1551 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1552 ArgumentKind::Variadic(start) => start,
1557 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1558 ArgumentKind::Variadic(start) => start + BytePos(3),
1563 ArgumentKind::Regular(..) => None,
1564 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1570 arg_items.extend(more_items);
1573 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1574 item.item = Some(arg);
1577 let indent = match context.config.fn_arg_indent {
1578 BlockIndentStyle::Inherit => indent,
1579 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1580 BlockIndentStyle::Visual => arg_indent,
1583 let tactic = definitive_tactic(&arg_items,
1584 context.config.fn_args_density.to_list_tactic(),
1586 let budget = match tactic {
1587 DefinitiveListTactic::Horizontal => one_line_budget,
1588 _ => multi_line_budget,
1591 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1593 let end_with_newline = match context.config.fn_args_layout {
1594 FnArgLayoutStyle::Block |
1595 FnArgLayoutStyle::BlockAlways => true,
1599 let fmt = ListFormatting {
1602 trailing_separator: SeparatorTactic::Never,
1605 ends_with_newline: end_with_newline,
1606 config: context.config,
1609 write_list(&arg_items, &fmt)
1612 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1613 if let ast::PatKind::Ident(_,
1615 node: ast::Ident { name: ast::Name(0u32), .. },
1625 fn compute_budgets_for_args(context: &RewriteContext,
1629 newline_brace: bool)
1630 -> Option<((usize, usize, Indent))> {
1631 // Try keeping everything on the same line.
1632 if !result.contains("\n") {
1633 // 3 = `() `, space is before ret_string.
1634 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1638 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1640 if one_line_budget > 0 {
1642 let multi_line_budget =
1643 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1645 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1649 // Didn't work. we must force vertical layout and put args on a newline.
1650 let new_indent = indent.block_indent(context.config);
1651 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1652 let max_space = context.config.max_width;
1653 if used_space <= max_space {
1654 Some((0, max_space - used_space, new_indent))
1656 // Whoops! bankrupt.
1661 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1662 match config.fn_brace_style {
1663 BraceStyle::AlwaysNextLine => true,
1664 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1669 fn rewrite_generics(context: &RewriteContext,
1670 generics: &ast::Generics,
1673 generics_offset: Indent,
1676 // FIXME: convert bounds to where clauses where they get too big or if
1677 // there is a where clause at all.
1678 let lifetimes: &[_] = &generics.lifetimes;
1679 let tys: &[_] = &generics.ty_params;
1680 if lifetimes.is_empty() && tys.is_empty() {
1681 return Some(String::new());
1684 let offset = match context.config.generics_indent {
1685 BlockIndentStyle::Inherit => offset,
1686 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1688 BlockIndentStyle::Visual => generics_offset + 1,
1691 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1692 // FIXME: might need to insert a newline if the generics are really long.
1694 // Strings for the generics.
1695 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1696 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1698 // Extract comments between generics.
1699 let lt_spans = lifetimes.iter().map(|l| {
1700 let hi = if l.bounds.is_empty() {
1703 l.bounds[l.bounds.len() - 1].span.hi
1705 mk_sp(l.lifetime.span.lo, hi)
1707 let ty_spans = tys.iter().map(span_for_ty_param);
1709 let items = itemize_list(context.codemap,
1710 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1714 // FIXME: don't clone
1715 |&(_, ref str)| str.clone(),
1716 context.codemap.span_after(span, "<"),
1718 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1720 Some(format!("<{}>", list_str))
1723 fn rewrite_trait_bounds(context: &RewriteContext,
1724 type_param_bounds: &ast::TyParamBounds,
1728 let bounds: &[_] = &type_param_bounds;
1730 if bounds.is_empty() {
1731 return Some(String::new());
1734 let bound_str = try_opt!(bounds.iter()
1735 .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1736 .intersperse(Some(" + ".to_string()))
1737 .collect::<Option<String>>());
1739 let mut result = String::new();
1740 result.push_str(": ");
1741 result.push_str(&bound_str);
1745 fn rewrite_where_clause(context: &RewriteContext,
1746 where_clause: &ast::WhereClause,
1748 brace_style: BraceStyle,
1753 allow_trailing_comma: bool,
1754 span_end: Option<BytePos>)
1756 if where_clause.predicates.is_empty() {
1757 return Some(String::new());
1760 let extra_indent = match context.config.where_indent {
1761 BlockIndentStyle::Inherit => Indent::empty(),
1762 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1765 let offset = match context.config.where_pred_indent {
1766 BlockIndentStyle::Inherit => indent + extra_indent,
1767 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1768 // 6 = "where ".len()
1769 BlockIndentStyle::Visual => indent + extra_indent + 6,
1771 // FIXME: if where_pred_indent != Visual, then the budgets below might
1772 // be out by a char or two.
1774 let budget = context.config.max_width - offset.width();
1775 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1776 // If we don't have the start of the next span, then use the end of the
1777 // predicates, but that means we miss comments.
1778 let len = where_clause.predicates.len();
1779 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1780 let span_end = span_end.unwrap_or(end_of_preds);
1781 let items = itemize_list(context.codemap,
1782 where_clause.predicates.iter(),
1784 |pred| span_for_where_pred(pred).lo,
1785 |pred| span_for_where_pred(pred).hi,
1786 |pred| pred.rewrite(&context, budget, offset),
1789 let item_vec = items.collect::<Vec<_>>();
1790 // FIXME: we don't need to collect here if the where_layout isn't
1791 // HorizontalVertical.
1792 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1793 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1795 let fmt = ListFormatting {
1798 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1801 ends_with_newline: true,
1802 config: context.config,
1804 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1806 let end_length = if terminator == "{" {
1807 // If the brace is on the next line we don't need to count it otherwise it needs two
1810 BraceStyle::AlwaysNextLine => 0,
1811 BraceStyle::PreferSameLine => 2,
1812 BraceStyle::SameLineWhere => 0,
1814 } else if terminator == "=" {
1819 if density == Density::Tall || preds_str.contains('\n') ||
1820 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1821 Some(format!("\n{}where {}",
1822 (indent + extra_indent).to_string(context.config),
1825 Some(format!(" where {}", preds_str))
1829 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1830 format!("{}{}{}", format_visibility(vis), item_name, ident)
1833 fn format_generics(context: &RewriteContext,
1834 generics: &ast::Generics,
1837 brace_style: BraceStyle,
1838 force_same_line_brace: bool,
1840 generics_offset: Indent,
1843 let mut result = try_opt!(rewrite_generics(context,
1846 context.config.max_width,
1850 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1851 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1852 let where_clause_str = try_opt!(rewrite_where_clause(context,
1853 &generics.where_clause,
1856 context.block_indent,
1862 result.push_str(&where_clause_str);
1863 if !force_same_line_brace &&
1864 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1866 result.push_str(&context.block_indent.to_string(context.config));
1870 result.push_str(opener);
1872 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1874 result.push_str(&context.block_indent.to_string(context.config));
1878 result.push_str(opener);