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 utils::{CodeMapSpanUtils, format_mutability, format_visibility, contains_skip, end_typaram,
15 wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
17 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
18 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
19 use comment::{FindUncommented, contains_comment};
20 use visitor::FmtVisitor;
21 use rewrite::{Rewrite, RewriteContext};
22 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use syntax::{ast, abi, ptr, codemap};
25 use syntax::codemap::{Span, BytePos, mk_sp};
26 use syntax::parse::token;
27 use syntax::ast::ImplItem;
29 // Statements of the form
30 // let pat: ty = init;
31 impl Rewrite for ast::Local {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33 let mut result = "let ".to_owned();
34 let pattern_offset = offset + result.len();
36 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
39 result.push_str(&pat_str);
41 // String that is placed within the assignment pattern and expression.
43 let mut infix = String::new();
45 if let Some(ref ty) = self.ty {
48 let indent = offset + last_line_width(&result) + 2;
49 let budget = try_opt!(width.checked_sub(indent.width() + 1));
50 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
53 infix.push_str(&rewrite);
56 if self.init.is_some() {
63 result.push_str(&infix);
65 if let Some(ref ex) = self.init {
66 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68 // 1 = trailing semicolon;
70 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
78 impl<'a> FmtVisitor<'a> {
79 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
80 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
81 self.buffer.push_str(&abi_str);
83 let snippet = self.snippet(span);
84 let brace_pos = snippet.find_uncommented("{").unwrap();
86 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
87 self.buffer.push_str("{");
89 // FIXME: this skips comments between the extern keyword and the opening
91 self.last_pos = span.lo + BytePos(brace_pos as u32);
92 self.block_indent = self.block_indent.block_indent(self.config);
94 for item in &fm.items {
95 self.format_foreign_item(&*item);
98 self.block_indent = self.block_indent.block_unindent(self.config);
99 self.format_missing_with_indent(span.hi - BytePos(1));
102 self.buffer.push_str("}");
103 self.last_pos = span.hi;
106 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
107 self.format_missing_with_indent(item.span.lo);
108 // Drop semicolon or it will be interpreted as comment.
109 // FIXME: this may be a faulty span from libsyntax.
110 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
113 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
114 let indent = self.block_indent;
115 let rewrite = rewrite_fn_base(&self.get_context(),
120 ast::Unsafety::Normal,
121 ast::Constness::NotConst,
122 // These are not actually rust functions,
123 // but we format them as such.
131 Some((new_fn, _)) => {
132 self.buffer.push_str(&new_fn);
133 self.buffer.push_str(";");
135 None => self.format_missing(item.span.hi),
138 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
139 // FIXME(#21): we're dropping potential comments in between the
140 // function keywords here.
141 let vis = format_visibility(&item.vis);
142 let mut_str = if is_mutable {
147 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
148 let offset = self.block_indent + prefix.len();
150 let width = self.config.max_width - offset.width() - 1;
151 let rewrite = ty.rewrite(&self.get_context(), width, offset);
155 self.buffer.push_str(&prefix);
156 self.buffer.push_str(&result);
157 self.buffer.push_str(";");
159 None => self.format_missing(item.span.hi),
164 self.last_pos = item.span.hi;
167 pub fn rewrite_fn(&mut self,
171 generics: &ast::Generics,
172 unsafety: ast::Unsafety,
173 constness: ast::Constness,
175 vis: &ast::Visibility,
179 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
180 let context = self.get_context();
182 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
183 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
184 !context.config.fn_empty_single_line;
186 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
199 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
200 newline_brace = false;
201 } else if force_newline_brace {
202 newline_brace = true;
205 // Prepare for the function body by possibly adding a newline and
207 // FIXME we'll miss anything between the end of the signature and the
208 // start of the body, but we need more spans from the compiler to solve
212 result.push_str(&indent.to_string(self.config));
217 self.single_line_fn(&result, block).or_else(|| Some(result))
220 pub fn rewrite_required_fn(&mut self,
223 sig: &ast::MethodSig,
226 // Drop semicolon or it will be interpreted as comment.
227 let span = mk_sp(span.lo, span.hi - BytePos(1));
228 let context = self.get_context();
230 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
238 &ast::Visibility::Inherited,
243 // Re-attach semicolon
249 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
250 if fn_str.contains('\n') {
254 let codemap = self.get_context().codemap;
256 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
257 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
258 return Some(format!("{}{{}}", fn_str));
261 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
263 if let Some(ref e) = block.expr {
264 let suffix = if semicolon_for_expr(e) {
270 e.rewrite(&self.get_context(),
271 self.config.max_width - self.block_indent.width(),
274 .or_else(|| Some(self.snippet(e.span)))
275 } else if let Some(ref stmt) = block.stmts.first() {
276 stmt.rewrite(&self.get_context(),
277 self.config.max_width - self.block_indent.width(),
284 if let Some(res) = rewrite {
285 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
286 if !res.contains('\n') && width <= self.config.max_width {
287 return Some(format!("{}{{ {} }}", fn_str, res));
295 pub fn visit_enum(&mut self,
297 vis: &ast::Visibility,
298 enum_def: &ast::EnumDef,
299 generics: &ast::Generics,
301 self.buffer.push_str(&format_header("enum ", ident, vis));
303 let enum_snippet = self.snippet(span);
304 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
305 let generics_str = format_generics(&self.get_context(),
309 self.config.item_brace_style,
310 enum_def.variants.is_empty(),
312 self.block_indent.block_indent(self.config),
313 mk_sp(span.lo, body_start))
315 self.buffer.push_str(&generics_str);
317 self.last_pos = body_start;
319 self.block_indent = self.block_indent.block_indent(self.config);
320 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
322 Some(ref body_str) => self.buffer.push_str(&body_str),
323 None => self.format_missing(span.hi - BytePos(1)),
325 self.block_indent = self.block_indent.block_unindent(self.config);
327 if variant_list.is_some() {
328 self.buffer.push_str(&self.block_indent.to_string(self.config));
330 self.buffer.push_str("}");
331 self.last_pos = span.hi;
334 // Format the body of an enum definition
335 fn format_variant_list(&self,
336 enum_def: &ast::EnumDef,
340 if enum_def.variants.is_empty() {
343 let mut result = String::with_capacity(1024);
345 let indentation = self.block_indent.to_string(self.config);
346 result.push_str(&indentation);
348 let items = itemize_list(self.codemap,
349 enum_def.variants.iter(),
352 if !f.node.attrs.is_empty() {
353 f.node.attrs[0].span.lo
359 |f| self.format_variant(f),
363 let budget = self.config.max_width - self.block_indent.width() - 2;
364 let fmt = ListFormatting {
365 tactic: DefinitiveListTactic::Vertical,
367 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
368 indent: self.block_indent,
370 ends_with_newline: true,
374 let list = try_opt!(write_list(items, &fmt));
375 result.push_str(&list);
380 // Variant of an enum.
381 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
382 if contains_skip(&field.node.attrs) {
383 let lo = field.node.attrs[0].span.lo;
384 let span = mk_sp(lo, field.span.hi);
385 return Some(self.snippet(span));
388 let indent = self.block_indent;
389 let mut result = try_opt!(field.node
391 .rewrite(&self.get_context(),
392 self.config.max_width - indent.width(),
394 if !result.is_empty() {
396 result.push_str(&indent.to_string(self.config));
399 let context = self.get_context();
400 let variant_body = match field.node.data {
401 ast::VariantData::Tuple(..) |
402 ast::VariantData::Struct(..) => {
403 // FIXME: Should limit the width, as we have a trailing comma
404 format_struct(&context,
407 &ast::Visibility::Inherited,
412 Some(self.config.struct_variant_width))
414 ast::VariantData::Unit(..) => {
415 let tag = if let Some(ref expr) = field.node.disr_expr {
416 format!("{} = {}", field.node.name, self.snippet(expr.span))
418 field.node.name.to_string()
422 self.config.max_width,
423 self.config.max_width - indent.width(),
428 if let Some(variant_str) = variant_body {
429 result.push_str(&variant_str);
437 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
438 if let ast::ItemKind::Impl(unsafety,
443 ref items) = item.node {
444 let mut result = String::new();
445 result.push_str(&*format_visibility(&item.vis));
446 result.push_str(format_unsafety(unsafety));
447 result.push_str("impl");
449 let lo = context.codemap.span_after(item.span, "impl");
450 let hi = match *trait_ref {
451 Some(ref tr) => tr.path.span.lo,
452 None => self_ty.span.lo,
454 let generics_str = try_opt!(rewrite_generics(context,
457 context.config.max_width,
458 offset + result.len(),
460 result.push_str(&generics_str);
462 // FIXME might need to linebreak in the impl header, here would be a
465 if polarity == ast::ImplPolarity::Negative {
466 result.push_str("!");
468 if let Some(ref trait_ref) = *trait_ref {
469 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
470 let indent = offset + result.len();
471 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
472 result.push_str(" for ");
475 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
476 let indent = offset + result.len();
477 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
479 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
480 let where_clause_str = try_opt!(rewrite_where_clause(context,
481 &generics.where_clause,
483 context.config.item_brace_style,
484 context.block_indent,
486 context.config.where_density,
491 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
492 result.push_str(&where_clause_str);
493 if where_clause_str.contains('\n') {
494 let white_space = offset.to_string(context.config);
495 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
497 result.push_str(" {}");
502 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
504 let width = context.block_indent.width() + context.config.tab_spaces - 1;
505 let where_indent = Indent::new(0, width);
506 result.push_str(&where_indent.to_string(context.config));
508 result.push_str(&where_clause_str);
510 match context.config.item_brace_style {
511 BraceStyle::AlwaysNextLine => result.push('\n'),
512 BraceStyle::PreferSameLine => result.push(' '),
513 BraceStyle::SameLineWhere => {
514 if !where_clause_str.is_empty() {
516 result.push_str(&offset.to_string(context.config));
525 let snippet = context.snippet(item.span);
526 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
528 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
529 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
530 visitor.block_indent = context.block_indent.block_indent(context.config);
531 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
534 visitor.visit_impl_item(&item);
537 visitor.format_missing(item.span.hi - BytePos(1));
539 let inner_indent_str = visitor.block_indent.to_string(context.config);
540 let outer_indent_str = context.block_indent.to_string(context.config);
543 result.push_str(&inner_indent_str);
544 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
546 result.push_str(&outer_indent_str);
549 if result.chars().last().unwrap() == '{' {
560 fn is_impl_single_line(context: &RewriteContext,
561 items: &Vec<ImplItem>,
563 where_clause_str: &str,
566 let snippet = context.snippet(item.span);
567 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
569 Some(context.config.impl_empty_single_line && items.is_empty() &&
570 result.len() + where_clause_str.len() <= context.config.max_width &&
571 !contains_comment(&snippet[open_pos..]))
574 pub fn format_struct(context: &RewriteContext,
577 vis: &ast::Visibility,
578 struct_def: &ast::VariantData,
579 generics: Option<&ast::Generics>,
582 one_line_width: Option<usize>)
585 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
586 ast::VariantData::Tuple(ref fields, _) => {
587 format_tuple_struct(context,
596 ast::VariantData::Struct(ref fields, _) => {
597 format_struct_struct(context,
610 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
611 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
613 let mut result = String::new();
614 let header = format!("{}{}trait {}",
615 format_visibility(&item.vis),
616 format_unsafety(unsafety),
619 result.push_str(&header);
621 let body_lo = context.codemap.span_after(item.span, "{");
623 let generics_str = try_opt!(rewrite_generics(context,
626 context.config.max_width,
627 offset + result.len(),
628 mk_sp(item.span.lo, body_lo)));
629 result.push_str(&generics_str);
631 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
634 context.config.max_width));
635 // If the trait, generics, and trait bound cannot fit on the same line,
636 // put the trait bounds on an indented new line
637 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
638 context.config.ideal_width {
640 let width = context.block_indent.width() + context.config.tab_spaces;
641 let trait_indent = Indent::new(0, width);
642 result.push_str(&trait_indent.to_string(context.config));
644 result.push_str(&trait_bound_str);
646 let has_body = !trait_items.is_empty();
649 if (context.config.where_density == Density::Compressed &&
650 (!result.contains('\n') ||
651 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
652 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
653 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
654 !result.contains('\n')) {
660 let where_budget = try_opt!(context.config
662 .checked_sub(last_line_width(&result)));
663 let where_clause_str = try_opt!(rewrite_where_clause(context,
664 &generics.where_clause,
666 context.config.item_brace_style,
667 context.block_indent,
673 // If the where clause cannot fit on the same line,
674 // put the where clause on a new line
675 if !where_clause_str.contains('\n') &&
676 last_line_width(&result) + where_clause_str.len() + offset.width() >
677 context.config.ideal_width {
679 let width = context.block_indent.width() + context.config.tab_spaces - 1;
680 let where_indent = Indent::new(0, width);
681 result.push_str(&where_indent.to_string(context.config));
683 result.push_str(&where_clause_str);
685 match context.config.item_brace_style {
686 BraceStyle::AlwaysNextLine => {
688 result.push_str(&offset.to_string(context.config));
690 BraceStyle::PreferSameLine => result.push(' '),
691 BraceStyle::SameLineWhere => {
692 if !where_clause_str.is_empty() &&
693 (trait_items.len() > 0 || result.contains('\n')) {
695 result.push_str(&offset.to_string(context.config));
703 let snippet = context.snippet(item.span);
704 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
706 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
707 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
708 visitor.block_indent = context.block_indent.block_indent(context.config);
709 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
711 for item in trait_items {
712 visitor.visit_trait_item(&item);
715 visitor.format_missing(item.span.hi - BytePos(1));
717 let inner_indent_str = visitor.block_indent.to_string(context.config);
718 let outer_indent_str = context.block_indent.to_string(context.config);
721 result.push_str(&inner_indent_str);
722 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
724 result.push_str(&outer_indent_str);
725 } else if result.contains('\n') {
736 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
737 format!("{};", format_header(item_name, ident, vis))
740 fn format_struct_struct(context: &RewriteContext,
743 vis: &ast::Visibility,
744 fields: &[ast::StructField],
745 generics: Option<&ast::Generics>,
748 one_line_width: Option<usize>)
750 let mut result = String::with_capacity(1024);
752 let header_str = format_header(item_name, ident, vis);
753 result.push_str(&header_str);
755 let body_lo = context.codemap.span_after(span, "{");
757 let generics_str = match generics {
759 try_opt!(format_generics(context,
763 context.config.item_brace_style,
766 offset + header_str.len(),
767 mk_sp(span.lo, body_lo)))
770 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
771 format!("\n{}{{", context.block_indent.to_string(context.config))
777 result.push_str(&generics_str);
779 // FIXME(#919): properly format empty structs and their comments.
780 if fields.is_empty() {
781 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
785 let item_indent = offset.block_indent(context.config);
787 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
789 let items = itemize_list(context.codemap,
793 // Include attributes and doc comments, if present
794 if !field.attrs.is_empty() {
795 field.attrs[0].span.lo
800 |field| field.ty.span.hi,
801 |field| field.rewrite(context, item_budget, item_indent),
802 context.codemap.span_after(span, "{"),
804 .collect::<Vec<_>>();
806 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
808 let tactic = match one_line_width {
809 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
810 None => DefinitiveListTactic::Vertical,
813 let fmt = ListFormatting {
816 trailing_separator: context.config.struct_trailing_comma,
819 ends_with_newline: true,
820 config: context.config,
822 let items_str = try_opt!(write_list(&items, &fmt));
823 if one_line_width.is_some() && !items_str.contains('\n') {
824 Some(format!("{} {} }}", result, items_str))
826 Some(format!("{}\n{}{}\n{}}}",
828 offset.block_indent(context.config).to_string(context.config),
830 offset.to_string(context.config)))
834 fn format_tuple_struct(context: &RewriteContext,
837 vis: &ast::Visibility,
838 fields: &[ast::StructField],
839 generics: Option<&ast::Generics>,
843 let mut result = String::with_capacity(1024);
845 let header_str = format_header(item_name, ident, vis);
846 result.push_str(&header_str);
848 // FIXME(#919): don't lose comments on empty tuple structs.
849 let body_lo = if fields.is_empty() {
855 let where_clause_str = match generics {
856 Some(ref generics) => {
857 let generics_str = try_opt!(rewrite_generics(context,
860 context.config.max_width,
861 offset + header_str.len(),
862 mk_sp(span.lo, body_lo)));
863 result.push_str(&generics_str);
865 let where_budget = try_opt!(context.config
867 .checked_sub(last_line_width(&result)));
868 try_opt!(rewrite_where_clause(context,
869 &generics.where_clause,
871 context.config.item_brace_style,
872 context.block_indent,
879 None => "".to_owned(),
883 let item_indent = context.block_indent + result.len();
885 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
887 let items = itemize_list(context.codemap,
891 // Include attributes and doc comments, if present
892 if !field.attrs.is_empty() {
893 field.attrs[0].span.lo
898 |field| field.ty.span.hi,
899 |field| field.rewrite(context, item_budget, item_indent),
900 context.codemap.span_after(span, "("),
902 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
903 result.push_str(&body);
906 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
907 (result.contains('\n') ||
908 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
909 context.config.max_width) {
910 // We need to put the where clause on a new line, but we didn'to_string
911 // know that earlier, so the where clause will not be indented properly.
913 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
914 .to_string(context.config));
916 result.push_str(&where_clause_str);
921 pub fn rewrite_type_alias(context: &RewriteContext,
925 generics: &ast::Generics,
926 vis: &ast::Visibility,
929 let mut result = String::new();
931 result.push_str(&format_visibility(&vis));
932 result.push_str("type ");
933 result.push_str(&ident.to_string());
935 let generics_indent = indent + result.len();
936 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
937 let generics_width = context.config.max_width - " =".len();
938 let generics_str = try_opt!(rewrite_generics(context,
945 result.push_str(&generics_str);
947 let where_budget = try_opt!(context.config
949 .checked_sub(last_line_width(&result)));
950 let where_clause_str = try_opt!(rewrite_where_clause(context,
951 &generics.where_clause,
953 context.config.item_brace_style,
956 context.config.where_density,
960 result.push_str(&where_clause_str);
961 result.push_str(" = ");
963 let line_width = last_line_width(&result);
964 // This checked_sub may fail as the extra space after '=' is not taken into account
965 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
966 let budget = context.config
968 .checked_sub(indent.width() + line_width + ";".len())
970 let type_indent = indent + line_width;
971 // Try to fit the type on the same line
972 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
974 // The line was too short, try to put the type on the next line
976 // Remove the space after '='
978 let type_indent = indent.block_indent(context.config);
980 result.push_str(&type_indent.to_string(context.config));
981 let budget = try_opt!(context.config
983 .checked_sub(type_indent.width() + ";".len()));
984 ty.rewrite(context, budget, type_indent)
986 result.push_str(&ty_str);
987 result.push_str(";");
991 impl Rewrite for ast::StructField {
992 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
993 if contains_skip(&self.attrs) {
994 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
995 return wrap_str(span, context.config.max_width, width, offset);
998 let name = self.ident;
999 let vis = format_visibility(&self.vis);
1000 let mut attr_str = try_opt!(self.attrs
1001 .rewrite(context, context.config.max_width - offset.width(), offset));
1002 if !attr_str.is_empty() {
1003 attr_str.push('\n');
1004 attr_str.push_str(&offset.to_string(context.config));
1007 let result = match name {
1008 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1009 None => format!("{}{}", attr_str, vis),
1012 let last_line_width = last_line_width(&result);
1013 let budget = try_opt!(width.checked_sub(last_line_width));
1014 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1015 Some(result + &rewrite)
1019 pub fn rewrite_static(prefix: &str,
1020 vis: &ast::Visibility,
1023 mutability: ast::Mutability,
1024 expr_opt: Option<&ptr::P<ast::Expr>>,
1025 context: &RewriteContext)
1027 let prefix = format!("{}{} {}{}: ",
1028 format_visibility(vis),
1030 format_mutability(mutability),
1033 let ty_str = try_opt!(ty.rewrite(context,
1034 context.config.max_width - context.block_indent.width() -
1036 context.block_indent));
1038 if let Some(ref expr) = expr_opt {
1039 let lhs = format!("{}{} =", prefix, ty_str);
1041 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1042 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1045 let lhs = format!("{}{};", prefix, ty_str);
1050 pub fn rewrite_associated_type(ident: ast::Ident,
1051 ty_opt: Option<&ptr::P<ast::Ty>>,
1052 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1053 context: &RewriteContext,
1056 let prefix = format!("type {}", ident);
1058 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1059 let bounds: &[_] = &ty_param_bounds;
1060 let bound_str = bounds.iter()
1061 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1062 .collect::<Vec<String>>()
1064 if bounds.len() > 0 {
1065 format!(": {}", bound_str)
1073 if let Some(ty) = ty_opt {
1074 let ty_str = try_opt!(ty.rewrite(context,
1075 context.config.max_width - context.block_indent.width() -
1078 context.block_indent));
1079 Some(format!("{} = {};", prefix, ty_str))
1081 Some(format!("{}{};", prefix, type_bounds_str))
1085 impl Rewrite for ast::FunctionRetTy {
1086 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1088 ast::FunctionRetTy::Default(_) => Some(String::new()),
1089 ast::FunctionRetTy::None(_) => {
1091 Some("-> !".to_owned())
1096 ast::FunctionRetTy::Ty(ref ty) => {
1097 let inner_width = try_opt!(width.checked_sub(3));
1098 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1104 impl Rewrite for ast::Arg {
1105 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1106 if is_named_arg(self) {
1107 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1109 if self.ty.node != ast::TyKind::Infer {
1110 result.push_str(": ");
1111 let max_width = try_opt!(width.checked_sub(result.len()));
1112 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1113 result.push_str(&ty_str);
1118 self.ty.rewrite(context, width, offset)
1123 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1125 context: &RewriteContext)
1127 match explicit_self.node {
1128 ast::SelfKind::Region(lt, m) => {
1129 let mut_str = format_mutability(m);
1133 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1134 Some(format!("&{} {}self", lifetime_str, mut_str))
1136 None => Some(format!("&{}self", mut_str)),
1139 ast::SelfKind::Explicit(ref ty, _) => {
1140 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1142 let mutability = explicit_self_mutability(&args[0]);
1143 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1145 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1147 ast::SelfKind::Value(_) => {
1148 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1150 let mutability = explicit_self_mutability(&args[0]);
1152 Some(format!("{}self", format_mutability(mutability)))
1157 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1158 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1159 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1160 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1167 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1168 if is_named_arg(arg) {
1175 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1177 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1178 _ => arg.ty.span.hi,
1182 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1183 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1184 ident.node != token::keywords::Invalid.ident()
1190 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1192 ast::FunctionRetTy::None(ref span) |
1193 ast::FunctionRetTy::Default(ref span) => span.clone(),
1194 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1198 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1199 // Note that ty.span is the span for ty.ident, not the whole item.
1200 let lo = ty.span.lo;
1201 if let Some(ref def) = ty.default {
1202 return mk_sp(lo, def.span.hi);
1204 if ty.bounds.is_empty() {
1207 let hi = match ty.bounds[ty.bounds.len() - 1] {
1208 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1209 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1214 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1216 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1217 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1218 ast::WherePredicate::EqPredicate(ref p) => p.span,
1222 // Return type is (result, force_new_line_for_brace)
1223 fn rewrite_fn_base(context: &RewriteContext,
1227 generics: &ast::Generics,
1228 unsafety: ast::Unsafety,
1229 constness: ast::Constness,
1231 vis: &ast::Visibility,
1233 newline_brace: bool,
1235 -> Option<(String, bool)> {
1236 let mut force_new_line_for_brace = false;
1237 // FIXME we'll lose any comments in between parts of the function decl, but
1238 // anyone who comments there probably deserves what they get.
1240 let where_clause = &generics.where_clause;
1242 let mut result = String::with_capacity(1024);
1243 // Vis unsafety abi.
1244 result.push_str(&*format_visibility(vis));
1246 if let ast::Constness::Const = constness {
1247 result.push_str("const ");
1250 result.push_str(::utils::format_unsafety(unsafety));
1252 if abi != abi::Abi::Rust {
1253 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1257 result.push_str("fn ");
1258 result.push_str(&ident.to_string());
1261 let generics_indent = indent + result.len();
1262 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1263 let generics_str = try_opt!(rewrite_generics(context,
1266 context.config.max_width,
1269 result.push_str(&generics_str);
1271 // Note that if the width and indent really matter, we'll re-layout the
1272 // return type later anyway.
1273 let ret_str = try_opt!(fd.output
1274 .rewrite(&context, context.config.max_width - indent.width(), indent));
1276 let multi_line_ret_str = ret_str.contains('\n');
1277 let ret_str_len = if multi_line_ret_str {
1284 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1285 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1287 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1288 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1289 arg_indent = indent.block_indent(context.config);
1290 multi_line_budget = context.config.max_width - arg_indent.width();
1293 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1298 // Check if vertical layout was forced by compute_budget_for_args.
1299 if one_line_budget == 0 {
1300 if context.config.fn_args_paren_newline {
1302 result.push_str(&arg_indent.to_string(context.config));
1303 arg_indent = arg_indent + 1; // extra space for `(`
1306 result.push_str("(\n");
1307 result.push_str(&arg_indent.to_string(context.config));
1313 if multi_line_ret_str {
1314 one_line_budget = 0;
1317 // A conservative estimation, to goal is to be over all parens in generics
1318 let args_start = generics.ty_params
1320 .map_or(span.lo, |tp| end_typaram(tp));
1321 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1322 span_for_return(&fd.output).lo);
1323 let arg_str = try_opt!(rewrite_args(context,
1325 fd.get_self().as_ref(),
1333 let multi_line_arg_str = arg_str.contains('\n');
1335 let put_args_in_block = match context.config.fn_args_layout {
1336 FnArgLayoutStyle::Block => multi_line_arg_str,
1337 FnArgLayoutStyle::BlockAlways => true,
1339 } && fd.inputs.len() > 0;
1341 if put_args_in_block {
1342 arg_indent = indent.block_indent(context.config);
1344 result.push_str(&arg_indent.to_string(context.config));
1345 result.push_str(&arg_str);
1347 result.push_str(&indent.to_string(context.config));
1350 result.push_str(&arg_str);
1355 if !ret_str.is_empty() {
1356 let ret_should_indent = match context.config.fn_args_layout {
1357 // If our args are block layout then we surely must have space.
1358 FnArgLayoutStyle::Block if put_args_in_block => false,
1359 FnArgLayoutStyle::BlockAlways => false,
1361 // If we've already gone multi-line, or the return type would push
1362 // over the max width, then put the return type on a new line.
1363 result.contains("\n") || multi_line_ret_str ||
1364 result.len() + indent.width() + ret_str_len > context.config.max_width
1367 let ret_indent = if ret_should_indent {
1368 let indent = match context.config.fn_return_indent {
1369 ReturnIndent::WithWhereClause => indent + 4,
1370 // Aligning with non-existent args looks silly.
1371 _ if arg_str.is_empty() => {
1372 force_new_line_for_brace = true;
1375 // FIXME: we might want to check that using the arg indent
1376 // doesn't blow our budget, and if it does, then fallback to
1377 // the where clause indent.
1382 result.push_str(&indent.to_string(context.config));
1386 Indent::new(indent.width(), result.len())
1389 if multi_line_ret_str {
1390 // Now that we know the proper indent and width, we need to
1391 // re-layout the return type.
1393 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1394 let ret_str = try_opt!(fd.output
1395 .rewrite(context, budget, ret_indent));
1396 result.push_str(&ret_str);
1398 result.push_str(&ret_str);
1401 // Comment between return type and the end of the decl.
1402 let snippet_lo = fd.output.span().hi;
1403 if where_clause.predicates.is_empty() {
1404 let snippet_hi = span.hi;
1405 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1406 let snippet = snippet.trim();
1407 if !snippet.is_empty() {
1409 result.push_str(snippet);
1412 // FIXME it would be nice to catch comments between the return type
1413 // and the where clause, but we don't have a span for the where
1418 let should_compress_where = match context.config.where_density {
1419 Density::Compressed => !result.contains('\n') || put_args_in_block,
1420 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1422 } || (put_args_in_block && ret_str.is_empty());
1424 let where_density = if should_compress_where {
1431 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1432 let where_clause_str = try_opt!(rewrite_where_clause(context,
1435 context.config.fn_brace_style,
1443 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1444 !where_clause_str.contains('\n') {
1448 result.push_str(&where_clause_str);
1450 Some((result, force_new_line_for_brace))
1453 fn rewrite_args(context: &RewriteContext,
1455 explicit_self: Option<&ast::ExplicitSelf>,
1456 one_line_budget: usize,
1457 multi_line_budget: usize,
1463 let mut arg_item_strs = try_opt!(args.iter()
1464 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1465 .collect::<Option<Vec<_>>>());
1467 // Account for sugary self.
1468 // FIXME: the comment for the self argument is dropped. This is blocked
1469 // on rust issue #27522.
1471 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1472 .map_or(1, |self_str| {
1473 arg_item_strs[0] = self_str;
1477 // Comments between args.
1478 let mut arg_items = Vec::new();
1480 arg_items.push(ListItem::from_str(""));
1483 // FIXME(#21): if there are no args, there might still be a comment, but
1484 // without spans for the comment or parens, there is no chance of
1485 // getting it right. You also don't get to put a comment on self, unless
1487 if args.len() >= min_args || variadic {
1488 let comment_span_start = if min_args == 2 {
1489 let second_arg_start = if arg_has_pattern(&args[1]) {
1494 let reduced_span = mk_sp(span.lo, second_arg_start);
1496 context.codemap.span_after_last(reduced_span, ",")
1501 enum ArgumentKind<'a> {
1502 Regular(&'a ast::Arg),
1506 let variadic_arg = if variadic {
1507 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1508 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1509 Some(ArgumentKind::Variadic(variadic_start))
1514 let more_items = itemize_list(context.codemap,
1515 args[min_args - 1..]
1517 .map(ArgumentKind::Regular)
1518 .chain(variadic_arg),
1522 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1523 ArgumentKind::Variadic(start) => start,
1528 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1529 ArgumentKind::Variadic(start) => start + BytePos(3),
1534 ArgumentKind::Regular(..) => None,
1535 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1541 arg_items.extend(more_items);
1544 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1545 item.item = Some(arg);
1548 let indent = match context.config.fn_arg_indent {
1549 BlockIndentStyle::Inherit => indent,
1550 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1551 BlockIndentStyle::Visual => arg_indent,
1554 let tactic = definitive_tactic(&arg_items,
1555 context.config.fn_args_density.to_list_tactic(),
1557 let budget = match tactic {
1558 DefinitiveListTactic::Horizontal => one_line_budget,
1559 _ => multi_line_budget,
1562 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1564 let end_with_newline = match context.config.fn_args_layout {
1565 FnArgLayoutStyle::Block |
1566 FnArgLayoutStyle::BlockAlways => true,
1570 let fmt = ListFormatting {
1573 trailing_separator: SeparatorTactic::Never,
1576 ends_with_newline: end_with_newline,
1577 config: context.config,
1580 write_list(&arg_items, &fmt)
1583 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1584 if let ast::PatKind::Ident(_,
1586 node: ast::Ident { name: ast::Name(0u32), .. },
1596 fn compute_budgets_for_args(context: &RewriteContext,
1600 newline_brace: bool)
1601 -> Option<((usize, usize, Indent))> {
1602 // Try keeping everything on the same line.
1603 if !result.contains("\n") {
1604 // 3 = `() `, space is before ret_string.
1605 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1609 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1611 if one_line_budget > 0 {
1613 let multi_line_budget =
1614 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1616 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1620 // Didn't work. we must force vertical layout and put args on a newline.
1621 let new_indent = indent.block_indent(context.config);
1622 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1623 let max_space = context.config.max_width;
1624 if used_space <= max_space {
1625 Some((0, max_space - used_space, new_indent))
1627 // Whoops! bankrupt.
1632 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1633 match config.fn_brace_style {
1634 BraceStyle::AlwaysNextLine => true,
1635 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1640 fn rewrite_generics(context: &RewriteContext,
1641 generics: &ast::Generics,
1644 generics_offset: Indent,
1647 // FIXME: convert bounds to where clauses where they get too big or if
1648 // there is a where clause at all.
1649 let lifetimes: &[_] = &generics.lifetimes;
1650 let tys: &[_] = &generics.ty_params;
1651 if lifetimes.is_empty() && tys.is_empty() {
1652 return Some(String::new());
1655 let offset = match context.config.generics_indent {
1656 BlockIndentStyle::Inherit => offset,
1657 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1659 BlockIndentStyle::Visual => generics_offset + 1,
1662 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1663 // FIXME: might need to insert a newline if the generics are really long.
1665 // Strings for the generics.
1666 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1667 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1669 // Extract comments between generics.
1670 let lt_spans = lifetimes.iter().map(|l| {
1671 let hi = if l.bounds.is_empty() {
1674 l.bounds[l.bounds.len() - 1].span.hi
1676 mk_sp(l.lifetime.span.lo, hi)
1678 let ty_spans = tys.iter().map(span_for_ty_param);
1680 let items = itemize_list(context.codemap,
1681 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1685 // FIXME: don't clone
1686 |&(_, ref str)| str.clone(),
1687 context.codemap.span_after(span, "<"),
1689 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1691 Some(format!("<{}>", list_str))
1694 fn rewrite_trait_bounds(context: &RewriteContext,
1695 type_param_bounds: &ast::TyParamBounds,
1699 let bounds: &[_] = &type_param_bounds;
1701 if bounds.is_empty() {
1702 return Some(String::new());
1705 let bound_str = bounds.iter()
1706 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1707 .collect::<Vec<String>>()
1710 let mut result = String::new();
1711 result.push_str(": ");
1712 result.push_str(&bound_str);
1716 fn rewrite_where_clause(context: &RewriteContext,
1717 where_clause: &ast::WhereClause,
1719 brace_style: BraceStyle,
1724 allow_trailing_comma: bool,
1725 span_end: Option<BytePos>)
1727 if where_clause.predicates.is_empty() {
1728 return Some(String::new());
1731 let extra_indent = match context.config.where_indent {
1732 BlockIndentStyle::Inherit => Indent::empty(),
1733 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1736 let offset = match context.config.where_pred_indent {
1737 BlockIndentStyle::Inherit => indent + extra_indent,
1738 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1739 // 6 = "where ".len()
1740 BlockIndentStyle::Visual => indent + extra_indent + 6,
1742 // FIXME: if where_pred_indent != Visual, then the budgets below might
1743 // be out by a char or two.
1745 let budget = context.config.max_width - offset.width();
1746 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1747 // If we don't have the start of the next span, then use the end of the
1748 // predicates, but that means we miss comments.
1749 let len = where_clause.predicates.len();
1750 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1751 let span_end = span_end.unwrap_or(end_of_preds);
1752 let items = itemize_list(context.codemap,
1753 where_clause.predicates.iter(),
1755 |pred| span_for_where_pred(pred).lo,
1756 |pred| span_for_where_pred(pred).hi,
1757 |pred| pred.rewrite(&context, budget, offset),
1760 let item_vec = items.collect::<Vec<_>>();
1761 // FIXME: we don't need to collect here if the where_layout isn't
1762 // HorizontalVertical.
1763 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1764 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1766 let fmt = ListFormatting {
1769 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1772 ends_with_newline: true,
1773 config: context.config,
1775 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1777 let end_length = if terminator == "{" {
1778 // If the brace is on the next line we don't need to count it otherwise it needs two
1781 BraceStyle::AlwaysNextLine => 0,
1782 BraceStyle::PreferSameLine => 2,
1783 BraceStyle::SameLineWhere => 0,
1785 } else if terminator == "=" {
1790 if density == Density::Tall || preds_str.contains('\n') ||
1791 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1792 Some(format!("\n{}where {}",
1793 (indent + extra_indent).to_string(context.config),
1796 Some(format!(" where {}", preds_str))
1800 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1801 format!("{}{}{}", format_visibility(vis), item_name, ident)
1804 fn format_generics(context: &RewriteContext,
1805 generics: &ast::Generics,
1808 brace_style: BraceStyle,
1809 force_same_line_brace: bool,
1811 generics_offset: Indent,
1814 let mut result = try_opt!(rewrite_generics(context,
1817 context.config.max_width,
1821 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1822 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1823 let where_clause_str = try_opt!(rewrite_where_clause(context,
1824 &generics.where_clause,
1827 context.block_indent,
1833 result.push_str(&where_clause_str);
1834 if !force_same_line_brace &&
1835 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1837 result.push_str(&context.block_indent.to_string(context.config));
1841 result.push_str(opener);
1843 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1845 result.push_str(&context.block_indent.to_string(context.config));
1849 result.push_str(opener);