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 {
50 let indent = offset + last_line_width(&result) + 2;
51 let budget = try_opt!(width.checked_sub(indent.width() + 1));
52 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
55 infix.push_str(&rewrite);
58 if self.init.is_some() {
65 result.push_str(&infix);
67 if let Some(ref ex) = self.init {
68 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
70 // 1 = trailing semicolon;
72 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
80 impl<'a> FmtVisitor<'a> {
81 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
82 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
83 self.buffer.push_str(&abi_str);
85 let snippet = self.snippet(span);
86 let brace_pos = snippet.find_uncommented("{").unwrap();
88 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
89 self.buffer.push_str("{");
91 // FIXME: this skips comments between the extern keyword and the opening
93 self.last_pos = span.lo + BytePos(brace_pos as u32);
94 self.block_indent = self.block_indent.block_indent(self.config);
96 for item in &fm.items {
97 self.format_foreign_item(&*item);
100 self.block_indent = self.block_indent.block_unindent(self.config);
101 self.format_missing_with_indent(span.hi - BytePos(1));
104 self.buffer.push_str("}");
105 self.last_pos = span.hi;
108 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
109 self.format_missing_with_indent(item.span.lo);
110 // Drop semicolon or it will be interpreted as comment.
111 // FIXME: this may be a faulty span from libsyntax.
112 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
115 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
116 let indent = self.block_indent;
117 let rewrite = rewrite_fn_base(&self.get_context(),
122 ast::Unsafety::Normal,
123 ast::Constness::NotConst,
124 ast::Defaultness::Final,
125 // These are not actually rust functions,
126 // but we format them as such.
134 Some((new_fn, _)) => {
135 self.buffer.push_str(&new_fn);
136 self.buffer.push_str(";");
138 None => self.format_missing(item.span.hi),
141 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
142 // FIXME(#21): we're dropping potential comments in between the
143 // function keywords here.
144 let vis = format_visibility(&item.vis);
145 let mut_str = if is_mutable { "mut " } else { "" };
146 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
147 let offset = self.block_indent + prefix.len();
149 let width = self.config.max_width - offset.width() - 1;
150 let rewrite = ty.rewrite(&self.get_context(), width, offset);
154 self.buffer.push_str(&prefix);
155 self.buffer.push_str(&result);
156 self.buffer.push_str(";");
158 None => self.format_missing(item.span.hi),
163 self.last_pos = item.span.hi;
166 pub fn rewrite_fn(&mut self,
170 generics: &ast::Generics,
171 unsafety: ast::Unsafety,
172 constness: ast::Constness,
173 defaultness: ast::Defaultness,
175 vis: &ast::Visibility,
179 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
180 let context = self.get_context();
182 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
183 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
184 !context.config.fn_empty_single_line;
186 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
200 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
201 newline_brace = false;
202 } else if force_newline_brace {
203 newline_brace = true;
206 // Prepare for the function body by possibly adding a newline and
208 // FIXME we'll miss anything between the end of the signature and the
209 // start of the body, but we need more spans from the compiler to solve
213 result.push_str(&indent.to_string(self.config));
218 self.single_line_fn(&result, block).or_else(|| Some(result))
221 pub fn rewrite_required_fn(&mut self,
224 sig: &ast::MethodSig,
227 // Drop semicolon or it will be interpreted as comment.
228 let span = mk_sp(span.lo, span.hi - BytePos(1));
229 let context = self.get_context();
231 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
238 ast::Defaultness::Final,
240 &ast::Visibility::Inherited,
245 // Re-attach semicolon
251 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
252 if fn_str.contains('\n') {
256 let codemap = self.get_context().codemap;
258 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
259 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
260 return Some(format!("{}{{}}", fn_str));
263 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
265 if let Some(ref e) = block.expr {
266 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
268 e.rewrite(&self.get_context(),
269 self.config.max_width - self.block_indent.width(),
272 .or_else(|| Some(self.snippet(e.span)))
273 } else if let Some(ref stmt) = block.stmts.first() {
274 stmt.rewrite(&self.get_context(),
275 self.config.max_width - self.block_indent.width(),
282 if let Some(res) = rewrite {
283 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
284 if !res.contains('\n') && width <= self.config.max_width {
285 return Some(format!("{}{{ {} }}", fn_str, res));
293 pub fn visit_enum(&mut self,
295 vis: &ast::Visibility,
296 enum_def: &ast::EnumDef,
297 generics: &ast::Generics,
299 self.buffer.push_str(&format_header("enum ", ident, vis));
301 let enum_snippet = self.snippet(span);
302 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
303 let generics_str = format_generics(&self.get_context(),
307 self.config.item_brace_style,
308 enum_def.variants.is_empty(),
310 self.block_indent.block_indent(self.config),
311 mk_sp(span.lo, body_start))
313 self.buffer.push_str(&generics_str);
315 self.last_pos = body_start;
317 self.block_indent = self.block_indent.block_indent(self.config);
318 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
320 Some(ref body_str) => self.buffer.push_str(&body_str),
321 None => self.format_missing(span.hi - BytePos(1)),
323 self.block_indent = self.block_indent.block_unindent(self.config);
325 if variant_list.is_some() {
326 self.buffer.push_str(&self.block_indent.to_string(self.config));
328 self.buffer.push_str("}");
329 self.last_pos = span.hi;
332 // Format the body of an enum definition
333 fn format_variant_list(&self,
334 enum_def: &ast::EnumDef,
338 if enum_def.variants.is_empty() {
341 let mut result = String::with_capacity(1024);
343 let indentation = self.block_indent.to_string(self.config);
344 result.push_str(&indentation);
346 let items = itemize_list(self.codemap,
347 enum_def.variants.iter(),
350 if !f.node.attrs.is_empty() {
351 f.node.attrs[0].span.lo
357 |f| self.format_variant(f),
361 let budget = self.config.max_width - self.block_indent.width() - 2;
362 let fmt = ListFormatting {
363 tactic: DefinitiveListTactic::Vertical,
365 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
366 indent: self.block_indent,
368 ends_with_newline: true,
372 let list = try_opt!(write_list(items, &fmt));
373 result.push_str(&list);
378 // Variant of an enum.
379 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
380 if contains_skip(&field.node.attrs) {
381 let lo = field.node.attrs[0].span.lo;
382 let span = mk_sp(lo, field.span.hi);
383 return Some(self.snippet(span));
386 let indent = self.block_indent;
387 let mut result = try_opt!(field.node
389 .rewrite(&self.get_context(),
390 self.config.max_width - indent.width(),
392 if !result.is_empty() {
394 result.push_str(&indent.to_string(self.config));
397 let context = self.get_context();
398 let variant_body = match field.node.data {
399 ast::VariantData::Tuple(..) |
400 ast::VariantData::Struct(..) => {
401 // FIXME: Should limit the width, as we have a trailing comma
402 format_struct(&context,
405 &ast::Visibility::Inherited,
410 Some(self.config.struct_variant_width))
412 ast::VariantData::Unit(..) => {
413 let tag = if let Some(ref expr) = field.node.disr_expr {
414 format!("{} = {}", field.node.name, self.snippet(expr.span))
416 field.node.name.to_string()
420 self.config.max_width,
421 self.config.max_width - indent.width(),
426 if let Some(variant_str) = variant_body {
427 result.push_str(&variant_str);
435 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
436 if let ast::ItemKind::Impl(unsafety,
441 ref items) = item.node {
442 let mut result = String::new();
444 result.push_str(&*format_visibility(&item.vis));
445 result.push_str(format_unsafety(unsafety));
446 result.push_str("impl");
448 let lo = context.codemap.span_after(item.span, "impl");
449 let hi = match *trait_ref {
450 Some(ref tr) => tr.path.span.lo,
451 None => self_ty.span.lo,
453 let generics_str = try_opt!(rewrite_generics(context,
456 context.config.max_width,
457 offset + result.len(),
459 result.push_str(&generics_str);
461 // FIXME might need to linebreak in the impl header, here would be a
464 if polarity == ast::ImplPolarity::Negative {
465 result.push_str("!");
467 if let Some(ref trait_ref) = *trait_ref {
468 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
469 let indent = offset + result.len();
470 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
471 result.push_str(" for ");
474 let mut used_space = result.len();
475 if generics.where_clause.predicates.is_empty() {
476 // If there is no where clause adapt budget for type formatting to take space and curly
477 // brace into account.
478 match context.config.item_brace_style {
479 BraceStyle::AlwaysNextLine => {}
480 BraceStyle::PreferSameLine => used_space += 2,
481 BraceStyle::SameLineWhere => used_space += 2,
485 let budget = try_opt!(context.config.max_width.checked_sub(used_space));
486 let indent = offset + result.len();
487 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
489 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
490 let where_clause_str = try_opt!(rewrite_where_clause(context,
491 &generics.where_clause,
493 context.config.item_brace_style,
494 context.block_indent,
496 context.config.where_density,
501 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
502 result.push_str(&where_clause_str);
503 if where_clause_str.contains('\n') {
504 let white_space = offset.to_string(context.config);
505 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
507 result.push_str(" {}");
512 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
514 let width = context.block_indent.width() + context.config.tab_spaces - 1;
515 let where_indent = Indent::new(0, width);
516 result.push_str(&where_indent.to_string(context.config));
518 result.push_str(&where_clause_str);
520 match context.config.item_brace_style {
521 BraceStyle::AlwaysNextLine => result.push('\n'),
522 BraceStyle::PreferSameLine => result.push(' '),
523 BraceStyle::SameLineWhere => {
524 if !where_clause_str.is_empty() {
526 result.push_str(&offset.to_string(context.config));
535 let snippet = context.snippet(item.span);
536 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
538 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
539 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
540 visitor.block_indent = context.block_indent.block_indent(context.config);
541 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
544 visitor.visit_impl_item(&item);
547 visitor.format_missing(item.span.hi - BytePos(1));
549 let inner_indent_str = visitor.block_indent.to_string(context.config);
550 let outer_indent_str = context.block_indent.to_string(context.config);
553 result.push_str(&inner_indent_str);
554 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
556 result.push_str(&outer_indent_str);
559 if result.chars().last().unwrap() == '{' {
570 fn is_impl_single_line(context: &RewriteContext,
571 items: &Vec<ImplItem>,
573 where_clause_str: &str,
576 let snippet = context.snippet(item.span);
577 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
579 Some(context.config.impl_empty_single_line && items.is_empty() &&
580 result.len() + where_clause_str.len() <= context.config.max_width &&
581 !contains_comment(&snippet[open_pos..]))
584 pub fn format_struct(context: &RewriteContext,
587 vis: &ast::Visibility,
588 struct_def: &ast::VariantData,
589 generics: Option<&ast::Generics>,
592 one_line_width: Option<usize>)
595 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
596 ast::VariantData::Tuple(ref fields, _) => {
597 format_tuple_struct(context,
606 ast::VariantData::Struct(ref fields, _) => {
607 format_struct_struct(context,
620 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
621 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
623 let mut result = String::new();
624 let header = format!("{}{}trait {}",
625 format_visibility(&item.vis),
626 format_unsafety(unsafety),
629 result.push_str(&header);
631 let body_lo = context.codemap.span_after(item.span, "{");
633 let generics_str = try_opt!(rewrite_generics(context,
636 context.config.max_width,
637 offset + result.len(),
638 mk_sp(item.span.lo, body_lo)));
639 result.push_str(&generics_str);
641 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
644 context.config.max_width));
645 // If the trait, generics, and trait bound cannot fit on the same line,
646 // put the trait bounds on an indented new line
647 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
648 context.config.ideal_width {
650 let width = context.block_indent.width() + context.config.tab_spaces;
651 let trait_indent = Indent::new(0, width);
652 result.push_str(&trait_indent.to_string(context.config));
654 result.push_str(&trait_bound_str);
656 let has_body = !trait_items.is_empty();
659 if (context.config.where_density == Density::Compressed &&
660 (!result.contains('\n') ||
661 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
662 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
663 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
664 !result.contains('\n')) {
670 let where_budget = try_opt!(context.config
672 .checked_sub(last_line_width(&result)));
673 let where_clause_str = try_opt!(rewrite_where_clause(context,
674 &generics.where_clause,
676 context.config.item_brace_style,
677 context.block_indent,
683 // If the where clause cannot fit on the same line,
684 // put the where clause on a new line
685 if !where_clause_str.contains('\n') &&
686 last_line_width(&result) + where_clause_str.len() + offset.width() >
687 context.config.ideal_width {
689 let width = context.block_indent.width() + context.config.tab_spaces - 1;
690 let where_indent = Indent::new(0, width);
691 result.push_str(&where_indent.to_string(context.config));
693 result.push_str(&where_clause_str);
695 match context.config.item_brace_style {
696 BraceStyle::AlwaysNextLine => {
698 result.push_str(&offset.to_string(context.config));
700 BraceStyle::PreferSameLine => result.push(' '),
701 BraceStyle::SameLineWhere => {
702 if !where_clause_str.is_empty() &&
703 (trait_items.len() > 0 || result.contains('\n')) {
705 result.push_str(&offset.to_string(context.config));
713 let snippet = context.snippet(item.span);
714 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
716 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
717 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
718 visitor.block_indent = context.block_indent.block_indent(context.config);
719 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
721 for item in trait_items {
722 visitor.visit_trait_item(&item);
725 visitor.format_missing(item.span.hi - BytePos(1));
727 let inner_indent_str = visitor.block_indent.to_string(context.config);
728 let outer_indent_str = context.block_indent.to_string(context.config);
731 result.push_str(&inner_indent_str);
732 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
734 result.push_str(&outer_indent_str);
735 } else if result.contains('\n') {
746 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
747 format!("{};", format_header(item_name, ident, vis))
750 fn format_struct_struct(context: &RewriteContext,
753 vis: &ast::Visibility,
754 fields: &[ast::StructField],
755 generics: Option<&ast::Generics>,
758 one_line_width: Option<usize>)
760 let mut result = String::with_capacity(1024);
762 let header_str = format_header(item_name, ident, vis);
763 result.push_str(&header_str);
765 let body_lo = context.codemap.span_after(span, "{");
767 let generics_str = match generics {
769 try_opt!(format_generics(context,
773 context.config.item_brace_style,
776 offset + header_str.len(),
777 mk_sp(span.lo, body_lo)))
780 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
781 format!("\n{}{{", context.block_indent.to_string(context.config))
787 result.push_str(&generics_str);
789 // FIXME(#919): properly format empty structs and their comments.
790 if fields.is_empty() {
791 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
795 let item_indent = offset.block_indent(context.config);
797 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
799 let items = itemize_list(context.codemap,
803 // Include attributes and doc comments, if present
804 if !field.attrs.is_empty() {
805 field.attrs[0].span.lo
810 |field| field.ty.span.hi,
811 |field| field.rewrite(context, item_budget, item_indent),
812 context.codemap.span_after(span, "{"),
814 .collect::<Vec<_>>();
816 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
818 let tactic = match one_line_width {
819 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
820 None => DefinitiveListTactic::Vertical,
823 let fmt = ListFormatting {
826 trailing_separator: context.config.struct_trailing_comma,
829 ends_with_newline: true,
830 config: context.config,
832 let items_str = try_opt!(write_list(&items, &fmt));
833 if one_line_width.is_some() && !items_str.contains('\n') {
834 Some(format!("{} {} }}", result, items_str))
836 Some(format!("{}\n{}{}\n{}}}",
838 offset.block_indent(context.config).to_string(context.config),
840 offset.to_string(context.config)))
844 fn format_tuple_struct(context: &RewriteContext,
847 vis: &ast::Visibility,
848 fields: &[ast::StructField],
849 generics: Option<&ast::Generics>,
853 let mut result = String::with_capacity(1024);
855 let header_str = format_header(item_name, ident, vis);
856 result.push_str(&header_str);
858 // FIXME(#919): don't lose comments on empty tuple structs.
859 let body_lo = if fields.is_empty() {
865 let where_clause_str = match generics {
866 Some(ref generics) => {
867 let generics_str = try_opt!(rewrite_generics(context,
870 context.config.max_width,
871 offset + header_str.len(),
872 mk_sp(span.lo, body_lo)));
873 result.push_str(&generics_str);
875 let where_budget = try_opt!(context.config
877 .checked_sub(last_line_width(&result)));
878 try_opt!(rewrite_where_clause(context,
879 &generics.where_clause,
881 context.config.item_brace_style,
882 context.block_indent,
889 None => "".to_owned(),
893 let item_indent = context.block_indent + result.len();
895 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
897 let items = itemize_list(context.codemap,
901 // Include attributes and doc comments, if present
902 if !field.attrs.is_empty() {
903 field.attrs[0].span.lo
908 |field| field.ty.span.hi,
909 |field| field.rewrite(context, item_budget, item_indent),
910 context.codemap.span_after(span, "("),
912 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
913 result.push_str(&body);
916 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
917 (result.contains('\n') ||
918 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
919 context.config.max_width) {
920 // We need to put the where clause on a new line, but we didn'to_string
921 // know that earlier, so the where clause will not be indented properly.
923 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
924 .to_string(context.config));
926 result.push_str(&where_clause_str);
931 pub fn rewrite_type_alias(context: &RewriteContext,
935 generics: &ast::Generics,
936 vis: &ast::Visibility,
939 let mut result = String::new();
941 result.push_str(&format_visibility(&vis));
942 result.push_str("type ");
943 result.push_str(&ident.to_string());
945 let generics_indent = indent + result.len();
946 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
947 let generics_width = context.config.max_width - " =".len();
948 let generics_str = try_opt!(rewrite_generics(context,
955 result.push_str(&generics_str);
957 let where_budget = try_opt!(context.config
959 .checked_sub(last_line_width(&result)));
960 let where_clause_str = try_opt!(rewrite_where_clause(context,
961 &generics.where_clause,
963 context.config.item_brace_style,
966 context.config.where_density,
970 result.push_str(&where_clause_str);
971 result.push_str(" = ");
973 let line_width = last_line_width(&result);
974 // This checked_sub may fail as the extra space after '=' is not taken into account
975 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
976 let budget = context.config
978 .checked_sub(indent.width() + line_width + ";".len())
980 let type_indent = indent + line_width;
981 // Try to fit the type on the same line
982 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
984 // The line was too short, try to put the type on the next line
986 // Remove the space after '='
988 let type_indent = indent.block_indent(context.config);
990 result.push_str(&type_indent.to_string(context.config));
991 let budget = try_opt!(context.config
993 .checked_sub(type_indent.width() + ";".len()));
994 ty.rewrite(context, budget, type_indent)
996 result.push_str(&ty_str);
997 result.push_str(";");
1001 impl Rewrite for ast::StructField {
1002 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1003 if contains_skip(&self.attrs) {
1004 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1005 return wrap_str(span, context.config.max_width, width, offset);
1008 let name = self.ident;
1009 let vis = format_visibility(&self.vis);
1010 let mut attr_str = try_opt!(self.attrs
1011 .rewrite(context, context.config.max_width - offset.width(), offset));
1012 if !attr_str.is_empty() {
1013 attr_str.push('\n');
1014 attr_str.push_str(&offset.to_string(context.config));
1017 let result = match name {
1018 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1019 None => format!("{}{}", attr_str, vis),
1022 let last_line_width = last_line_width(&result);
1023 let budget = try_opt!(width.checked_sub(last_line_width));
1024 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1025 Some(result + &rewrite)
1029 pub fn rewrite_static(prefix: &str,
1030 vis: &ast::Visibility,
1033 mutability: ast::Mutability,
1034 expr_opt: Option<&ptr::P<ast::Expr>>,
1035 context: &RewriteContext)
1037 let prefix = format!("{}{} {}{}: ",
1038 format_visibility(vis),
1040 format_mutability(mutability),
1043 let ty_str = try_opt!(ty.rewrite(context,
1044 context.config.max_width - context.block_indent.width() -
1046 context.block_indent));
1048 if let Some(ref expr) = expr_opt {
1049 let lhs = format!("{}{} =", prefix, ty_str);
1051 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1052 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1055 let lhs = format!("{}{};", prefix, ty_str);
1060 pub fn rewrite_associated_type(ident: ast::Ident,
1061 ty_opt: Option<&ptr::P<ast::Ty>>,
1062 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1063 context: &RewriteContext,
1066 let prefix = format!("type {}", ident);
1068 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1069 let bounds: &[_] = &ty_param_bounds;
1070 let bound_str = try_opt!(bounds.iter()
1071 .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1072 .intersperse(Some(" + ".to_string()))
1073 .collect::<Option<String>>());
1074 if bounds.len() > 0 {
1075 format!(": {}", bound_str)
1083 if let Some(ty) = ty_opt {
1084 let ty_str = try_opt!(ty.rewrite(context,
1085 context.config.max_width - context.block_indent.width() -
1088 context.block_indent));
1089 Some(format!("{} = {};", prefix, ty_str))
1091 Some(format!("{}{};", prefix, type_bounds_str))
1095 impl Rewrite for ast::FunctionRetTy {
1096 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1098 ast::FunctionRetTy::Default(_) => Some(String::new()),
1099 ast::FunctionRetTy::None(_) => {
1101 Some("-> !".to_owned())
1106 ast::FunctionRetTy::Ty(ref ty) => {
1107 let inner_width = try_opt!(width.checked_sub(3));
1108 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1114 impl Rewrite for ast::Arg {
1115 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1116 if is_named_arg(self) {
1117 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1119 if self.ty.node != ast::TyKind::Infer {
1120 result.push_str(": ");
1121 let max_width = try_opt!(width.checked_sub(result.len()));
1122 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1123 result.push_str(&ty_str);
1128 self.ty.rewrite(context, width, offset)
1133 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1135 context: &RewriteContext)
1137 match explicit_self.node {
1138 ast::SelfKind::Region(lt, m) => {
1139 let mut_str = format_mutability(m);
1143 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1144 Some(format!("&{} {}self", lifetime_str, mut_str))
1146 None => Some(format!("&{}self", mut_str)),
1149 ast::SelfKind::Explicit(ref ty, _) => {
1150 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1152 let mutability = explicit_self_mutability(&args[0]);
1153 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1155 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1157 ast::SelfKind::Value(_) => {
1158 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1160 let mutability = explicit_self_mutability(&args[0]);
1162 Some(format!("{}self", format_mutability(mutability)))
1167 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1168 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1169 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1170 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1177 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1178 if is_named_arg(arg) {
1185 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1187 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1188 _ => arg.ty.span.hi,
1192 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1193 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1194 ident.node != token::keywords::Invalid.ident()
1200 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1202 ast::FunctionRetTy::None(ref span) |
1203 ast::FunctionRetTy::Default(ref span) => span.clone(),
1204 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1208 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1209 // Note that ty.span is the span for ty.ident, not the whole item.
1210 let lo = ty.span.lo;
1211 if let Some(ref def) = ty.default {
1212 return mk_sp(lo, def.span.hi);
1214 if ty.bounds.is_empty() {
1217 let hi = match ty.bounds[ty.bounds.len() - 1] {
1218 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1219 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1224 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1226 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1227 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1228 ast::WherePredicate::EqPredicate(ref p) => p.span,
1232 // Return type is (result, force_new_line_for_brace)
1233 fn rewrite_fn_base(context: &RewriteContext,
1237 generics: &ast::Generics,
1238 unsafety: ast::Unsafety,
1239 constness: ast::Constness,
1240 defaultness: ast::Defaultness,
1242 vis: &ast::Visibility,
1244 newline_brace: bool,
1246 -> Option<(String, bool)> {
1247 let mut force_new_line_for_brace = false;
1248 // FIXME we'll lose any comments in between parts of the function decl, but
1249 // anyone who comments there probably deserves what they get.
1251 let where_clause = &generics.where_clause;
1253 let mut result = String::with_capacity(1024);
1254 // Vis unsafety abi.
1255 result.push_str(&*format_visibility(vis));
1257 if let ast::Defaultness::Default = defaultness {
1258 result.push_str("default ");
1261 if let ast::Constness::Const = constness {
1262 result.push_str("const ");
1265 result.push_str(::utils::format_unsafety(unsafety));
1267 if abi != abi::Abi::Rust {
1268 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1272 result.push_str("fn ");
1273 result.push_str(&ident.to_string());
1276 let generics_indent = indent + result.len();
1277 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1278 let generics_str = try_opt!(rewrite_generics(context,
1281 context.config.max_width,
1284 result.push_str(&generics_str);
1286 // Note that if the width and indent really matter, we'll re-layout the
1287 // return type later anyway.
1288 let ret_str = try_opt!(fd.output
1289 .rewrite(&context, context.config.max_width - indent.width(), indent));
1291 let multi_line_ret_str = ret_str.contains('\n');
1292 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1295 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1296 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1298 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1299 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1300 arg_indent = indent.block_indent(context.config);
1301 multi_line_budget = context.config.max_width - arg_indent.width();
1304 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1309 // Check if vertical layout was forced by compute_budget_for_args.
1310 if one_line_budget == 0 {
1311 if context.config.fn_args_paren_newline {
1313 result.push_str(&arg_indent.to_string(context.config));
1314 arg_indent = arg_indent + 1; // extra space for `(`
1317 result.push_str("(\n");
1318 result.push_str(&arg_indent.to_string(context.config));
1324 if multi_line_ret_str {
1325 one_line_budget = 0;
1328 // A conservative estimation, to goal is to be over all parens in generics
1329 let args_start = generics.ty_params
1331 .map_or(span.lo, |tp| end_typaram(tp));
1332 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1333 span_for_return(&fd.output).lo);
1334 let arg_str = try_opt!(rewrite_args(context,
1336 fd.get_self().as_ref(),
1344 let multi_line_arg_str = arg_str.contains('\n');
1346 let put_args_in_block = match context.config.fn_args_layout {
1347 FnArgLayoutStyle::Block => multi_line_arg_str,
1348 FnArgLayoutStyle::BlockAlways => true,
1350 } && fd.inputs.len() > 0;
1352 if put_args_in_block {
1353 arg_indent = indent.block_indent(context.config);
1355 result.push_str(&arg_indent.to_string(context.config));
1356 result.push_str(&arg_str);
1358 result.push_str(&indent.to_string(context.config));
1361 result.push_str(&arg_str);
1366 if !ret_str.is_empty() {
1367 let ret_should_indent = match context.config.fn_args_layout {
1368 // If our args are block layout then we surely must have space.
1369 FnArgLayoutStyle::Block if put_args_in_block => false,
1370 FnArgLayoutStyle::BlockAlways => false,
1372 // If we've already gone multi-line, or the return type would push over the max
1373 // width, then put the return type on a new line. With the +1 for the signature
1374 // length an additional space between the closing parenthesis of the argument and
1375 // the arrow '->' is considered.
1376 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1378 // If there is no where clause, take into account the space after the return type
1380 if where_clause.predicates.is_empty() {
1384 let overlong_sig = sig_length > context.config.max_width;
1386 result.contains("\n") || multi_line_ret_str || overlong_sig
1389 let ret_indent = if ret_should_indent {
1390 let indent = match context.config.fn_return_indent {
1391 ReturnIndent::WithWhereClause => indent + 4,
1392 // Aligning with non-existent args looks silly.
1393 _ if arg_str.is_empty() => {
1394 force_new_line_for_brace = true;
1397 // FIXME: we might want to check that using the arg indent
1398 // doesn't blow our budget, and if it does, then fallback to
1399 // the where clause indent.
1404 result.push_str(&indent.to_string(context.config));
1408 Indent::new(indent.width(), result.len())
1411 if multi_line_ret_str {
1412 // Now that we know the proper indent and width, we need to
1413 // re-layout the return type.
1414 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1415 let ret_str = try_opt!(fd.output.rewrite(context, budget, ret_indent));
1416 result.push_str(&ret_str);
1418 result.push_str(&ret_str);
1421 // Comment between return type and the end of the decl.
1422 let snippet_lo = fd.output.span().hi;
1423 if where_clause.predicates.is_empty() {
1424 let snippet_hi = span.hi;
1425 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1426 let snippet = snippet.trim();
1427 if !snippet.is_empty() {
1429 result.push_str(snippet);
1432 // FIXME it would be nice to catch comments between the return type
1433 // and the where clause, but we don't have a span for the where
1438 let should_compress_where = match context.config.where_density {
1439 Density::Compressed => !result.contains('\n') || put_args_in_block,
1440 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1442 } || (put_args_in_block && ret_str.is_empty());
1444 let where_density = if should_compress_where {
1451 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1452 let where_clause_str = try_opt!(rewrite_where_clause(context,
1455 context.config.fn_brace_style,
1463 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1464 !where_clause_str.contains('\n') {
1468 result.push_str(&where_clause_str);
1470 Some((result, force_new_line_for_brace))
1473 fn rewrite_args(context: &RewriteContext,
1475 explicit_self: Option<&ast::ExplicitSelf>,
1476 one_line_budget: usize,
1477 multi_line_budget: usize,
1483 let mut arg_item_strs = try_opt!(args.iter()
1484 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1485 .collect::<Option<Vec<_>>>());
1487 // Account for sugary self.
1488 // FIXME: the comment for the self argument is dropped. This is blocked
1489 // on rust issue #27522.
1491 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1492 .map_or(1, |self_str| {
1493 arg_item_strs[0] = self_str;
1497 // Comments between args.
1498 let mut arg_items = Vec::new();
1500 arg_items.push(ListItem::from_str(""));
1503 // FIXME(#21): if there are no args, there might still be a comment, but
1504 // without spans for the comment or parens, there is no chance of
1505 // getting it right. You also don't get to put a comment on self, unless
1507 if args.len() >= min_args || variadic {
1508 let comment_span_start = if min_args == 2 {
1509 let second_arg_start = if arg_has_pattern(&args[1]) {
1514 let reduced_span = mk_sp(span.lo, second_arg_start);
1516 context.codemap.span_after_last(reduced_span, ",")
1521 enum ArgumentKind<'a> {
1522 Regular(&'a ast::Arg),
1526 let variadic_arg = if variadic {
1527 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1528 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1529 Some(ArgumentKind::Variadic(variadic_start))
1534 let more_items = itemize_list(context.codemap,
1535 args[min_args - 1..]
1537 .map(ArgumentKind::Regular)
1538 .chain(variadic_arg),
1542 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1543 ArgumentKind::Variadic(start) => start,
1548 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1549 ArgumentKind::Variadic(start) => start + BytePos(3),
1554 ArgumentKind::Regular(..) => None,
1555 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1561 arg_items.extend(more_items);
1564 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1565 item.item = Some(arg);
1568 let indent = match context.config.fn_arg_indent {
1569 BlockIndentStyle::Inherit => indent,
1570 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1571 BlockIndentStyle::Visual => arg_indent,
1574 let tactic = definitive_tactic(&arg_items,
1575 context.config.fn_args_density.to_list_tactic(),
1577 let budget = match tactic {
1578 DefinitiveListTactic::Horizontal => one_line_budget,
1579 _ => multi_line_budget,
1582 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1584 let end_with_newline = match context.config.fn_args_layout {
1585 FnArgLayoutStyle::Block |
1586 FnArgLayoutStyle::BlockAlways => true,
1590 let fmt = ListFormatting {
1593 trailing_separator: SeparatorTactic::Never,
1596 ends_with_newline: end_with_newline,
1597 config: context.config,
1600 write_list(&arg_items, &fmt)
1603 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1604 if let ast::PatKind::Ident(_,
1606 node: ast::Ident { name: ast::Name(0u32), .. },
1616 fn compute_budgets_for_args(context: &RewriteContext,
1620 newline_brace: bool)
1621 -> Option<((usize, usize, Indent))> {
1622 // Try keeping everything on the same line.
1623 if !result.contains("\n") {
1624 // 3 = `() `, space is before ret_string.
1625 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1629 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1631 if one_line_budget > 0 {
1633 let multi_line_budget =
1634 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1636 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1640 // Didn't work. we must force vertical layout and put args on a newline.
1641 let new_indent = indent.block_indent(context.config);
1642 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1643 let max_space = context.config.max_width;
1644 if used_space <= max_space {
1645 Some((0, max_space - used_space, new_indent))
1647 // Whoops! bankrupt.
1652 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1653 match config.fn_brace_style {
1654 BraceStyle::AlwaysNextLine => true,
1655 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1660 fn rewrite_generics(context: &RewriteContext,
1661 generics: &ast::Generics,
1664 generics_offset: Indent,
1667 // FIXME: convert bounds to where clauses where they get too big or if
1668 // there is a where clause at all.
1669 let lifetimes: &[_] = &generics.lifetimes;
1670 let tys: &[_] = &generics.ty_params;
1671 if lifetimes.is_empty() && tys.is_empty() {
1672 return Some(String::new());
1675 let offset = match context.config.generics_indent {
1676 BlockIndentStyle::Inherit => offset,
1677 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1679 BlockIndentStyle::Visual => generics_offset + 1,
1682 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1683 // FIXME: might need to insert a newline if the generics are really long.
1685 // Strings for the generics.
1686 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1687 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1689 // Extract comments between generics.
1690 let lt_spans = lifetimes.iter().map(|l| {
1691 let hi = if l.bounds.is_empty() {
1694 l.bounds[l.bounds.len() - 1].span.hi
1696 mk_sp(l.lifetime.span.lo, hi)
1698 let ty_spans = tys.iter().map(span_for_ty_param);
1700 let items = itemize_list(context.codemap,
1701 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1705 // FIXME: don't clone
1706 |&(_, ref str)| str.clone(),
1707 context.codemap.span_after(span, "<"),
1709 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1711 Some(format!("<{}>", list_str))
1714 fn rewrite_trait_bounds(context: &RewriteContext,
1715 type_param_bounds: &ast::TyParamBounds,
1719 let bounds: &[_] = &type_param_bounds;
1721 if bounds.is_empty() {
1722 return Some(String::new());
1725 let bound_str = try_opt!(bounds.iter()
1726 .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1727 .intersperse(Some(" + ".to_string()))
1728 .collect::<Option<String>>());
1730 let mut result = String::new();
1731 result.push_str(": ");
1732 result.push_str(&bound_str);
1736 fn rewrite_where_clause(context: &RewriteContext,
1737 where_clause: &ast::WhereClause,
1739 brace_style: BraceStyle,
1744 allow_trailing_comma: bool,
1745 span_end: Option<BytePos>)
1747 if where_clause.predicates.is_empty() {
1748 return Some(String::new());
1751 let extra_indent = match context.config.where_indent {
1752 BlockIndentStyle::Inherit => Indent::empty(),
1753 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1756 let offset = match context.config.where_pred_indent {
1757 BlockIndentStyle::Inherit => indent + extra_indent,
1758 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1759 // 6 = "where ".len()
1760 BlockIndentStyle::Visual => indent + extra_indent + 6,
1762 // FIXME: if where_pred_indent != Visual, then the budgets below might
1763 // be out by a char or two.
1765 let budget = context.config.max_width - offset.width();
1766 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1767 // If we don't have the start of the next span, then use the end of the
1768 // predicates, but that means we miss comments.
1769 let len = where_clause.predicates.len();
1770 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1771 let span_end = span_end.unwrap_or(end_of_preds);
1772 let items = itemize_list(context.codemap,
1773 where_clause.predicates.iter(),
1775 |pred| span_for_where_pred(pred).lo,
1776 |pred| span_for_where_pred(pred).hi,
1777 |pred| pred.rewrite(&context, budget, offset),
1780 let item_vec = items.collect::<Vec<_>>();
1781 // FIXME: we don't need to collect here if the where_layout isn't
1782 // HorizontalVertical.
1783 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1784 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1786 let fmt = ListFormatting {
1789 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1792 ends_with_newline: true,
1793 config: context.config,
1795 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1797 let end_length = if terminator == "{" {
1798 // If the brace is on the next line we don't need to count it otherwise it needs two
1801 BraceStyle::AlwaysNextLine => 0,
1802 BraceStyle::PreferSameLine => 2,
1803 BraceStyle::SameLineWhere => 0,
1805 } else if terminator == "=" {
1810 if density == Density::Tall || preds_str.contains('\n') ||
1811 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1812 Some(format!("\n{}where {}",
1813 (indent + extra_indent).to_string(context.config),
1816 Some(format!(" where {}", preds_str))
1820 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1821 format!("{}{}{}", format_visibility(vis), item_name, ident)
1824 fn format_generics(context: &RewriteContext,
1825 generics: &ast::Generics,
1828 brace_style: BraceStyle,
1829 force_same_line_brace: bool,
1831 generics_offset: Indent,
1834 let mut result = try_opt!(rewrite_generics(context,
1837 context.config.max_width,
1841 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1842 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1843 let where_clause_str = try_opt!(rewrite_where_clause(context,
1844 &generics.where_clause,
1847 context.block_indent,
1853 result.push_str(&where_clause_str);
1854 if !force_same_line_brace &&
1855 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1857 result.push_str(&context.block_indent.to_string(context.config));
1861 result.push_str(opener);
1863 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1865 result.push_str(&context.block_indent.to_string(context.config));
1869 result.push_str(opener);