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, format_unsafety, trim_newlines, stmt_expr, semicolon_for_expr};
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, type_annotation_separator};
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 = type_annotation_separator(context.config);
49 let indent = offset + last_line_width(&result) + separator.len();
51 let budget = try_opt!(width.checked_sub(indent.width() + 1));
52 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
54 infix.push_str(separator);
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 self.buffer.push_str("{");
89 if !fm.items.is_empty() || contains_comment(&snippet[brace_pos..]) {
90 // FIXME: this skips comments between the extern keyword and the opening
92 self.last_pos = span.lo + BytePos(brace_pos as u32 + 1);
93 self.block_indent = self.block_indent.block_indent(self.config);
95 if fm.items.is_empty() {
96 self.format_missing_no_indent(span.hi - BytePos(1));
97 self.block_indent = self.block_indent.block_unindent(self.config);
99 self.buffer.push_str(&self.block_indent.to_string(self.config));
101 for item in &fm.items {
102 self.format_foreign_item(&*item);
105 self.block_indent = self.block_indent.block_unindent(self.config);
106 self.format_missing_with_indent(span.hi - BytePos(1));
110 self.buffer.push_str("}");
111 self.last_pos = span.hi;
114 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
115 self.format_missing_with_indent(item.span.lo);
116 // Drop semicolon or it will be interpreted as comment.
117 // FIXME: this may be a faulty span from libsyntax.
118 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
121 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
122 let indent = self.block_indent;
123 let rewrite = rewrite_fn_base(&self.get_context(),
128 ast::Unsafety::Normal,
129 ast::Constness::NotConst,
130 ast::Defaultness::Final,
131 // These are not actually rust functions,
132 // but we format them as such.
140 Some((new_fn, _)) => {
141 self.buffer.push_str(&new_fn);
142 self.buffer.push_str(";");
144 None => self.format_missing(item.span.hi),
147 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
148 // FIXME(#21): we're dropping potential comments in between the
149 // function keywords here.
150 let vis = format_visibility(&item.vis);
151 let mut_str = if is_mutable { "mut " } else { "" };
152 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
153 let offset = self.block_indent + prefix.len();
155 let width = self.config.max_width - offset.width() - 1;
156 let rewrite = ty.rewrite(&self.get_context(), width, offset);
160 self.buffer.push_str(&prefix);
161 self.buffer.push_str(&result);
162 self.buffer.push_str(";");
164 None => self.format_missing(item.span.hi),
169 self.last_pos = item.span.hi;
172 pub fn rewrite_fn(&mut self,
176 generics: &ast::Generics,
177 unsafety: ast::Unsafety,
178 constness: ast::Constness,
179 defaultness: ast::Defaultness,
181 vis: &ast::Visibility,
185 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
186 let context = self.get_context();
188 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
189 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
190 !context.config.fn_empty_single_line;
192 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
206 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
207 newline_brace = false;
208 } else if force_newline_brace {
209 newline_brace = true;
212 // Prepare for the function body by possibly adding a newline and
214 // FIXME we'll miss anything between the end of the signature and the
215 // start of the body, but we need more spans from the compiler to solve
219 result.push_str(&indent.to_string(self.config));
224 self.single_line_fn(&result, block).or_else(|| Some(result))
227 pub fn rewrite_required_fn(&mut self,
230 sig: &ast::MethodSig,
233 // Drop semicolon or it will be interpreted as comment.
234 let span = mk_sp(span.lo, span.hi - BytePos(1));
235 let context = self.get_context();
237 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
244 ast::Defaultness::Final,
246 &ast::Visibility::Inherited,
251 // Re-attach semicolon
257 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
258 if fn_str.contains('\n') {
262 let codemap = self.get_context().codemap;
264 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
265 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
266 return Some(format!("{}{{}}", fn_str));
269 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
271 if let Some(ref stmt) = block.stmts.first() {
272 match stmt_expr(stmt) {
274 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
276 e.rewrite(&self.get_context(),
277 self.config.max_width - self.block_indent.width(),
280 .or_else(|| Some(self.snippet(e.span)))
283 stmt.rewrite(&self.get_context(),
284 self.config.max_width - self.block_indent.width(),
293 if let Some(res) = rewrite {
294 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
295 if !res.contains('\n') && width <= self.config.max_width {
296 return Some(format!("{}{{ {} }}", fn_str, res));
304 pub fn visit_enum(&mut self,
306 vis: &ast::Visibility,
307 enum_def: &ast::EnumDef,
308 generics: &ast::Generics,
310 self.buffer.push_str(&format_header("enum ", ident, vis));
312 let enum_snippet = self.snippet(span);
313 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
314 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
315 let generics_str = format_generics(&self.get_context(),
319 self.config.item_brace_style,
320 enum_def.variants.is_empty(),
322 self.block_indent.block_indent(self.config),
323 mk_sp(span.lo, body_start))
325 self.buffer.push_str(&generics_str);
327 self.last_pos = body_start;
329 self.block_indent = self.block_indent.block_indent(self.config);
330 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
332 Some(ref body_str) => self.buffer.push_str(body_str),
334 if contains_comment(&enum_snippet[brace_pos..]) {
335 self.format_missing_no_indent(span.hi - BytePos(1))
337 self.format_missing(span.hi - BytePos(1))
341 self.block_indent = self.block_indent.block_unindent(self.config);
343 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
344 self.buffer.push_str(&self.block_indent.to_string(self.config));
346 self.buffer.push_str("}");
347 self.last_pos = span.hi;
350 // Format the body of an enum definition
351 fn format_variant_list(&self,
352 enum_def: &ast::EnumDef,
356 if enum_def.variants.is_empty() {
359 let mut result = String::with_capacity(1024);
361 let indentation = self.block_indent.to_string(self.config);
362 result.push_str(&indentation);
364 let items = itemize_list(self.codemap,
365 enum_def.variants.iter(),
367 |f| if !f.node.attrs.is_empty() {
368 f.node.attrs[0].span.lo
373 |f| self.format_variant(f),
377 let budget = self.config.max_width - self.block_indent.width() - 2;
378 let fmt = ListFormatting {
379 tactic: DefinitiveListTactic::Vertical,
381 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
382 indent: self.block_indent,
384 ends_with_newline: true,
388 let list = try_opt!(write_list(items, &fmt));
389 result.push_str(&list);
394 // Variant of an enum.
395 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
396 if contains_skip(&field.node.attrs) {
397 let lo = field.node.attrs[0].span.lo;
398 let span = mk_sp(lo, field.span.hi);
399 return Some(self.snippet(span));
402 let indent = self.block_indent;
403 let mut result = try_opt!(field.node
405 .rewrite(&self.get_context(),
406 self.config.max_width - indent.width(),
408 if !result.is_empty() {
410 result.push_str(&indent.to_string(self.config));
413 let context = self.get_context();
414 let variant_body = match field.node.data {
415 ast::VariantData::Tuple(..) |
416 ast::VariantData::Struct(..) => {
417 // FIXME: Should limit the width, as we have a trailing comma
418 format_struct(&context,
421 &ast::Visibility::Inherited,
426 Some(self.config.struct_variant_width))
428 ast::VariantData::Unit(..) => {
429 let tag = if let Some(ref expr) = field.node.disr_expr {
430 format!("{} = {}", field.node.name, self.snippet(expr.span))
432 field.node.name.to_string()
436 self.config.max_width,
437 self.config.max_width - indent.width(),
442 if let Some(variant_str) = variant_body {
443 result.push_str(&variant_str);
451 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
452 if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
453 let mut result = String::new();
455 // First try to format the ref and type without a split at the 'for'.
456 let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
458 // If there is a line break present in the first result format it again
459 // with a split at the 'for'. Skip this if there is no trait ref and
460 // therefore no 'for'.
461 if let Some(_) = *trait_ref {
462 if ref_and_type.contains('\n') {
463 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
466 result.push_str(&ref_and_type);
468 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
469 let where_clause_str = try_opt!(rewrite_where_clause(context,
470 &generics.where_clause,
472 context.config.item_brace_style,
473 context.block_indent,
475 context.config.where_density,
480 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
481 result.push_str(&where_clause_str);
482 if where_clause_str.contains('\n') {
483 let white_space = offset.to_string(context.config);
484 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
486 result.push_str(" {}");
491 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
493 let width = context.block_indent.width() + context.config.tab_spaces - 1;
494 let where_indent = Indent::new(0, width);
495 result.push_str(&where_indent.to_string(context.config));
497 result.push_str(&where_clause_str);
499 match context.config.item_brace_style {
500 BraceStyle::AlwaysNextLine => {
502 result.push_str(&offset.to_string(context.config));
504 BraceStyle::PreferSameLine => result.push(' '),
505 BraceStyle::SameLineWhere => {
506 if !where_clause_str.is_empty() {
508 result.push_str(&offset.to_string(context.config));
517 let snippet = context.snippet(item.span);
518 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
520 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
521 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
522 visitor.block_indent = context.block_indent.block_indent(context.config);
523 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
526 visitor.visit_impl_item(item);
529 visitor.format_missing(item.span.hi - BytePos(1));
531 let inner_indent_str = visitor.block_indent.to_string(context.config);
532 let outer_indent_str = context.block_indent.to_string(context.config);
535 result.push_str(&inner_indent_str);
536 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
538 result.push_str(&outer_indent_str);
541 if result.chars().last().unwrap() == '{' {
552 fn is_impl_single_line(context: &RewriteContext,
555 where_clause_str: &str,
558 let snippet = context.snippet(item.span);
559 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
561 Some(context.config.impl_empty_single_line && items.is_empty() &&
562 result.len() + where_clause_str.len() <= context.config.max_width &&
563 !contains_comment(&snippet[open_pos..]))
566 fn format_impl_ref_and_type(context: &RewriteContext,
571 if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
573 let mut result = String::new();
575 result.push_str(&*format_visibility(&item.vis));
576 result.push_str(format_unsafety(unsafety));
577 result.push_str("impl");
579 let lo = context.codemap.span_after(item.span, "impl");
580 let hi = match *trait_ref {
581 Some(ref tr) => tr.path.span.lo,
582 None => self_ty.span.lo,
584 let generics_str = try_opt!(rewrite_generics(context,
587 context.config.max_width,
588 offset + result.len(),
590 result.push_str(&generics_str);
593 if polarity == ast::ImplPolarity::Negative {
596 if let Some(ref trait_ref) = *trait_ref {
597 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
598 let indent = offset + result.len();
599 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
604 // Add indentation of one additional tab.
605 let width = context.block_indent.width() + context.config.tab_spaces;
606 let for_indent = Indent::new(0, width);
607 result.push_str(&for_indent.to_string(context.config));
609 result.push_str("for ");
611 result.push_str(" for ");
615 let mut used_space = last_line_width(&result);
616 if generics.where_clause.predicates.is_empty() {
617 // If there is no where clause adapt budget for type formatting to take space and curly
618 // brace into account.
619 match context.config.item_brace_style {
620 BraceStyle::AlwaysNextLine => {}
621 BraceStyle::PreferSameLine => used_space += 2,
622 BraceStyle::SameLineWhere => used_space += 2,
626 let budget = try_opt!(context.config.max_width.checked_sub(used_space));
627 let indent = offset + result.len();
628 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
636 pub fn format_struct(context: &RewriteContext,
639 vis: &ast::Visibility,
640 struct_def: &ast::VariantData,
641 generics: Option<&ast::Generics>,
644 one_line_width: Option<usize>)
647 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
648 ast::VariantData::Tuple(ref fields, _) => {
649 format_tuple_struct(context,
658 ast::VariantData::Struct(ref fields, _) => {
659 format_struct_struct(context,
672 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
673 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
675 let mut result = String::new();
676 let header = format!("{}{}trait {}",
677 format_visibility(&item.vis),
678 format_unsafety(unsafety),
681 result.push_str(&header);
683 let body_lo = context.codemap.span_after(item.span, "{");
685 let generics_str = try_opt!(rewrite_generics(context,
688 context.config.max_width,
689 offset + result.len(),
690 mk_sp(item.span.lo, body_lo)));
691 result.push_str(&generics_str);
693 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
696 context.config.max_width));
697 // If the trait, generics, and trait bound cannot fit on the same line,
698 // put the trait bounds on an indented new line
699 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
700 context.config.ideal_width {
702 let width = context.block_indent.width() + context.config.tab_spaces;
703 let trait_indent = Indent::new(0, width);
704 result.push_str(&trait_indent.to_string(context.config));
706 result.push_str(&trait_bound_str);
708 let has_body = !trait_items.is_empty();
711 if (context.config.where_density == Density::Compressed &&
712 (!result.contains('\n') ||
713 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
714 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
715 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
716 !result.contains('\n')) {
722 let where_budget = try_opt!(context.config
724 .checked_sub(last_line_width(&result)));
725 let where_clause_str = try_opt!(rewrite_where_clause(context,
726 &generics.where_clause,
728 context.config.item_brace_style,
729 context.block_indent,
735 // If the where clause cannot fit on the same line,
736 // put the where clause on a new line
737 if !where_clause_str.contains('\n') &&
738 last_line_width(&result) + where_clause_str.len() + offset.width() >
739 context.config.ideal_width {
741 let width = context.block_indent.width() + context.config.tab_spaces - 1;
742 let where_indent = Indent::new(0, width);
743 result.push_str(&where_indent.to_string(context.config));
745 result.push_str(&where_clause_str);
747 match context.config.item_brace_style {
748 BraceStyle::AlwaysNextLine => {
750 result.push_str(&offset.to_string(context.config));
752 BraceStyle::PreferSameLine => result.push(' '),
753 BraceStyle::SameLineWhere => {
754 if !where_clause_str.is_empty() &&
755 (!trait_items.is_empty() || result.contains('\n')) {
757 result.push_str(&offset.to_string(context.config));
765 let snippet = context.snippet(item.span);
766 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
768 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
769 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
770 visitor.block_indent = context.block_indent.block_indent(context.config);
771 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
773 for item in trait_items {
774 visitor.visit_trait_item(item);
777 visitor.format_missing(item.span.hi - BytePos(1));
779 let inner_indent_str = visitor.block_indent.to_string(context.config);
780 let outer_indent_str = context.block_indent.to_string(context.config);
783 result.push_str(&inner_indent_str);
784 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
786 result.push_str(&outer_indent_str);
787 } else if result.contains('\n') {
798 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
799 format!("{};", format_header(item_name, ident, vis))
802 fn format_struct_struct(context: &RewriteContext,
805 vis: &ast::Visibility,
806 fields: &[ast::StructField],
807 generics: Option<&ast::Generics>,
810 one_line_width: Option<usize>)
812 let mut result = String::with_capacity(1024);
814 let header_str = format_header(item_name, ident, vis);
815 result.push_str(&header_str);
817 let body_lo = context.codemap.span_after(span, "{");
819 let generics_str = match generics {
821 try_opt!(format_generics(context,
825 context.config.item_brace_style,
828 offset + header_str.len(),
829 mk_sp(span.lo, body_lo)))
832 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
833 format!("\n{}{{", context.block_indent.to_string(context.config))
839 result.push_str(&generics_str);
841 // FIXME(#919): properly format empty structs and their comments.
842 if fields.is_empty() {
843 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
847 let item_indent = offset.block_indent(context.config);
849 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
851 let items = itemize_list(context.codemap,
855 // Include attributes and doc comments, if present
856 if !field.attrs.is_empty() {
857 field.attrs[0].span.lo
862 |field| field.ty.span.hi,
863 |field| field.rewrite(context, item_budget, item_indent),
864 context.codemap.span_after(span, "{"),
866 .collect::<Vec<_>>();
868 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
870 let tactic = match one_line_width {
871 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
872 None => DefinitiveListTactic::Vertical,
875 let fmt = ListFormatting {
878 trailing_separator: context.config.struct_trailing_comma,
881 ends_with_newline: true,
882 config: context.config,
884 let items_str = try_opt!(write_list(&items, &fmt));
885 if one_line_width.is_some() && !items_str.contains('\n') {
886 Some(format!("{} {} }}", result, items_str))
888 Some(format!("{}\n{}{}\n{}}}",
890 offset.block_indent(context.config).to_string(context.config),
892 offset.to_string(context.config)))
896 fn format_tuple_struct(context: &RewriteContext,
899 vis: &ast::Visibility,
900 fields: &[ast::StructField],
901 generics: Option<&ast::Generics>,
905 let mut result = String::with_capacity(1024);
907 let header_str = format_header(item_name, ident, vis);
908 result.push_str(&header_str);
910 // FIXME(#919): don't lose comments on empty tuple structs.
911 let body_lo = if fields.is_empty() {
917 let where_clause_str = match generics {
919 let generics_str = try_opt!(rewrite_generics(context,
922 context.config.max_width,
923 offset + header_str.len(),
924 mk_sp(span.lo, body_lo)));
925 result.push_str(&generics_str);
927 let where_budget = try_opt!(context.config
929 .checked_sub(last_line_width(&result)));
930 try_opt!(rewrite_where_clause(context,
931 &generics.where_clause,
933 context.config.item_brace_style,
934 context.block_indent,
941 None => "".to_owned(),
945 let item_indent = context.block_indent + result.len();
947 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
949 let items = itemize_list(context.codemap,
953 // Include attributes and doc comments, if present
954 if !field.attrs.is_empty() {
955 field.attrs[0].span.lo
960 |field| field.ty.span.hi,
961 |field| field.rewrite(context, item_budget, item_indent),
962 context.codemap.span_after(span, "("),
964 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
966 if context.config.spaces_within_parens && body.len() > 0 {
970 result.push_str(&body);
972 if context.config.spaces_within_parens && body.len() > 0 {
978 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
979 (result.contains('\n') ||
980 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
981 context.config.max_width) {
982 // We need to put the where clause on a new line, but we didn'to_string
983 // know that earlier, so the where clause will not be indented properly.
985 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
986 .to_string(context.config));
988 result.push_str(&where_clause_str);
993 pub fn rewrite_type_alias(context: &RewriteContext,
997 generics: &ast::Generics,
998 vis: &ast::Visibility,
1001 let mut result = String::new();
1003 result.push_str(&format_visibility(vis));
1004 result.push_str("type ");
1005 result.push_str(&ident.to_string());
1007 let generics_indent = indent + result.len();
1008 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1009 let generics_width = context.config.max_width - " =".len();
1010 let generics_str = try_opt!(rewrite_generics(context,
1017 result.push_str(&generics_str);
1019 let where_budget = try_opt!(context.config
1021 .checked_sub(last_line_width(&result)));
1022 let where_clause_str = try_opt!(rewrite_where_clause(context,
1023 &generics.where_clause,
1025 context.config.item_brace_style,
1028 context.config.where_density,
1032 result.push_str(&where_clause_str);
1033 result.push_str(" = ");
1035 let line_width = last_line_width(&result);
1036 // This checked_sub may fail as the extra space after '=' is not taken into account
1037 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1038 let budget = context.config
1040 .checked_sub(indent.width() + line_width + ";".len())
1042 let type_indent = indent + line_width;
1043 // Try to fit the type on the same line
1044 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
1046 // The line was too short, try to put the type on the next line
1048 // Remove the space after '='
1050 let type_indent = indent.block_indent(context.config);
1052 result.push_str(&type_indent.to_string(context.config));
1053 let budget = try_opt!(context.config
1055 .checked_sub(type_indent.width() + ";".len()));
1056 ty.rewrite(context, budget, type_indent)
1058 result.push_str(&ty_str);
1059 result.push_str(";");
1063 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1064 (if config.space_before_type_annotation {
1069 if config.space_after_type_annotation_colon {
1076 impl Rewrite for ast::StructField {
1077 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1078 if contains_skip(&self.attrs) {
1079 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1080 return wrap_str(span, context.config.max_width, width, offset);
1083 let name = self.ident;
1084 let vis = format_visibility(&self.vis);
1085 let mut attr_str = try_opt!(self.attrs
1086 .rewrite(context, context.config.max_width - offset.width(), offset));
1087 if !attr_str.is_empty() {
1088 attr_str.push('\n');
1089 attr_str.push_str(&offset.to_string(context.config));
1092 let type_annotation_spacing = type_annotation_spacing(context.config);
1093 let result = match name {
1095 format!("{}{}{}{}:{}",
1099 type_annotation_spacing.0,
1100 type_annotation_spacing.1)
1102 None => format!("{}{}", attr_str, vis),
1105 let last_line_width = last_line_width(&result);
1106 let budget = try_opt!(width.checked_sub(last_line_width));
1107 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1108 Some(result + &rewrite)
1112 pub fn rewrite_static(prefix: &str,
1113 vis: &ast::Visibility,
1116 mutability: ast::Mutability,
1117 expr_opt: Option<&ptr::P<ast::Expr>>,
1118 context: &RewriteContext)
1120 let type_annotation_spacing = type_annotation_spacing(context.config);
1121 let prefix = format!("{}{} {}{}{}:{}",
1122 format_visibility(vis),
1124 format_mutability(mutability),
1126 type_annotation_spacing.0,
1127 type_annotation_spacing.1);
1129 let ty_str = try_opt!(ty.rewrite(context,
1130 context.config.max_width - context.block_indent.width() -
1132 context.block_indent));
1134 if let Some(expr) = expr_opt {
1135 let lhs = format!("{}{} =", prefix, ty_str);
1137 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1138 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1141 let lhs = format!("{}{};", prefix, ty_str);
1146 pub fn rewrite_associated_type(ident: ast::Ident,
1147 ty_opt: Option<&ptr::P<ast::Ty>>,
1148 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1149 context: &RewriteContext,
1152 let prefix = format!("type {}", ident);
1154 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1155 let bounds: &[_] = ty_param_bounds;
1156 let bound_str = try_opt!(bounds.iter()
1157 .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1158 .intersperse(Some(" + ".to_string()))
1159 .collect::<Option<String>>());
1160 if bounds.len() > 0 {
1161 format!(": {}", bound_str)
1169 if let Some(ty) = ty_opt {
1170 let ty_str = try_opt!(ty.rewrite(context,
1171 context.config.max_width - context.block_indent.width() -
1174 context.block_indent));
1175 Some(format!("{} = {};", prefix, ty_str))
1177 Some(format!("{}{};", prefix, type_bounds_str))
1181 impl Rewrite for ast::FunctionRetTy {
1182 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1184 ast::FunctionRetTy::Default(_) => Some(String::new()),
1185 ast::FunctionRetTy::Ty(ref ty) => {
1186 let inner_width = try_opt!(width.checked_sub(3));
1187 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1193 impl Rewrite for ast::Arg {
1194 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1195 if is_named_arg(self) {
1196 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1198 if self.ty.node != ast::TyKind::Infer {
1199 if context.config.space_before_type_annotation {
1200 result.push_str(" ");
1202 result.push_str(":");
1203 if context.config.space_after_type_annotation_colon {
1204 result.push_str(" ");
1206 let max_width = try_opt!(width.checked_sub(result.len()));
1207 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1208 result.push_str(&ty_str);
1213 self.ty.rewrite(context, width, offset)
1218 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1220 context: &RewriteContext)
1222 match explicit_self.node {
1223 ast::SelfKind::Region(lt, m) => {
1224 let mut_str = format_mutability(m);
1228 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1229 Some(format!("&{} {}self", lifetime_str, mut_str))
1231 None => Some(format!("&{}self", mut_str)),
1234 ast::SelfKind::Explicit(ref ty, _) => {
1235 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1237 let mutability = explicit_self_mutability(&args[0]);
1238 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1240 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1242 ast::SelfKind::Value(_) => {
1243 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1245 let mutability = explicit_self_mutability(&args[0]);
1247 Some(format!("{}self", format_mutability(mutability)))
1252 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1253 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1254 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1255 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1262 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1263 if is_named_arg(arg) {
1270 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1272 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1273 _ => arg.ty.span.hi,
1277 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1278 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1279 ident.node != token::keywords::Invalid.ident()
1285 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1287 ast::FunctionRetTy::Default(ref span) => span.clone(),
1288 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1292 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1293 // Note that ty.span is the span for ty.ident, not the whole item.
1294 let lo = ty.span.lo;
1295 if let Some(ref def) = ty.default {
1296 return mk_sp(lo, def.span.hi);
1298 if ty.bounds.is_empty() {
1301 let hi = match ty.bounds[ty.bounds.len() - 1] {
1302 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1303 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1308 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1310 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1311 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1312 ast::WherePredicate::EqPredicate(ref p) => p.span,
1316 // Return type is (result, force_new_line_for_brace)
1317 fn rewrite_fn_base(context: &RewriteContext,
1321 generics: &ast::Generics,
1322 unsafety: ast::Unsafety,
1323 constness: ast::Constness,
1324 defaultness: ast::Defaultness,
1326 vis: &ast::Visibility,
1328 newline_brace: bool,
1330 -> Option<(String, bool)> {
1331 let mut force_new_line_for_brace = false;
1332 // FIXME we'll lose any comments in between parts of the function decl, but
1333 // anyone who comments there probably deserves what they get.
1335 let where_clause = &generics.where_clause;
1337 let mut result = String::with_capacity(1024);
1338 // Vis unsafety abi.
1339 result.push_str(&*format_visibility(vis));
1341 if let ast::Defaultness::Default = defaultness {
1342 result.push_str("default ");
1345 if let ast::Constness::Const = constness {
1346 result.push_str("const ");
1349 result.push_str(::utils::format_unsafety(unsafety));
1351 if abi != abi::Abi::Rust {
1352 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1356 result.push_str("fn ");
1357 result.push_str(&ident.to_string());
1360 let generics_indent = indent + result.len();
1361 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1362 let generics_str = try_opt!(rewrite_generics(context,
1365 context.config.max_width,
1368 result.push_str(&generics_str);
1370 // Note that if the width and indent really matter, we'll re-layout the
1371 // return type later anyway.
1372 let ret_str = try_opt!(fd.output
1373 .rewrite(&context, context.config.max_width - indent.width(), indent));
1375 let multi_line_ret_str = ret_str.contains('\n');
1376 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1379 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1380 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1382 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1383 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1384 arg_indent = indent.block_indent(context.config);
1385 multi_line_budget = context.config.max_width - arg_indent.width();
1388 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1393 // Check if vertical layout was forced by compute_budget_for_args.
1394 if one_line_budget == 0 {
1395 if context.config.fn_args_paren_newline {
1397 result.push_str(&arg_indent.to_string(context.config));
1398 arg_indent = arg_indent + 1; // extra space for `(`
1400 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1404 result.push_str("(\n");
1405 result.push_str(&arg_indent.to_string(context.config));
1409 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1414 if multi_line_ret_str {
1415 one_line_budget = 0;
1418 // A conservative estimation, to goal is to be over all parens in generics
1419 let args_start = generics.ty_params
1421 .map_or(span.lo, |tp| end_typaram(tp));
1422 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1423 span_for_return(&fd.output).lo);
1424 let arg_str = try_opt!(rewrite_args(context,
1426 fd.get_self().as_ref(),
1434 let multi_line_arg_str = arg_str.contains('\n');
1436 let put_args_in_block = match context.config.fn_args_layout {
1437 FnArgLayoutStyle::Block => multi_line_arg_str,
1438 FnArgLayoutStyle::BlockAlways => true,
1440 } && !fd.inputs.is_empty();
1442 if put_args_in_block {
1443 arg_indent = indent.block_indent(context.config);
1445 result.push_str(&arg_indent.to_string(context.config));
1446 result.push_str(&arg_str);
1448 result.push_str(&indent.to_string(context.config));
1451 result.push_str(&arg_str);
1452 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1459 if !ret_str.is_empty() {
1460 let ret_should_indent = match context.config.fn_args_layout {
1461 // If our args are block layout then we surely must have space.
1462 FnArgLayoutStyle::Block if put_args_in_block => false,
1463 FnArgLayoutStyle::BlockAlways => false,
1465 // If we've already gone multi-line, or the return type would push over the max
1466 // width, then put the return type on a new line. With the +1 for the signature
1467 // length an additional space between the closing parenthesis of the argument and
1468 // the arrow '->' is considered.
1469 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1471 // If there is no where clause, take into account the space after the return type
1473 if where_clause.predicates.is_empty() {
1477 let overlong_sig = sig_length > context.config.max_width;
1479 result.contains('\n') || multi_line_ret_str || overlong_sig
1482 let ret_indent = if ret_should_indent {
1483 let indent = match context.config.fn_return_indent {
1484 ReturnIndent::WithWhereClause => indent + 4,
1485 // Aligning with non-existent args looks silly.
1486 _ if arg_str.is_empty() => {
1487 force_new_line_for_brace = true;
1490 // FIXME: we might want to check that using the arg indent
1491 // doesn't blow our budget, and if it does, then fallback to
1492 // the where clause indent.
1497 result.push_str(&indent.to_string(context.config));
1501 Indent::new(indent.width(), result.len())
1504 if multi_line_ret_str {
1505 // Now that we know the proper indent and width, we need to
1506 // re-layout the return type.
1507 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1508 let ret_str = try_opt!(fd.output.rewrite(context, budget, ret_indent));
1509 result.push_str(&ret_str);
1511 result.push_str(&ret_str);
1514 // Comment between return type and the end of the decl.
1515 let snippet_lo = fd.output.span().hi;
1516 if where_clause.predicates.is_empty() {
1517 let snippet_hi = span.hi;
1518 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1519 let snippet = snippet.trim();
1520 if !snippet.is_empty() {
1522 result.push_str(snippet);
1525 // FIXME it would be nice to catch comments between the return type
1526 // and the where clause, but we don't have a span for the where
1531 let should_compress_where = match context.config.where_density {
1532 Density::Compressed => !result.contains('\n') || put_args_in_block,
1533 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1535 } || (put_args_in_block && ret_str.is_empty());
1537 let where_density = if should_compress_where {
1544 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1545 let where_clause_str = try_opt!(rewrite_where_clause(context,
1548 context.config.fn_brace_style,
1556 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1557 !where_clause_str.contains('\n') {
1561 result.push_str(&where_clause_str);
1563 Some((result, force_new_line_for_brace))
1566 fn rewrite_args(context: &RewriteContext,
1568 explicit_self: Option<&ast::ExplicitSelf>,
1569 one_line_budget: usize,
1570 multi_line_budget: usize,
1576 let mut arg_item_strs = try_opt!(args.iter()
1577 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1578 .collect::<Option<Vec<_>>>());
1580 // Account for sugary self.
1581 // FIXME: the comment for the self argument is dropped. This is blocked
1582 // on rust issue #27522.
1584 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1585 .map_or(1, |self_str| {
1586 arg_item_strs[0] = self_str;
1590 // Comments between args.
1591 let mut arg_items = Vec::new();
1593 arg_items.push(ListItem::from_str(""));
1596 // FIXME(#21): if there are no args, there might still be a comment, but
1597 // without spans for the comment or parens, there is no chance of
1598 // getting it right. You also don't get to put a comment on self, unless
1600 if args.len() >= min_args || variadic {
1601 let comment_span_start = if min_args == 2 {
1602 let second_arg_start = if arg_has_pattern(&args[1]) {
1607 let reduced_span = mk_sp(span.lo, second_arg_start);
1609 context.codemap.span_after_last(reduced_span, ",")
1614 enum ArgumentKind<'a> {
1615 Regular(&'a ast::Arg),
1619 let variadic_arg = if variadic {
1620 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1621 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1622 Some(ArgumentKind::Variadic(variadic_start))
1627 let more_items = itemize_list(context.codemap,
1628 args[min_args - 1..]
1630 .map(ArgumentKind::Regular)
1631 .chain(variadic_arg),
1634 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1635 ArgumentKind::Variadic(start) => start,
1638 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1639 ArgumentKind::Variadic(start) => start + BytePos(3),
1642 ArgumentKind::Regular(..) => None,
1643 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1648 arg_items.extend(more_items);
1651 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1652 item.item = Some(arg);
1655 let indent = match context.config.fn_arg_indent {
1656 BlockIndentStyle::Inherit => indent,
1657 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1658 BlockIndentStyle::Visual => arg_indent,
1661 let tactic = definitive_tactic(&arg_items,
1662 context.config.fn_args_density.to_list_tactic(),
1664 let budget = match tactic {
1665 DefinitiveListTactic::Horizontal => one_line_budget,
1666 _ => multi_line_budget,
1669 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1671 let end_with_newline = match context.config.fn_args_layout {
1672 FnArgLayoutStyle::Block |
1673 FnArgLayoutStyle::BlockAlways => true,
1677 let fmt = ListFormatting {
1680 trailing_separator: SeparatorTactic::Never,
1683 ends_with_newline: end_with_newline,
1684 config: context.config,
1687 write_list(&arg_items, &fmt)
1690 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1691 if let ast::PatKind::Ident(_,
1693 node: ast::Ident { name: ast::Name(0u32), .. },
1703 fn compute_budgets_for_args(context: &RewriteContext,
1707 newline_brace: bool)
1708 -> Option<((usize, usize, Indent))> {
1709 // Try keeping everything on the same line.
1710 if !result.contains('\n') {
1711 // 3 = `() `, space is before ret_string.
1712 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1716 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1718 if one_line_budget > 0 {
1720 let multi_line_budget =
1721 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1723 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1727 // Didn't work. we must force vertical layout and put args on a newline.
1728 let new_indent = indent.block_indent(context.config);
1729 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1730 let max_space = context.config.max_width;
1731 if used_space <= max_space {
1732 Some((0, max_space - used_space, new_indent))
1734 // Whoops! bankrupt.
1739 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1740 match config.fn_brace_style {
1741 BraceStyle::AlwaysNextLine => true,
1742 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1747 fn rewrite_generics(context: &RewriteContext,
1748 generics: &ast::Generics,
1751 generics_offset: Indent,
1754 // FIXME: convert bounds to where clauses where they get too big or if
1755 // there is a where clause at all.
1756 let lifetimes: &[_] = &generics.lifetimes;
1757 let tys: &[_] = &generics.ty_params;
1758 if lifetimes.is_empty() && tys.is_empty() {
1759 return Some(String::new());
1762 let offset = match context.config.generics_indent {
1763 BlockIndentStyle::Inherit => offset,
1764 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1766 BlockIndentStyle::Visual => generics_offset + 1,
1769 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1770 // FIXME: might need to insert a newline if the generics are really long.
1772 // Strings for the generics.
1773 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, h_budget, offset));
1774 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, h_budget, offset));
1776 // Extract comments between generics.
1777 let lt_spans = lifetimes.iter().map(|l| {
1778 let hi = if l.bounds.is_empty() {
1781 l.bounds[l.bounds.len() - 1].span.hi
1783 mk_sp(l.lifetime.span.lo, hi)
1785 let ty_spans = tys.iter().map(span_for_ty_param);
1787 let items = itemize_list(context.codemap,
1788 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1792 // FIXME: don't clone
1793 |&(_, ref str)| str.clone(),
1794 context.codemap.span_after(span, "<"),
1796 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1798 Some(if context.config.spaces_within_angle_brackets {
1799 format!("< {} >", list_str)
1801 format!("<{}>", list_str)
1805 fn rewrite_trait_bounds(context: &RewriteContext,
1806 type_param_bounds: &ast::TyParamBounds,
1810 let bounds: &[_] = type_param_bounds;
1812 if bounds.is_empty() {
1813 return Some(String::new());
1816 let bound_str = try_opt!(bounds.iter()
1817 .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1818 .intersperse(Some(" + ".to_string()))
1819 .collect::<Option<String>>());
1821 let mut result = String::new();
1822 result.push_str(": ");
1823 result.push_str(&bound_str);
1827 fn rewrite_where_clause(context: &RewriteContext,
1828 where_clause: &ast::WhereClause,
1830 brace_style: BraceStyle,
1835 allow_trailing_comma: bool,
1836 span_end: Option<BytePos>)
1838 if where_clause.predicates.is_empty() {
1839 return Some(String::new());
1842 let extra_indent = match context.config.where_indent {
1843 BlockIndentStyle::Inherit => Indent::empty(),
1844 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1847 let offset = match context.config.where_pred_indent {
1848 BlockIndentStyle::Inherit => indent + extra_indent,
1849 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1850 // 6 = "where ".len()
1851 BlockIndentStyle::Visual => indent + extra_indent + 6,
1853 // FIXME: if where_pred_indent != Visual, then the budgets below might
1854 // be out by a char or two.
1856 let budget = context.config.max_width - offset.width();
1857 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1858 // If we don't have the start of the next span, then use the end of the
1859 // predicates, but that means we miss comments.
1860 let len = where_clause.predicates.len();
1861 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1862 let span_end = span_end.unwrap_or(end_of_preds);
1863 let items = itemize_list(context.codemap,
1864 where_clause.predicates.iter(),
1866 |pred| span_for_where_pred(pred).lo,
1867 |pred| span_for_where_pred(pred).hi,
1868 |pred| pred.rewrite(context, budget, offset),
1871 let item_vec = items.collect::<Vec<_>>();
1872 // FIXME: we don't need to collect here if the where_layout isn't
1873 // HorizontalVertical.
1874 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1875 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1877 let fmt = ListFormatting {
1880 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1883 ends_with_newline: true,
1884 config: context.config,
1886 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1888 let end_length = if terminator == "{" {
1889 // If the brace is on the next line we don't need to count it otherwise it needs two
1892 BraceStyle::AlwaysNextLine |
1893 BraceStyle::SameLineWhere => 0,
1894 BraceStyle::PreferSameLine => 2,
1896 } else if terminator == "=" {
1901 if density == Density::Tall || preds_str.contains('\n') ||
1902 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1903 Some(format!("\n{}where {}",
1904 (indent + extra_indent).to_string(context.config),
1907 Some(format!(" where {}", preds_str))
1911 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1912 format!("{}{}{}", format_visibility(vis), item_name, ident)
1915 fn format_generics(context: &RewriteContext,
1916 generics: &ast::Generics,
1919 brace_style: BraceStyle,
1920 force_same_line_brace: bool,
1922 generics_offset: Indent,
1925 let mut result = try_opt!(rewrite_generics(context,
1928 context.config.max_width,
1932 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1933 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1934 let where_clause_str = try_opt!(rewrite_where_clause(context,
1935 &generics.where_clause,
1938 context.block_indent,
1944 result.push_str(&where_clause_str);
1945 if !force_same_line_brace &&
1946 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1948 result.push_str(&context.block_indent.to_string(context.config));
1952 result.push_str(opener);
1954 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1956 result.push_str(&context.block_indent.to_string(context.config));
1960 result.push_str(opener);