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};
25 use syntax::{ast, abi, ptr, codemap};
26 use syntax::codemap::{Span, BytePos, mk_sp};
27 use syntax::parse::token;
28 use syntax::ast::ImplItem;
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34 let mut result = "let ".to_owned();
35 let pattern_offset = offset + result.len();
37 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
39 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
40 result.push_str(&pat_str);
42 // String that is placed within the assignment pattern and expression.
44 let mut infix = String::new();
46 if let Some(ref ty) = self.ty {
49 let indent = offset + last_line_width(&result) + 2;
50 let budget = try_opt!(width.checked_sub(indent.width() + 1));
51 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
54 infix.push_str(&rewrite);
57 if self.init.is_some() {
64 result.push_str(&infix);
66 if let Some(ref ex) = self.init {
67 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
69 // 1 = trailing semicolon;
71 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
79 impl<'a> FmtVisitor<'a> {
80 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
81 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
82 self.buffer.push_str(&abi_str);
84 let snippet = self.snippet(span);
85 let brace_pos = snippet.find_uncommented("{").unwrap();
87 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
88 self.buffer.push_str("{");
90 // FIXME: this skips comments between the extern keyword and the opening
92 self.last_pos = span.lo + BytePos(brace_pos as u32);
93 self.block_indent = self.block_indent.block_indent(self.config);
95 for item in &fm.items {
96 self.format_foreign_item(&*item);
99 self.block_indent = self.block_indent.block_unindent(self.config);
100 self.format_missing_with_indent(span.hi - BytePos(1));
103 self.buffer.push_str("}");
104 self.last_pos = span.hi;
107 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
108 self.format_missing_with_indent(item.span.lo);
109 // Drop semicolon or it will be interpreted as comment.
110 // FIXME: this may be a faulty span from libsyntax.
111 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
114 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
115 let indent = self.block_indent;
116 let rewrite = rewrite_fn_base(&self.get_context(),
121 ast::Unsafety::Normal,
122 ast::Constness::NotConst,
123 // These are not actually rust functions,
124 // but we format them as such.
132 Some((new_fn, _)) => {
133 self.buffer.push_str(&new_fn);
134 self.buffer.push_str(";");
136 None => self.format_missing(item.span.hi),
139 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
140 // FIXME(#21): we're dropping potential comments in between the
141 // function keywords here.
142 let vis = format_visibility(&item.vis);
143 let mut_str = if is_mutable { "mut " } else { "" };
144 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
145 let offset = self.block_indent + prefix.len();
147 let width = self.config.max_width - offset.width() - 1;
148 let rewrite = ty.rewrite(&self.get_context(), width, offset);
152 self.buffer.push_str(&prefix);
153 self.buffer.push_str(&result);
154 self.buffer.push_str(";");
156 None => self.format_missing(item.span.hi),
161 self.last_pos = item.span.hi;
164 pub fn rewrite_fn(&mut self,
168 generics: &ast::Generics,
169 unsafety: ast::Unsafety,
170 constness: ast::Constness,
172 vis: &ast::Visibility,
176 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
177 let context = self.get_context();
179 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
180 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
181 !context.config.fn_empty_single_line;
183 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
196 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
197 newline_brace = false;
198 } else if force_newline_brace {
199 newline_brace = true;
202 // Prepare for the function body by possibly adding a newline and
204 // FIXME we'll miss anything between the end of the signature and the
205 // start of the body, but we need more spans from the compiler to solve
209 result.push_str(&indent.to_string(self.config));
214 self.single_line_fn(&result, block).or_else(|| Some(result))
217 pub fn rewrite_required_fn(&mut self,
220 sig: &ast::MethodSig,
223 // Drop semicolon or it will be interpreted as comment.
224 let span = mk_sp(span.lo, span.hi - BytePos(1));
225 let context = self.get_context();
227 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
235 &ast::Visibility::Inherited,
240 // Re-attach semicolon
246 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
247 if fn_str.contains('\n') {
251 let codemap = self.get_context().codemap;
253 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
254 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
255 return Some(format!("{}{{}}", fn_str));
258 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
260 if let Some(ref e) = block.expr {
261 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
263 e.rewrite(&self.get_context(),
264 self.config.max_width - self.block_indent.width(),
267 .or_else(|| Some(self.snippet(e.span)))
268 } else if let Some(ref stmt) = block.stmts.first() {
269 stmt.rewrite(&self.get_context(),
270 self.config.max_width - self.block_indent.width(),
277 if let Some(res) = rewrite {
278 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
279 if !res.contains('\n') && width <= self.config.max_width {
280 return Some(format!("{}{{ {} }}", fn_str, res));
288 pub fn visit_enum(&mut self,
290 vis: &ast::Visibility,
291 enum_def: &ast::EnumDef,
292 generics: &ast::Generics,
294 self.buffer.push_str(&format_header("enum ", ident, vis));
296 let enum_snippet = self.snippet(span);
297 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
298 let generics_str = format_generics(&self.get_context(),
302 self.config.item_brace_style,
303 enum_def.variants.is_empty(),
305 self.block_indent.block_indent(self.config),
306 mk_sp(span.lo, body_start))
308 self.buffer.push_str(&generics_str);
310 self.last_pos = body_start;
312 self.block_indent = self.block_indent.block_indent(self.config);
313 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
315 Some(ref body_str) => self.buffer.push_str(&body_str),
316 None => self.format_missing(span.hi - BytePos(1)),
318 self.block_indent = self.block_indent.block_unindent(self.config);
320 if variant_list.is_some() {
321 self.buffer.push_str(&self.block_indent.to_string(self.config));
323 self.buffer.push_str("}");
324 self.last_pos = span.hi;
327 // Format the body of an enum definition
328 fn format_variant_list(&self,
329 enum_def: &ast::EnumDef,
333 if enum_def.variants.is_empty() {
336 let mut result = String::with_capacity(1024);
338 let indentation = self.block_indent.to_string(self.config);
339 result.push_str(&indentation);
341 let items = itemize_list(self.codemap,
342 enum_def.variants.iter(),
345 if !f.node.attrs.is_empty() {
346 f.node.attrs[0].span.lo
352 |f| self.format_variant(f),
356 let budget = self.config.max_width - self.block_indent.width() - 2;
357 let fmt = ListFormatting {
358 tactic: DefinitiveListTactic::Vertical,
360 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
361 indent: self.block_indent,
363 ends_with_newline: true,
367 let list = try_opt!(write_list(items, &fmt));
368 result.push_str(&list);
373 // Variant of an enum.
374 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
375 if contains_skip(&field.node.attrs) {
376 let lo = field.node.attrs[0].span.lo;
377 let span = mk_sp(lo, field.span.hi);
378 return Some(self.snippet(span));
381 let indent = self.block_indent;
382 let mut result = try_opt!(field.node
384 .rewrite(&self.get_context(),
385 self.config.max_width - indent.width(),
387 if !result.is_empty() {
389 result.push_str(&indent.to_string(self.config));
392 let context = self.get_context();
393 let variant_body = match field.node.data {
394 ast::VariantData::Tuple(..) |
395 ast::VariantData::Struct(..) => {
396 // FIXME: Should limit the width, as we have a trailing comma
397 format_struct(&context,
400 &ast::Visibility::Inherited,
405 Some(self.config.struct_variant_width))
407 ast::VariantData::Unit(..) => {
408 let tag = if let Some(ref expr) = field.node.disr_expr {
409 format!("{} = {}", field.node.name, self.snippet(expr.span))
411 field.node.name.to_string()
415 self.config.max_width,
416 self.config.max_width - indent.width(),
421 if let Some(variant_str) = variant_body {
422 result.push_str(&variant_str);
430 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
431 if let ast::ItemKind::Impl(unsafety,
436 ref items) = item.node {
437 let mut result = String::new();
438 result.push_str(&*format_visibility(&item.vis));
439 result.push_str(format_unsafety(unsafety));
440 result.push_str("impl");
442 let lo = context.codemap.span_after(item.span, "impl");
443 let hi = match *trait_ref {
444 Some(ref tr) => tr.path.span.lo,
445 None => self_ty.span.lo,
447 let generics_str = try_opt!(rewrite_generics(context,
450 context.config.max_width,
451 offset + result.len(),
453 result.push_str(&generics_str);
455 // FIXME might need to linebreak in the impl header, here would be a
458 if polarity == ast::ImplPolarity::Negative {
459 result.push_str("!");
461 if let Some(ref trait_ref) = *trait_ref {
462 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
463 let indent = offset + result.len();
464 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
465 result.push_str(" for ");
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!(self_ty.rewrite(context, budget, indent)));
472 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
473 let where_clause_str = try_opt!(rewrite_where_clause(context,
474 &generics.where_clause,
476 context.config.item_brace_style,
477 context.block_indent,
479 context.config.where_density,
484 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
485 result.push_str(&where_clause_str);
486 if where_clause_str.contains('\n') {
487 let white_space = offset.to_string(context.config);
488 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
490 result.push_str(" {}");
495 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
497 let width = context.block_indent.width() + context.config.tab_spaces - 1;
498 let where_indent = Indent::new(0, width);
499 result.push_str(&where_indent.to_string(context.config));
501 result.push_str(&where_clause_str);
503 match context.config.item_brace_style {
504 BraceStyle::AlwaysNextLine => result.push('\n'),
505 BraceStyle::PreferSameLine => result.push(' '),
506 BraceStyle::SameLineWhere => {
507 if !where_clause_str.is_empty() {
509 result.push_str(&offset.to_string(context.config));
518 let snippet = context.snippet(item.span);
519 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
521 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
522 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
523 visitor.block_indent = context.block_indent.block_indent(context.config);
524 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
527 visitor.visit_impl_item(&item);
530 visitor.format_missing(item.span.hi - BytePos(1));
532 let inner_indent_str = visitor.block_indent.to_string(context.config);
533 let outer_indent_str = context.block_indent.to_string(context.config);
536 result.push_str(&inner_indent_str);
537 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
539 result.push_str(&outer_indent_str);
542 if result.chars().last().unwrap() == '{' {
553 fn is_impl_single_line(context: &RewriteContext,
554 items: &Vec<ImplItem>,
556 where_clause_str: &str,
559 let snippet = context.snippet(item.span);
560 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
562 Some(context.config.impl_empty_single_line && items.is_empty() &&
563 result.len() + where_clause_str.len() <= context.config.max_width &&
564 !contains_comment(&snippet[open_pos..]))
567 pub fn format_struct(context: &RewriteContext,
570 vis: &ast::Visibility,
571 struct_def: &ast::VariantData,
572 generics: Option<&ast::Generics>,
575 one_line_width: Option<usize>)
578 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
579 ast::VariantData::Tuple(ref fields, _) => {
580 format_tuple_struct(context,
589 ast::VariantData::Struct(ref fields, _) => {
590 format_struct_struct(context,
603 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
604 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
606 let mut result = String::new();
607 let header = format!("{}{}trait {}",
608 format_visibility(&item.vis),
609 format_unsafety(unsafety),
612 result.push_str(&header);
614 let body_lo = context.codemap.span_after(item.span, "{");
616 let generics_str = try_opt!(rewrite_generics(context,
619 context.config.max_width,
620 offset + result.len(),
621 mk_sp(item.span.lo, body_lo)));
622 result.push_str(&generics_str);
624 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
627 context.config.max_width));
628 // If the trait, generics, and trait bound cannot fit on the same line,
629 // put the trait bounds on an indented new line
630 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
631 context.config.ideal_width {
633 let width = context.block_indent.width() + context.config.tab_spaces;
634 let trait_indent = Indent::new(0, width);
635 result.push_str(&trait_indent.to_string(context.config));
637 result.push_str(&trait_bound_str);
639 let has_body = !trait_items.is_empty();
642 if (context.config.where_density == Density::Compressed &&
643 (!result.contains('\n') ||
644 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
645 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
646 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
647 !result.contains('\n')) {
653 let where_budget = try_opt!(context.config
655 .checked_sub(last_line_width(&result)));
656 let where_clause_str = try_opt!(rewrite_where_clause(context,
657 &generics.where_clause,
659 context.config.item_brace_style,
660 context.block_indent,
666 // If the where clause cannot fit on the same line,
667 // put the where clause on a new line
668 if !where_clause_str.contains('\n') &&
669 last_line_width(&result) + where_clause_str.len() + offset.width() >
670 context.config.ideal_width {
672 let width = context.block_indent.width() + context.config.tab_spaces - 1;
673 let where_indent = Indent::new(0, width);
674 result.push_str(&where_indent.to_string(context.config));
676 result.push_str(&where_clause_str);
678 match context.config.item_brace_style {
679 BraceStyle::AlwaysNextLine => {
681 result.push_str(&offset.to_string(context.config));
683 BraceStyle::PreferSameLine => result.push(' '),
684 BraceStyle::SameLineWhere => {
685 if !where_clause_str.is_empty() &&
686 (trait_items.len() > 0 || result.contains('\n')) {
688 result.push_str(&offset.to_string(context.config));
696 let snippet = context.snippet(item.span);
697 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
699 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
700 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
701 visitor.block_indent = context.block_indent.block_indent(context.config);
702 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
704 for item in trait_items {
705 visitor.visit_trait_item(&item);
708 visitor.format_missing(item.span.hi - BytePos(1));
710 let inner_indent_str = visitor.block_indent.to_string(context.config);
711 let outer_indent_str = context.block_indent.to_string(context.config);
714 result.push_str(&inner_indent_str);
715 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
717 result.push_str(&outer_indent_str);
718 } else if result.contains('\n') {
729 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
730 format!("{};", format_header(item_name, ident, vis))
733 fn format_struct_struct(context: &RewriteContext,
736 vis: &ast::Visibility,
737 fields: &[ast::StructField],
738 generics: Option<&ast::Generics>,
741 one_line_width: Option<usize>)
743 let mut result = String::with_capacity(1024);
745 let header_str = format_header(item_name, ident, vis);
746 result.push_str(&header_str);
748 let body_lo = context.codemap.span_after(span, "{");
750 let generics_str = match generics {
752 try_opt!(format_generics(context,
756 context.config.item_brace_style,
759 offset + header_str.len(),
760 mk_sp(span.lo, body_lo)))
763 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
764 format!("\n{}{{", context.block_indent.to_string(context.config))
770 result.push_str(&generics_str);
772 // FIXME(#919): properly format empty structs and their comments.
773 if fields.is_empty() {
774 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
778 let item_indent = offset.block_indent(context.config);
780 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
782 let items = itemize_list(context.codemap,
786 // Include attributes and doc comments, if present
787 if !field.attrs.is_empty() {
788 field.attrs[0].span.lo
793 |field| field.ty.span.hi,
794 |field| field.rewrite(context, item_budget, item_indent),
795 context.codemap.span_after(span, "{"),
797 .collect::<Vec<_>>();
799 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
801 let tactic = match one_line_width {
802 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
803 None => DefinitiveListTactic::Vertical,
806 let fmt = ListFormatting {
809 trailing_separator: context.config.struct_trailing_comma,
812 ends_with_newline: true,
813 config: context.config,
815 let items_str = try_opt!(write_list(&items, &fmt));
816 if one_line_width.is_some() && !items_str.contains('\n') {
817 Some(format!("{} {} }}", result, items_str))
819 Some(format!("{}\n{}{}\n{}}}",
821 offset.block_indent(context.config).to_string(context.config),
823 offset.to_string(context.config)))
827 fn format_tuple_struct(context: &RewriteContext,
830 vis: &ast::Visibility,
831 fields: &[ast::StructField],
832 generics: Option<&ast::Generics>,
836 let mut result = String::with_capacity(1024);
838 let header_str = format_header(item_name, ident, vis);
839 result.push_str(&header_str);
841 // FIXME(#919): don't lose comments on empty tuple structs.
842 let body_lo = if fields.is_empty() {
848 let where_clause_str = match generics {
849 Some(ref generics) => {
850 let generics_str = try_opt!(rewrite_generics(context,
853 context.config.max_width,
854 offset + header_str.len(),
855 mk_sp(span.lo, body_lo)));
856 result.push_str(&generics_str);
858 let where_budget = try_opt!(context.config
860 .checked_sub(last_line_width(&result)));
861 try_opt!(rewrite_where_clause(context,
862 &generics.where_clause,
864 context.config.item_brace_style,
865 context.block_indent,
872 None => "".to_owned(),
876 let item_indent = context.block_indent + result.len();
878 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
880 let items = itemize_list(context.codemap,
884 // Include attributes and doc comments, if present
885 if !field.attrs.is_empty() {
886 field.attrs[0].span.lo
891 |field| field.ty.span.hi,
892 |field| field.rewrite(context, item_budget, item_indent),
893 context.codemap.span_after(span, "("),
895 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
896 result.push_str(&body);
899 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
900 (result.contains('\n') ||
901 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
902 context.config.max_width) {
903 // We need to put the where clause on a new line, but we didn'to_string
904 // know that earlier, so the where clause will not be indented properly.
906 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
907 .to_string(context.config));
909 result.push_str(&where_clause_str);
914 pub fn rewrite_type_alias(context: &RewriteContext,
918 generics: &ast::Generics,
919 vis: &ast::Visibility,
922 let mut result = String::new();
924 result.push_str(&format_visibility(&vis));
925 result.push_str("type ");
926 result.push_str(&ident.to_string());
928 let generics_indent = indent + result.len();
929 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
930 let generics_width = context.config.max_width - " =".len();
931 let generics_str = try_opt!(rewrite_generics(context,
938 result.push_str(&generics_str);
940 let where_budget = try_opt!(context.config
942 .checked_sub(last_line_width(&result)));
943 let where_clause_str = try_opt!(rewrite_where_clause(context,
944 &generics.where_clause,
946 context.config.item_brace_style,
949 context.config.where_density,
953 result.push_str(&where_clause_str);
954 result.push_str(" = ");
956 let line_width = last_line_width(&result);
957 // This checked_sub may fail as the extra space after '=' is not taken into account
958 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
959 let budget = context.config
961 .checked_sub(indent.width() + line_width + ";".len())
963 let type_indent = indent + line_width;
964 // Try to fit the type on the same line
965 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
967 // The line was too short, try to put the type on the next line
969 // Remove the space after '='
971 let type_indent = indent.block_indent(context.config);
973 result.push_str(&type_indent.to_string(context.config));
974 let budget = try_opt!(context.config
976 .checked_sub(type_indent.width() + ";".len()));
977 ty.rewrite(context, budget, type_indent)
979 result.push_str(&ty_str);
980 result.push_str(";");
984 impl Rewrite for ast::StructField {
985 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
986 if contains_skip(&self.attrs) {
987 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
988 return wrap_str(span, context.config.max_width, width, offset);
991 let name = self.ident;
992 let vis = format_visibility(&self.vis);
993 let mut attr_str = try_opt!(self.attrs
994 .rewrite(context, context.config.max_width - offset.width(), offset));
995 if !attr_str.is_empty() {
997 attr_str.push_str(&offset.to_string(context.config));
1000 let result = match name {
1001 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1002 None => format!("{}{}", attr_str, vis),
1005 let last_line_width = last_line_width(&result);
1006 let budget = try_opt!(width.checked_sub(last_line_width));
1007 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1008 Some(result + &rewrite)
1012 pub fn rewrite_static(prefix: &str,
1013 vis: &ast::Visibility,
1016 mutability: ast::Mutability,
1017 expr_opt: Option<&ptr::P<ast::Expr>>,
1018 context: &RewriteContext)
1020 let prefix = format!("{}{} {}{}: ",
1021 format_visibility(vis),
1023 format_mutability(mutability),
1026 let ty_str = try_opt!(ty.rewrite(context,
1027 context.config.max_width - context.block_indent.width() -
1029 context.block_indent));
1031 if let Some(ref expr) = expr_opt {
1032 let lhs = format!("{}{} =", prefix, ty_str);
1034 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1035 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1038 let lhs = format!("{}{};", prefix, ty_str);
1043 pub fn rewrite_associated_type(ident: ast::Ident,
1044 ty_opt: Option<&ptr::P<ast::Ty>>,
1045 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1046 context: &RewriteContext,
1049 let prefix = format!("type {}", ident);
1051 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1052 let bounds: &[_] = &ty_param_bounds;
1053 let bound_str = bounds.iter()
1054 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1055 .collect::<Vec<String>>()
1057 if bounds.len() > 0 {
1058 format!(": {}", bound_str)
1066 if let Some(ty) = ty_opt {
1067 let ty_str = try_opt!(ty.rewrite(context,
1068 context.config.max_width - context.block_indent.width() -
1071 context.block_indent));
1072 Some(format!("{} = {};", prefix, ty_str))
1074 Some(format!("{}{};", prefix, type_bounds_str))
1078 impl Rewrite for ast::FunctionRetTy {
1079 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1081 ast::FunctionRetTy::Default(_) => Some(String::new()),
1082 ast::FunctionRetTy::None(_) => {
1084 Some("-> !".to_owned())
1089 ast::FunctionRetTy::Ty(ref ty) => {
1090 let inner_width = try_opt!(width.checked_sub(3));
1091 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1097 impl Rewrite for ast::Arg {
1098 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1099 if is_named_arg(self) {
1100 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1102 if self.ty.node != ast::TyKind::Infer {
1103 result.push_str(": ");
1104 let max_width = try_opt!(width.checked_sub(result.len()));
1105 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1106 result.push_str(&ty_str);
1111 self.ty.rewrite(context, width, offset)
1116 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1118 context: &RewriteContext)
1120 match explicit_self.node {
1121 ast::SelfKind::Region(lt, m) => {
1122 let mut_str = format_mutability(m);
1126 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1127 Some(format!("&{} {}self", lifetime_str, mut_str))
1129 None => Some(format!("&{}self", mut_str)),
1132 ast::SelfKind::Explicit(ref ty, _) => {
1133 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1135 let mutability = explicit_self_mutability(&args[0]);
1136 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1138 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1140 ast::SelfKind::Value(_) => {
1141 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1143 let mutability = explicit_self_mutability(&args[0]);
1145 Some(format!("{}self", format_mutability(mutability)))
1150 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1151 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1152 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1153 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1160 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1161 if is_named_arg(arg) {
1168 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1170 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1171 _ => arg.ty.span.hi,
1175 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1176 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1177 ident.node != token::keywords::Invalid.ident()
1183 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1185 ast::FunctionRetTy::None(ref span) |
1186 ast::FunctionRetTy::Default(ref span) => span.clone(),
1187 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1191 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1192 // Note that ty.span is the span for ty.ident, not the whole item.
1193 let lo = ty.span.lo;
1194 if let Some(ref def) = ty.default {
1195 return mk_sp(lo, def.span.hi);
1197 if ty.bounds.is_empty() {
1200 let hi = match ty.bounds[ty.bounds.len() - 1] {
1201 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1202 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1207 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1209 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1210 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1211 ast::WherePredicate::EqPredicate(ref p) => p.span,
1215 // Return type is (result, force_new_line_for_brace)
1216 fn rewrite_fn_base(context: &RewriteContext,
1220 generics: &ast::Generics,
1221 unsafety: ast::Unsafety,
1222 constness: ast::Constness,
1224 vis: &ast::Visibility,
1226 newline_brace: bool,
1228 -> Option<(String, bool)> {
1229 let mut force_new_line_for_brace = false;
1230 // FIXME we'll lose any comments in between parts of the function decl, but
1231 // anyone who comments there probably deserves what they get.
1233 let where_clause = &generics.where_clause;
1235 let mut result = String::with_capacity(1024);
1236 // Vis unsafety abi.
1237 result.push_str(&*format_visibility(vis));
1239 if let ast::Constness::Const = constness {
1240 result.push_str("const ");
1243 result.push_str(::utils::format_unsafety(unsafety));
1245 if abi != abi::Abi::Rust {
1246 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1250 result.push_str("fn ");
1251 result.push_str(&ident.to_string());
1254 let generics_indent = indent + result.len();
1255 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1256 let generics_str = try_opt!(rewrite_generics(context,
1259 context.config.max_width,
1262 result.push_str(&generics_str);
1264 // Note that if the width and indent really matter, we'll re-layout the
1265 // return type later anyway.
1266 let ret_str = try_opt!(fd.output
1267 .rewrite(&context, context.config.max_width - indent.width(), indent));
1269 let multi_line_ret_str = ret_str.contains('\n');
1270 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1273 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1274 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1276 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1277 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1278 arg_indent = indent.block_indent(context.config);
1279 multi_line_budget = context.config.max_width - arg_indent.width();
1282 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1287 // Check if vertical layout was forced by compute_budget_for_args.
1288 if one_line_budget == 0 {
1289 if context.config.fn_args_paren_newline {
1291 result.push_str(&arg_indent.to_string(context.config));
1292 arg_indent = arg_indent + 1; // extra space for `(`
1295 result.push_str("(\n");
1296 result.push_str(&arg_indent.to_string(context.config));
1302 if multi_line_ret_str {
1303 one_line_budget = 0;
1306 // A conservative estimation, to goal is to be over all parens in generics
1307 let args_start = generics.ty_params
1309 .map_or(span.lo, |tp| end_typaram(tp));
1310 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1311 span_for_return(&fd.output).lo);
1312 let arg_str = try_opt!(rewrite_args(context,
1314 fd.get_self().as_ref(),
1322 let multi_line_arg_str = arg_str.contains('\n');
1324 let put_args_in_block = match context.config.fn_args_layout {
1325 FnArgLayoutStyle::Block => multi_line_arg_str,
1326 FnArgLayoutStyle::BlockAlways => true,
1328 } && fd.inputs.len() > 0;
1330 if put_args_in_block {
1331 arg_indent = indent.block_indent(context.config);
1333 result.push_str(&arg_indent.to_string(context.config));
1334 result.push_str(&arg_str);
1336 result.push_str(&indent.to_string(context.config));
1339 result.push_str(&arg_str);
1344 if !ret_str.is_empty() {
1345 let ret_should_indent = match context.config.fn_args_layout {
1346 // If our args are block layout then we surely must have space.
1347 FnArgLayoutStyle::Block if put_args_in_block => false,
1348 FnArgLayoutStyle::BlockAlways => false,
1350 // If we've already gone multi-line, or the return type would push
1351 // over the max width, then put the return type on a new line.
1352 result.contains("\n") || multi_line_ret_str ||
1353 result.len() + indent.width() + ret_str_len > context.config.max_width
1356 let ret_indent = if ret_should_indent {
1357 let indent = match context.config.fn_return_indent {
1358 ReturnIndent::WithWhereClause => indent + 4,
1359 // Aligning with non-existent args looks silly.
1360 _ if arg_str.is_empty() => {
1361 force_new_line_for_brace = true;
1364 // FIXME: we might want to check that using the arg indent
1365 // doesn't blow our budget, and if it does, then fallback to
1366 // the where clause indent.
1371 result.push_str(&indent.to_string(context.config));
1375 Indent::new(indent.width(), result.len())
1378 if multi_line_ret_str {
1379 // Now that we know the proper indent and width, we need to
1380 // re-layout the return type.
1382 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1383 let ret_str = try_opt!(fd.output
1384 .rewrite(context, budget, ret_indent));
1385 result.push_str(&ret_str);
1387 result.push_str(&ret_str);
1390 // Comment between return type and the end of the decl.
1391 let snippet_lo = fd.output.span().hi;
1392 if where_clause.predicates.is_empty() {
1393 let snippet_hi = span.hi;
1394 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1395 let snippet = snippet.trim();
1396 if !snippet.is_empty() {
1398 result.push_str(snippet);
1401 // FIXME it would be nice to catch comments between the return type
1402 // and the where clause, but we don't have a span for the where
1407 let should_compress_where = match context.config.where_density {
1408 Density::Compressed => !result.contains('\n') || put_args_in_block,
1409 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1411 } || (put_args_in_block && ret_str.is_empty());
1413 let where_density = if should_compress_where {
1420 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1421 let where_clause_str = try_opt!(rewrite_where_clause(context,
1424 context.config.fn_brace_style,
1432 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1433 !where_clause_str.contains('\n') {
1437 result.push_str(&where_clause_str);
1439 Some((result, force_new_line_for_brace))
1442 fn rewrite_args(context: &RewriteContext,
1444 explicit_self: Option<&ast::ExplicitSelf>,
1445 one_line_budget: usize,
1446 multi_line_budget: usize,
1452 let mut arg_item_strs = try_opt!(args.iter()
1453 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1454 .collect::<Option<Vec<_>>>());
1456 // Account for sugary self.
1457 // FIXME: the comment for the self argument is dropped. This is blocked
1458 // on rust issue #27522.
1460 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1461 .map_or(1, |self_str| {
1462 arg_item_strs[0] = self_str;
1466 // Comments between args.
1467 let mut arg_items = Vec::new();
1469 arg_items.push(ListItem::from_str(""));
1472 // FIXME(#21): if there are no args, there might still be a comment, but
1473 // without spans for the comment or parens, there is no chance of
1474 // getting it right. You also don't get to put a comment on self, unless
1476 if args.len() >= min_args || variadic {
1477 let comment_span_start = if min_args == 2 {
1478 let second_arg_start = if arg_has_pattern(&args[1]) {
1483 let reduced_span = mk_sp(span.lo, second_arg_start);
1485 context.codemap.span_after_last(reduced_span, ",")
1490 enum ArgumentKind<'a> {
1491 Regular(&'a ast::Arg),
1495 let variadic_arg = if variadic {
1496 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1497 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1498 Some(ArgumentKind::Variadic(variadic_start))
1503 let more_items = itemize_list(context.codemap,
1504 args[min_args - 1..]
1506 .map(ArgumentKind::Regular)
1507 .chain(variadic_arg),
1511 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1512 ArgumentKind::Variadic(start) => start,
1517 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1518 ArgumentKind::Variadic(start) => start + BytePos(3),
1523 ArgumentKind::Regular(..) => None,
1524 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1530 arg_items.extend(more_items);
1533 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1534 item.item = Some(arg);
1537 let indent = match context.config.fn_arg_indent {
1538 BlockIndentStyle::Inherit => indent,
1539 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1540 BlockIndentStyle::Visual => arg_indent,
1543 let tactic = definitive_tactic(&arg_items,
1544 context.config.fn_args_density.to_list_tactic(),
1546 let budget = match tactic {
1547 DefinitiveListTactic::Horizontal => one_line_budget,
1548 _ => multi_line_budget,
1551 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1553 let end_with_newline = match context.config.fn_args_layout {
1554 FnArgLayoutStyle::Block |
1555 FnArgLayoutStyle::BlockAlways => true,
1559 let fmt = ListFormatting {
1562 trailing_separator: SeparatorTactic::Never,
1565 ends_with_newline: end_with_newline,
1566 config: context.config,
1569 write_list(&arg_items, &fmt)
1572 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1573 if let ast::PatKind::Ident(_,
1575 node: ast::Ident { name: ast::Name(0u32), .. },
1585 fn compute_budgets_for_args(context: &RewriteContext,
1589 newline_brace: bool)
1590 -> Option<((usize, usize, Indent))> {
1591 // Try keeping everything on the same line.
1592 if !result.contains("\n") {
1593 // 3 = `() `, space is before ret_string.
1594 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1598 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1600 if one_line_budget > 0 {
1602 let multi_line_budget =
1603 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1605 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1609 // Didn't work. we must force vertical layout and put args on a newline.
1610 let new_indent = indent.block_indent(context.config);
1611 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1612 let max_space = context.config.max_width;
1613 if used_space <= max_space {
1614 Some((0, max_space - used_space, new_indent))
1616 // Whoops! bankrupt.
1621 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1622 match config.fn_brace_style {
1623 BraceStyle::AlwaysNextLine => true,
1624 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1629 fn rewrite_generics(context: &RewriteContext,
1630 generics: &ast::Generics,
1633 generics_offset: Indent,
1636 // FIXME: convert bounds to where clauses where they get too big or if
1637 // there is a where clause at all.
1638 let lifetimes: &[_] = &generics.lifetimes;
1639 let tys: &[_] = &generics.ty_params;
1640 if lifetimes.is_empty() && tys.is_empty() {
1641 return Some(String::new());
1644 let offset = match context.config.generics_indent {
1645 BlockIndentStyle::Inherit => offset,
1646 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1648 BlockIndentStyle::Visual => generics_offset + 1,
1651 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1652 // FIXME: might need to insert a newline if the generics are really long.
1654 // Strings for the generics.
1655 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1656 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1658 // Extract comments between generics.
1659 let lt_spans = lifetimes.iter().map(|l| {
1660 let hi = if l.bounds.is_empty() {
1663 l.bounds[l.bounds.len() - 1].span.hi
1665 mk_sp(l.lifetime.span.lo, hi)
1667 let ty_spans = tys.iter().map(span_for_ty_param);
1669 let items = itemize_list(context.codemap,
1670 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1674 // FIXME: don't clone
1675 |&(_, ref str)| str.clone(),
1676 context.codemap.span_after(span, "<"),
1678 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1680 Some(format!("<{}>", list_str))
1683 fn rewrite_trait_bounds(context: &RewriteContext,
1684 type_param_bounds: &ast::TyParamBounds,
1688 let bounds: &[_] = &type_param_bounds;
1690 if bounds.is_empty() {
1691 return Some(String::new());
1694 let bound_str = bounds.iter()
1695 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1696 .collect::<Vec<String>>()
1699 let mut result = String::new();
1700 result.push_str(": ");
1701 result.push_str(&bound_str);
1705 fn rewrite_where_clause(context: &RewriteContext,
1706 where_clause: &ast::WhereClause,
1708 brace_style: BraceStyle,
1713 allow_trailing_comma: bool,
1714 span_end: Option<BytePos>)
1716 if where_clause.predicates.is_empty() {
1717 return Some(String::new());
1720 let extra_indent = match context.config.where_indent {
1721 BlockIndentStyle::Inherit => Indent::empty(),
1722 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1725 let offset = match context.config.where_pred_indent {
1726 BlockIndentStyle::Inherit => indent + extra_indent,
1727 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1728 // 6 = "where ".len()
1729 BlockIndentStyle::Visual => indent + extra_indent + 6,
1731 // FIXME: if where_pred_indent != Visual, then the budgets below might
1732 // be out by a char or two.
1734 let budget = context.config.max_width - offset.width();
1735 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1736 // If we don't have the start of the next span, then use the end of the
1737 // predicates, but that means we miss comments.
1738 let len = where_clause.predicates.len();
1739 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1740 let span_end = span_end.unwrap_or(end_of_preds);
1741 let items = itemize_list(context.codemap,
1742 where_clause.predicates.iter(),
1744 |pred| span_for_where_pred(pred).lo,
1745 |pred| span_for_where_pred(pred).hi,
1746 |pred| pred.rewrite(&context, budget, offset),
1749 let item_vec = items.collect::<Vec<_>>();
1750 // FIXME: we don't need to collect here if the where_layout isn't
1751 // HorizontalVertical.
1752 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1753 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1755 let fmt = ListFormatting {
1758 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1761 ends_with_newline: true,
1762 config: context.config,
1764 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1766 let end_length = if terminator == "{" {
1767 // If the brace is on the next line we don't need to count it otherwise it needs two
1770 BraceStyle::AlwaysNextLine => 0,
1771 BraceStyle::PreferSameLine => 2,
1772 BraceStyle::SameLineWhere => 0,
1774 } else if terminator == "=" {
1779 if density == Density::Tall || preds_str.contains('\n') ||
1780 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1781 Some(format!("\n{}where {}",
1782 (indent + extra_indent).to_string(context.config),
1785 Some(format!(" where {}", preds_str))
1789 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1790 format!("{}{}{}", format_visibility(vis), item_name, ident)
1793 fn format_generics(context: &RewriteContext,
1794 generics: &ast::Generics,
1797 brace_style: BraceStyle,
1798 force_same_line_brace: bool,
1800 generics_offset: Indent,
1803 let mut result = try_opt!(rewrite_generics(context,
1806 context.config.max_width,
1810 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1811 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1812 let where_clause_str = try_opt!(rewrite_where_clause(context,
1813 &generics.where_clause,
1816 context.block_indent,
1822 result.push_str(&where_clause_str);
1823 if !force_same_line_brace &&
1824 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1826 result.push_str(&context.block_indent.to_string(context.config));
1830 result.push_str(opener);
1832 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1834 result.push_str(&context.block_indent.to_string(context.config));
1838 result.push_str(opener);