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, 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;
69 result = try_opt!(rewrite_assign_rhs(&context,
73 context.block_indent));
81 impl<'a> FmtVisitor<'a> {
82 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
83 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
84 self.buffer.push_str(&abi_str);
86 let snippet = self.snippet(span);
87 let brace_pos = snippet.find_uncommented("{").unwrap();
89 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
90 self.buffer.push_str("{");
92 // FIXME: this skips comments between the extern keyword and the opening
94 self.last_pos = span.lo + BytePos(brace_pos as u32);
95 self.block_indent = self.block_indent.block_indent(self.config);
97 for item in &fm.items {
98 self.format_foreign_item(&*item);
101 self.block_indent = self.block_indent.block_unindent(self.config);
102 self.format_missing_with_indent(span.hi - BytePos(1));
105 self.buffer.push_str("}");
106 self.last_pos = span.hi;
109 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
110 self.format_missing_with_indent(item.span.lo);
111 // Drop semicolon or it will be interpreted as comment.
112 // FIXME: this may be a faulty span from libsyntax.
113 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
116 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
117 let indent = self.block_indent;
118 let rewrite = rewrite_fn_base(&self.get_context(),
124 ast::Unsafety::Normal,
125 ast::Constness::NotConst,
126 // These are not actually rust functions,
127 // but we format them as such.
135 Some((new_fn, _)) => {
136 self.buffer.push_str(&new_fn);
137 self.buffer.push_str(";");
139 None => self.format_missing(item.span.hi),
142 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
143 // FIXME(#21): we're dropping potential comments in between the
144 // function keywords here.
145 let vis = match format_visibility(&item.vis) {
149 let mut_str = if is_mutable {
154 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
155 let offset = self.block_indent + prefix.len();
157 let width = self.config.max_width - offset.width() - 1;
158 let rewrite = ty.rewrite(&self.get_context(), width, offset);
162 self.buffer.push_str(&prefix);
163 self.buffer.push_str(&result);
164 self.buffer.push_str(";");
166 None => self.format_missing(item.span.hi),
171 self.last_pos = item.span.hi;
174 pub fn rewrite_fn(&mut self,
178 explicit_self: Option<&ast::ExplicitSelf>,
179 generics: &ast::Generics,
180 unsafety: ast::Unsafety,
181 constness: ast::Constness,
183 vis: &ast::Visibility,
187 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
188 let context = self.get_context();
190 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
191 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
192 !context.config.fn_empty_single_line;
194 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
208 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
209 newline_brace = false;
210 } else if force_newline_brace {
211 newline_brace = true;
214 // Prepare for the function body by possibly adding a newline and
216 // FIXME we'll miss anything between the end of the signature and the
217 // start of the body, but we need more spans from the compiler to solve
221 result.push_str(&indent.to_string(self.config));
226 self.single_line_fn(&result, block).or_else(|| Some(result))
229 pub fn rewrite_required_fn(&mut self,
232 sig: &ast::MethodSig,
235 // Drop semicolon or it will be interpreted as comment.
236 let span = mk_sp(span.lo, span.hi - BytePos(1));
237 let context = self.get_context();
239 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
243 Some(&sig.explicit_self),
248 &ast::Visibility::Inherited,
253 // Re-attach semicolon
259 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
260 if fn_str.contains('\n') {
264 let codemap = self.get_context().codemap;
266 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
267 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
268 return Some(format!("{}{{}}", fn_str));
271 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
273 if let Some(ref e) = block.expr {
274 let suffix = if semicolon_for_expr(e) {
280 e.rewrite(&self.get_context(),
281 self.config.max_width - self.block_indent.width(),
284 .or_else(|| Some(self.snippet(e.span)))
285 } else if let Some(ref stmt) = block.stmts.first() {
286 stmt.rewrite(&self.get_context(),
287 self.config.max_width - self.block_indent.width(),
294 if let Some(res) = rewrite {
295 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
296 if !res.contains('\n') && width <= self.config.max_width {
297 return Some(format!("{}{{ {} }}", fn_str, res));
305 pub fn visit_enum(&mut self,
307 vis: &ast::Visibility,
308 enum_def: &ast::EnumDef,
309 generics: &ast::Generics,
311 let header_str = match format_header("enum ", ident, vis) {
315 self.buffer.push_str(&header_str);
317 let enum_snippet = self.snippet(span);
318 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
319 let generics_str = format_generics(&self.get_context(),
323 self.config.item_brace_style,
324 enum_def.variants.is_empty(),
326 self.block_indent.block_indent(self.config),
327 mk_sp(span.lo, body_start))
329 self.buffer.push_str(&generics_str);
331 self.last_pos = body_start;
333 self.block_indent = self.block_indent.block_indent(self.config);
334 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
336 Some(ref body_str) => self.buffer.push_str(&body_str),
337 None => self.format_missing(span.hi - BytePos(1)),
339 self.block_indent = self.block_indent.block_unindent(self.config);
341 if variant_list.is_some() {
342 self.buffer.push_str(&self.block_indent.to_string(self.config));
344 self.buffer.push_str("}");
345 self.last_pos = span.hi;
348 // Format the body of an enum definition
349 fn format_variant_list(&self,
350 enum_def: &ast::EnumDef,
354 if enum_def.variants.is_empty() {
357 let mut result = String::with_capacity(1024);
359 let indentation = self.block_indent.to_string(self.config);
360 result.push_str(&indentation);
362 let items = itemize_list(self.codemap,
363 enum_def.variants.iter(),
366 if !f.node.attrs.is_empty() {
367 f.node.attrs[0].span.lo
373 |f| self.format_variant(f),
377 let budget = self.config.max_width - self.block_indent.width() - 2;
378 let fmt = ListFormatting {
379 tactic: DefinitiveListTactic::Vertical,
381 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
382 indent: self.block_indent,
384 ends_with_newline: true,
388 let list = try_opt!(write_list(items, &fmt));
389 result.push_str(&list);
394 // Variant of an enum.
395 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
396 if contains_skip(&field.node.attrs) {
397 let lo = field.node.attrs[0].span.lo;
398 let span = mk_sp(lo, field.span.hi);
399 return Some(self.snippet(span));
402 let indent = self.block_indent;
403 let mut result = try_opt!(field.node
405 .rewrite(&self.get_context(),
406 self.config.max_width - indent.width(),
408 if !result.is_empty() {
410 result.push_str(&indent.to_string(self.config));
413 let context = self.get_context();
414 let variant_body = match field.node.data {
415 ast::VariantData::Tuple(..) |
416 ast::VariantData::Struct(..) => {
417 // FIXME: Should limit the width, as we have a trailing comma
418 format_struct(&context,
421 &ast::Visibility::Inherited,
427 ast::VariantData::Unit(..) => {
428 let tag = if let Some(ref expr) = field.node.disr_expr {
429 format!("{} = {}", field.node.name, self.snippet(expr.span))
431 field.node.name.to_string()
435 self.config.max_width,
436 self.config.max_width - indent.width(),
441 if let Some(variant_str) = variant_body {
442 result.push_str(&variant_str);
450 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
451 if let ast::ItemKind::Impl(unsafety,
456 ref items) = item.node {
457 let mut result = String::new();
458 result.push_str(try_opt!(format_visibility(&item.vis)));
459 result.push_str(format_unsafety(unsafety));
460 result.push_str("impl");
462 let lo = context.codemap.span_after(item.span, "impl");
463 let hi = match *trait_ref {
464 Some(ref tr) => tr.path.span.lo,
465 None => self_ty.span.lo,
467 let generics_str = try_opt!(rewrite_generics(context,
470 context.config.max_width,
471 offset + result.len(),
473 result.push_str(&generics_str);
475 // FIXME might need to linebreak in the impl header, here would be a
478 if polarity == ast::ImplPolarity::Negative {
479 result.push_str("!");
481 if let Some(ref trait_ref) = *trait_ref {
482 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
483 let indent = offset + result.len();
484 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
485 result.push_str(" for ");
488 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
489 let indent = offset + result.len();
490 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
492 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
493 let where_clause_str = try_opt!(rewrite_where_clause(context,
494 &generics.where_clause,
496 context.config.item_brace_style,
497 context.block_indent,
499 context.config.where_density,
504 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
505 result.push_str(&where_clause_str);
506 if where_clause_str.contains('\n') {
507 let white_space = offset.to_string(context.config);
508 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
510 result.push_str(" {}");
515 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
517 let width = context.block_indent.width() + context.config.tab_spaces - 1;
518 let where_indent = Indent::new(0, width);
519 result.push_str(&where_indent.to_string(context.config));
521 result.push_str(&where_clause_str);
523 match context.config.item_brace_style {
524 BraceStyle::AlwaysNextLine => result.push('\n'),
525 BraceStyle::PreferSameLine => result.push(' '),
526 BraceStyle::SameLineWhere => {
527 if !where_clause_str.is_empty() {
529 result.push_str(&offset.to_string(context.config));
538 let snippet = context.snippet(item.span);
539 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
541 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
542 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
543 visitor.block_indent = context.block_indent.block_indent(context.config);
544 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
547 visitor.visit_impl_item(&item);
550 visitor.format_missing(item.span.hi - BytePos(1));
552 let inner_indent_str = visitor.block_indent.to_string(context.config);
553 let outer_indent_str = context.block_indent.to_string(context.config);
556 result.push_str(&inner_indent_str);
557 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
559 result.push_str(&outer_indent_str);
562 if result.chars().last().unwrap() == '{' {
573 fn is_impl_single_line(context: &RewriteContext,
574 items: &Vec<ImplItem>,
576 where_clause_str: &str,
579 let snippet = context.snippet(item.span);
580 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
582 Some(context.config.impl_empty_single_line && items.is_empty() &&
583 result.len() + where_clause_str.len() <= context.config.max_width &&
584 !contains_comment(&snippet[open_pos..]))
587 pub fn format_struct(context: &RewriteContext,
590 vis: &ast::Visibility,
591 struct_def: &ast::VariantData,
592 generics: Option<&ast::Generics>,
597 ast::VariantData::Unit(..) => format_unit_struct(item_name, ident, vis),
598 ast::VariantData::Tuple(ref fields, _) => {
599 format_tuple_struct(context,
608 ast::VariantData::Struct(ref fields, _) => {
609 format_struct_struct(context,
621 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
622 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
624 let mut result = String::new();
625 let header = format!("{}{}trait {}",
626 try_opt!(format_visibility(&item.vis)),
627 format_unsafety(unsafety),
630 result.push_str(&header);
632 let body_lo = context.codemap.span_after(item.span, "{");
634 let generics_str = try_opt!(rewrite_generics(context,
637 context.config.max_width,
638 offset + result.len(),
639 mk_sp(item.span.lo, body_lo)));
640 result.push_str(&generics_str);
642 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
645 context.config.max_width));
646 // If the trait, generics, and trait bound cannot fit on the same line,
647 // put the trait bounds on an indented new line
648 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
649 context.config.ideal_width {
651 let width = context.block_indent.width() + context.config.tab_spaces;
652 let trait_indent = Indent::new(0, width);
653 result.push_str(&trait_indent.to_string(context.config));
655 result.push_str(&trait_bound_str);
657 let has_body = !trait_items.is_empty();
659 let where_density = if (context.config.where_density == Density::Compressed &&
660 (!result.contains('\n') ||
661 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
662 (context.config.fn_args_layout == FnArgLayoutStyle::Block &&
663 result.is_empty()) ||
664 (context.config.where_density == Density::CompressedIfEmpty &&
666 !result.contains('\n')) {
672 let where_budget = try_opt!(context.config
674 .checked_sub(last_line_width(&result)));
675 let where_clause_str = try_opt!(rewrite_where_clause(context,
676 &generics.where_clause,
678 context.config.item_brace_style,
679 context.block_indent,
685 // If the where clause cannot fit on the same line,
686 // put the where clause on a new line
687 if !where_clause_str.contains('\n') &&
688 last_line_width(&result) + where_clause_str.len() + offset.width() >
689 context.config.ideal_width {
691 let width = context.block_indent.width() + context.config.tab_spaces - 1;
692 let where_indent = Indent::new(0, width);
693 result.push_str(&where_indent.to_string(context.config));
695 result.push_str(&where_clause_str);
697 match context.config.item_brace_style {
698 BraceStyle::AlwaysNextLine => {
700 result.push_str(&offset.to_string(context.config));
702 BraceStyle::PreferSameLine => result.push(' '),
703 BraceStyle::SameLineWhere => {
704 if !where_clause_str.is_empty() &&
705 (trait_items.len() > 0 || result.contains('\n')) {
707 result.push_str(&offset.to_string(context.config));
715 let snippet = context.snippet(item.span);
716 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
718 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
719 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
720 visitor.block_indent = context.block_indent.block_indent(context.config);
721 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
723 for item in trait_items {
724 visitor.visit_trait_item(&item);
727 visitor.format_missing(item.span.hi - BytePos(1));
729 let inner_indent_str = visitor.block_indent.to_string(context.config);
730 let outer_indent_str = context.block_indent.to_string(context.config);
733 result.push_str(&inner_indent_str);
734 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
736 result.push_str(&outer_indent_str);
737 } else if result.contains('\n') {
748 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> Option<String> {
749 let mut result = String::with_capacity(1024);
751 let header_str = try_opt!(format_header(item_name, ident, vis));
752 result.push_str(&header_str);
758 fn format_struct_struct(context: &RewriteContext,
761 vis: &ast::Visibility,
762 fields: &[ast::StructField],
763 generics: Option<&ast::Generics>,
767 let mut result = String::with_capacity(1024);
769 let header_str = try_opt!(format_header(item_name, ident, vis));
770 result.push_str(&header_str);
772 let body_lo = context.codemap.span_after(span, "{");
774 let generics_str = match generics {
776 try_opt!(format_generics(context,
780 context.config.item_brace_style,
783 offset + header_str.len(),
784 mk_sp(span.lo, body_lo)))
787 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
788 format!("\n{}{{", context.block_indent.to_string(context.config))
794 result.push_str(&generics_str);
796 // FIXME(#919): properly format empty structs and their comments.
797 if fields.is_empty() {
798 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
802 let item_indent = offset.block_indent(context.config);
804 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
806 let items = itemize_list(context.codemap,
810 // Include attributes and doc comments, if present
811 if !field.attrs.is_empty() {
812 field.attrs[0].span.lo
817 |field| field.ty.span.hi,
818 |field| field.rewrite(context, item_budget, item_indent),
819 context.codemap.span_after(span, "{"),
822 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
823 let fmt = ListFormatting {
824 tactic: DefinitiveListTactic::Vertical,
826 trailing_separator: context.config.struct_trailing_comma,
829 ends_with_newline: true,
830 config: context.config,
832 Some(format!("{}\n{}{}\n{}}}",
834 offset.block_indent(context.config).to_string(context.config),
835 try_opt!(write_list(items, &fmt)),
836 offset.to_string(context.config)))
839 fn format_tuple_struct(context: &RewriteContext,
842 vis: &ast::Visibility,
843 fields: &[ast::StructField],
844 generics: Option<&ast::Generics>,
848 let mut result = String::with_capacity(1024);
850 let header_str = try_opt!(format_header(item_name, ident, vis));
851 result.push_str(&header_str);
853 // FIXME(#919): don't lose comments on empty tuple structs.
854 let body_lo = if fields.is_empty() {
860 let where_clause_str = match generics {
861 Some(ref generics) => {
862 let generics_str = try_opt!(rewrite_generics(context,
865 context.config.max_width,
866 offset + header_str.len(),
867 mk_sp(span.lo, body_lo)));
868 result.push_str(&generics_str);
870 let where_budget = try_opt!(context.config
872 .checked_sub(last_line_width(&result)));
873 try_opt!(rewrite_where_clause(context,
874 &generics.where_clause,
876 context.config.item_brace_style,
877 context.block_indent,
884 None => "".to_owned(),
888 let item_indent = context.block_indent + result.len();
890 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
892 let items = itemize_list(context.codemap,
896 // Include attributes and doc comments, if present
897 if !field.attrs.is_empty() {
898 field.attrs[0].span.lo
903 |field| field.ty.span.hi,
904 |field| field.rewrite(context, item_budget, item_indent),
905 context.codemap.span_after(span, "("),
907 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
908 result.push_str(&body);
911 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
912 (result.contains('\n') ||
913 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
914 context.config.max_width) {
915 // We need to put the where clause on a new line, but we didn'to_string
916 // know that earlier, so the where clause will not be indented properly.
918 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
919 .to_string(context.config));
921 result.push_str(&where_clause_str);
926 pub fn rewrite_type_alias(context: &RewriteContext,
930 generics: &ast::Generics,
931 vis: &ast::Visibility,
934 let mut result = String::new();
936 result.push_str(&try_opt!(format_visibility(&vis)));
937 result.push_str("type ");
938 result.push_str(&ident.to_string());
940 let generics_indent = indent + result.len();
941 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
942 let generics_width = context.config.max_width - " =".len();
943 let generics_str = try_opt!(rewrite_generics(context,
950 result.push_str(&generics_str);
952 let where_budget = try_opt!(context.config
954 .checked_sub(last_line_width(&result)));
955 let where_clause_str = try_opt!(rewrite_where_clause(context,
956 &generics.where_clause,
958 context.config.item_brace_style,
961 context.config.where_density,
965 result.push_str(&where_clause_str);
966 result.push_str(" = ");
968 let line_width = last_line_width(&result);
969 // This checked_sub may fail as the extra space after '=' is not taken into account
970 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
971 let budget = context.config
973 .checked_sub(indent.width() + line_width + ";".len())
975 let type_indent = indent + line_width;
976 // Try to fit the type on the same line
977 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
979 // The line was too short, try to put the type on the next line
981 // Remove the space after '='
983 let type_indent = indent.block_indent(context.config);
985 result.push_str(&type_indent.to_string(context.config));
986 let budget = try_opt!(context.config
988 .checked_sub(type_indent.width() + ";".len()));
989 ty.rewrite(context, budget, type_indent)
991 result.push_str(&ty_str);
992 result.push_str(";");
996 impl Rewrite for ast::StructField {
997 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
998 if contains_skip(&self.attrs) {
999 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1000 return wrap_str(span, context.config.max_width, width, offset);
1003 let name = self.ident;
1004 let vis = try_opt!(format_visibility(&self.vis));
1005 let mut attr_str = try_opt!(self.attrs
1006 .rewrite(context, context.config.max_width - offset.width(), offset));
1007 if !attr_str.is_empty() {
1008 attr_str.push('\n');
1009 attr_str.push_str(&offset.to_string(context.config));
1012 let result = match name {
1013 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1014 None => format!("{}{}", attr_str, vis),
1017 let last_line_width = last_line_width(&result);
1018 let budget = try_opt!(width.checked_sub(last_line_width));
1019 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1020 Some(result + &rewrite)
1024 pub fn rewrite_static(prefix: &str,
1025 vis: &ast::Visibility,
1028 mutability: ast::Mutability,
1029 expr_opt: Option<&ptr::P<ast::Expr>>,
1030 context: &RewriteContext)
1032 let prefix = format!("{}{} {}{}: ",
1033 try_opt!(format_visibility(vis)),
1035 format_mutability(mutability),
1038 let ty_str = try_opt!(ty.rewrite(context,
1039 context.config.max_width - context.block_indent.width() -
1041 context.block_indent));
1043 if let Some(ref expr) = expr_opt {
1044 let lhs = format!("{}{} =", prefix, ty_str);
1046 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1047 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1050 let lhs = format!("{}{};", prefix, ty_str);
1055 pub fn rewrite_associated_type(ident: ast::Ident,
1056 ty_opt: Option<&ptr::P<ast::Ty>>,
1057 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1058 context: &RewriteContext,
1061 let prefix = format!("type {}", ident);
1063 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1064 let bounds: &[_] = &ty_param_bounds;
1065 let bound_str = bounds.iter()
1066 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1067 .collect::<Vec<String>>()
1069 if bounds.len() > 0 {
1070 format!(": {}", bound_str)
1078 if let Some(ty) = ty_opt {
1079 let ty_str = try_opt!(ty.rewrite(context,
1080 context.config.max_width - context.block_indent.width() -
1083 context.block_indent));
1084 Some(format!("{} = {};", prefix, ty_str))
1086 Some(format!("{}{};", prefix, type_bounds_str))
1090 impl Rewrite for ast::FunctionRetTy {
1091 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1093 ast::FunctionRetTy::Default(_) => Some(String::new()),
1094 ast::FunctionRetTy::None(_) => {
1096 Some("-> !".to_owned())
1101 ast::FunctionRetTy::Ty(ref ty) => {
1102 let inner_width = try_opt!(width.checked_sub(3));
1103 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1109 impl Rewrite for ast::Arg {
1110 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1111 if is_named_arg(self) {
1112 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1114 if self.ty.node != ast::TyKind::Infer {
1115 result.push_str(": ");
1116 let max_width = try_opt!(width.checked_sub(result.len()));
1117 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1118 result.push_str(&ty_str);
1123 self.ty.rewrite(context, width, offset)
1128 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1130 context: &RewriteContext)
1132 match explicit_self.node {
1133 ast::SelfKind::Region(lt, m, _) => {
1134 let mut_str = format_mutability(m);
1137 let lifetime_str = try_opt!(l.rewrite(context,
1140 Some(format!("&{} {}self", lifetime_str, mut_str))
1142 None => Some(format!("&{}self", mut_str)),
1145 ast::SelfKind::Explicit(ref ty, _) => {
1146 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1148 let mutability = explicit_self_mutability(&args[0]);
1149 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1151 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1153 ast::SelfKind::Value(_) => {
1154 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1156 let mutability = explicit_self_mutability(&args[0]);
1158 Some(format!("{}self", format_mutability(mutability)))
1164 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1165 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1166 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1167 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1174 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1175 if is_named_arg(arg) {
1182 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1184 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1185 _ => arg.ty.span.hi,
1189 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1190 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1191 ident.node != token::keywords::Invalid.ident()
1197 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1199 ast::FunctionRetTy::None(ref span) |
1200 ast::FunctionRetTy::Default(ref span) => span.clone(),
1201 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1205 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1206 // Note that ty.span is the span for ty.ident, not the whole item.
1207 let lo = ty.span.lo;
1208 if let Some(ref def) = ty.default {
1209 return mk_sp(lo, def.span.hi);
1211 if ty.bounds.is_empty() {
1214 let hi = match ty.bounds[ty.bounds.len() - 1] {
1215 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1216 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1221 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1223 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1224 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1225 ast::WherePredicate::EqPredicate(ref p) => p.span,
1229 // Return type is (result, force_new_line_for_brace)
1230 fn rewrite_fn_base(context: &RewriteContext,
1234 explicit_self: Option<&ast::ExplicitSelf>,
1235 generics: &ast::Generics,
1236 unsafety: ast::Unsafety,
1237 constness: ast::Constness,
1239 vis: &ast::Visibility,
1241 newline_brace: bool,
1243 -> Option<(String, bool)> {
1244 let mut force_new_line_for_brace = false;
1245 // FIXME we'll lose any comments in between parts of the function decl, but
1246 // anyone who comments there probably deserves what they get.
1248 let where_clause = &generics.where_clause;
1250 let mut result = String::with_capacity(1024);
1251 // Vis unsafety abi.
1252 result.push_str(try_opt!(format_visibility(vis)));
1254 if let ast::Constness::Const = constness {
1255 result.push_str("const ");
1258 result.push_str(::utils::format_unsafety(unsafety));
1260 if abi != abi::Abi::Rust {
1261 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1265 result.push_str("fn ");
1266 result.push_str(&ident.to_string());
1269 let generics_indent = indent + result.len();
1270 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1271 let generics_str = try_opt!(rewrite_generics(context,
1274 context.config.max_width,
1277 result.push_str(&generics_str);
1279 // Note that if the width and indent really matter, we'll re-layout the
1280 // return type later anyway.
1281 let ret_str = try_opt!(fd.output
1282 .rewrite(&context, context.config.max_width - indent.width(), indent));
1284 let multi_line_ret_str = ret_str.contains('\n');
1285 let ret_str_len = if multi_line_ret_str {
1292 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1293 compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace);
1295 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1296 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1297 arg_indent = indent.block_indent(context.config);
1298 multi_line_budget = context.config.max_width - arg_indent.width();
1301 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1306 // Check if vertical layout was forced by compute_budget_for_args.
1307 if one_line_budget == 0 {
1308 if context.config.fn_args_paren_newline {
1310 result.push_str(&arg_indent.to_string(context.config));
1311 arg_indent = arg_indent + 1; // extra space for `(`
1314 result.push_str("(\n");
1315 result.push_str(&arg_indent.to_string(context.config));
1321 if multi_line_ret_str {
1322 one_line_budget = 0;
1325 // A conservative estimation, to goal is to be over all parens in generics
1326 let args_start = generics.ty_params
1328 .map_or(span.lo, |tp| end_typaram(tp));
1329 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1330 span_for_return(&fd.output).lo);
1331 let arg_str = try_opt!(rewrite_args(context,
1341 let multi_line_arg_str = arg_str.contains('\n');
1343 let put_args_in_block = match context.config.fn_args_layout {
1344 FnArgLayoutStyle::Block => multi_line_arg_str,
1345 FnArgLayoutStyle::BlockAlways => true,
1347 } && fd.inputs.len() > 0;
1349 if put_args_in_block {
1350 arg_indent = indent.block_indent(context.config);
1352 result.push_str(&arg_indent.to_string(context.config));
1353 result.push_str(&arg_str);
1355 result.push_str(&indent.to_string(context.config));
1358 result.push_str(&arg_str);
1363 if !ret_str.is_empty() {
1364 let ret_should_indent = match context.config.fn_args_layout {
1365 // If our args are block layout then we surely must have space.
1366 FnArgLayoutStyle::Block if put_args_in_block => false,
1367 FnArgLayoutStyle::BlockAlways => false,
1369 // If we've already gone multi-line, or the return type would push
1370 // over the max width, then put the return type on a new line.
1371 result.contains("\n") || multi_line_ret_str ||
1372 result.len() + indent.width() + ret_str_len > context.config.max_width
1375 let ret_indent = if ret_should_indent {
1376 let indent = match context.config.fn_return_indent {
1377 ReturnIndent::WithWhereClause => indent + 4,
1378 // Aligning with non-existent args looks silly.
1379 _ if arg_str.is_empty() => {
1380 force_new_line_for_brace = true;
1383 // FIXME: we might want to check that using the arg indent
1384 // doesn't blow our budget, and if it does, then fallback to
1385 // the where clause indent.
1390 result.push_str(&indent.to_string(context.config));
1394 Indent::new(indent.width(), result.len())
1397 if multi_line_ret_str {
1398 // Now that we know the proper indent and width, we need to
1399 // re-layout the return type.
1401 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1402 let ret_str = try_opt!(fd.output
1403 .rewrite(context, budget, ret_indent));
1404 result.push_str(&ret_str);
1406 result.push_str(&ret_str);
1409 // Comment between return type and the end of the decl.
1410 let snippet_lo = fd.output.span().hi;
1411 if where_clause.predicates.is_empty() {
1412 let snippet_hi = span.hi;
1413 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1414 let snippet = snippet.trim();
1415 if !snippet.is_empty() {
1417 result.push_str(snippet);
1420 // FIXME it would be nice to catch comments between the return type
1421 // and the where clause, but we don't have a span for the where
1426 let should_compress_where = match context.config.where_density {
1427 Density::Compressed => !result.contains('\n') || put_args_in_block,
1428 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1430 } || (put_args_in_block && ret_str.is_empty());
1432 let where_density = if should_compress_where {
1439 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1440 let where_clause_str = try_opt!(rewrite_where_clause(context,
1443 context.config.fn_brace_style,
1451 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1452 !where_clause_str.contains('\n') {
1456 result.push_str(&where_clause_str);
1458 Some((result, force_new_line_for_brace))
1461 fn rewrite_args(context: &RewriteContext,
1463 explicit_self: Option<&ast::ExplicitSelf>,
1464 one_line_budget: usize,
1465 multi_line_budget: usize,
1471 let mut arg_item_strs = try_opt!(args.iter()
1472 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1473 .collect::<Option<Vec<_>>>());
1475 // Account for sugary self.
1476 // FIXME: the comment for the self argument is dropped. This is blocked
1477 // on rust issue #27522.
1479 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1480 .map_or(1, |self_str| {
1481 arg_item_strs[0] = self_str;
1485 // Comments between args.
1486 let mut arg_items = Vec::new();
1488 arg_items.push(ListItem::from_str(""));
1491 // FIXME(#21): if there are no args, there might still be a comment, but
1492 // without spans for the comment or parens, there is no chance of
1493 // getting it right. You also don't get to put a comment on self, unless
1495 if args.len() >= min_args || variadic {
1496 let comment_span_start = if min_args == 2 {
1497 let second_arg_start = if arg_has_pattern(&args[1]) {
1502 let reduced_span = mk_sp(span.lo, second_arg_start);
1504 context.codemap.span_after_last(reduced_span, ",")
1509 enum ArgumentKind<'a> {
1510 Regular(&'a ast::Arg),
1514 let variadic_arg = if variadic {
1515 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1516 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1517 Some(ArgumentKind::Variadic(variadic_start))
1522 let more_items = itemize_list(context.codemap,
1523 args[min_args - 1..]
1525 .map(ArgumentKind::Regular)
1526 .chain(variadic_arg),
1530 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1531 ArgumentKind::Variadic(start) => start,
1536 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1537 ArgumentKind::Variadic(start) => start + BytePos(3),
1542 ArgumentKind::Regular(..) => None,
1543 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1549 arg_items.extend(more_items);
1552 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1553 item.item = Some(arg);
1556 let indent = match context.config.fn_arg_indent {
1557 BlockIndentStyle::Inherit => indent,
1558 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1559 BlockIndentStyle::Visual => arg_indent,
1562 let tactic = definitive_tactic(&arg_items,
1563 context.config.fn_args_density.to_list_tactic(),
1565 let budget = match tactic {
1566 DefinitiveListTactic::Horizontal => one_line_budget,
1567 _ => multi_line_budget,
1570 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1572 let end_with_newline = match context.config.fn_args_layout {
1573 FnArgLayoutStyle::Block |
1574 FnArgLayoutStyle::BlockAlways => true,
1578 let fmt = ListFormatting {
1581 trailing_separator: SeparatorTactic::Never,
1584 ends_with_newline: end_with_newline,
1585 config: context.config,
1588 write_list(&arg_items, &fmt)
1591 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1592 if let ast::PatKind::Ident(_,
1594 node: ast::Ident { name: ast::Name(0u32), .. },
1604 fn compute_budgets_for_args(context: &RewriteContext,
1608 newline_brace: bool)
1609 -> (usize, usize, Indent) {
1610 // Try keeping everything on the same line.
1611 if !result.contains("\n") {
1612 // 3 = `() `, space is before ret_string.
1613 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1617 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1619 if one_line_budget > 0 {
1620 let multi_line_budget = context.config.max_width -
1621 (indent.width() + result.len() + "()".len());
1623 return (one_line_budget, multi_line_budget, indent + result.len() + 1);
1627 // Didn't work. we must force vertical layout and put args on a newline.
1628 let new_indent = indent.block_indent(context.config);
1629 let used_space = new_indent.width() + 2; // account for `(` and `)`
1630 let max_space = context.config.max_width;
1631 if used_space <= max_space {
1632 (0, max_space - used_space, new_indent)
1634 // Whoops! bankrupt.
1635 // FIXME: take evasive action, perhaps kill the indent or something.
1636 panic!("in compute_budgets_for_args");
1640 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1641 match config.fn_brace_style {
1642 BraceStyle::AlwaysNextLine => true,
1643 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1648 fn rewrite_generics(context: &RewriteContext,
1649 generics: &ast::Generics,
1652 generics_offset: Indent,
1655 // FIXME: convert bounds to where clauses where they get too big or if
1656 // there is a where clause at all.
1657 let lifetimes: &[_] = &generics.lifetimes;
1658 let tys: &[_] = &generics.ty_params;
1659 if lifetimes.is_empty() && tys.is_empty() {
1660 return Some(String::new());
1663 let offset = match context.config.generics_indent {
1664 BlockIndentStyle::Inherit => offset,
1665 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1667 BlockIndentStyle::Visual => generics_offset + 1,
1670 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1671 // FIXME: might need to insert a newline if the generics are really long.
1673 // Strings for the generics.
1674 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1675 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1677 // Extract comments between generics.
1678 let lt_spans = lifetimes.iter().map(|l| {
1679 let hi = if l.bounds.is_empty() {
1682 l.bounds[l.bounds.len() - 1].span.hi
1684 mk_sp(l.lifetime.span.lo, hi)
1686 let ty_spans = tys.iter().map(span_for_ty_param);
1688 let items = itemize_list(context.codemap,
1689 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1693 // FIXME: don't clone
1694 |&(_, ref str)| str.clone(),
1695 context.codemap.span_after(span, "<"),
1697 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1699 Some(format!("<{}>", list_str))
1702 fn rewrite_trait_bounds(context: &RewriteContext,
1703 type_param_bounds: &ast::TyParamBounds,
1707 let bounds: &[_] = &type_param_bounds;
1709 if bounds.is_empty() {
1710 return Some(String::new());
1713 let bound_str = bounds.iter()
1714 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1715 .collect::<Vec<String>>()
1718 let mut result = String::new();
1719 result.push_str(": ");
1720 result.push_str(&bound_str);
1724 fn rewrite_where_clause(context: &RewriteContext,
1725 where_clause: &ast::WhereClause,
1727 brace_style: BraceStyle,
1732 allow_trailing_comma: bool,
1733 span_end: Option<BytePos>)
1735 if where_clause.predicates.is_empty() {
1736 return Some(String::new());
1739 let extra_indent = match context.config.where_indent {
1740 BlockIndentStyle::Inherit => Indent::empty(),
1741 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1744 let offset = match context.config.where_pred_indent {
1745 BlockIndentStyle::Inherit => indent + extra_indent,
1746 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1747 // 6 = "where ".len()
1748 BlockIndentStyle::Visual => indent + extra_indent + 6,
1750 // FIXME: if where_pred_indent != Visual, then the budgets below might
1751 // be out by a char or two.
1753 let budget = context.config.max_width - offset.width();
1754 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1755 // If we don't have the start of the next span, then use the end of the
1756 // predicates, but that means we miss comments.
1757 let len = where_clause.predicates.len();
1758 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1759 let span_end = span_end.unwrap_or(end_of_preds);
1760 let items = itemize_list(context.codemap,
1761 where_clause.predicates.iter(),
1763 |pred| span_for_where_pred(pred).lo,
1764 |pred| span_for_where_pred(pred).hi,
1765 |pred| pred.rewrite(&context, budget, offset),
1768 let item_vec = items.collect::<Vec<_>>();
1769 // FIXME: we don't need to collect here if the where_layout isn't
1770 // HorizontalVertical.
1771 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1772 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1774 let fmt = ListFormatting {
1777 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1780 ends_with_newline: true,
1781 config: context.config,
1783 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1785 let end_length = if terminator == "{" {
1786 // If the brace is on the next line we don't need to count it otherwise it needs two
1789 BraceStyle::AlwaysNextLine => 0,
1790 BraceStyle::PreferSameLine => 2,
1791 BraceStyle::SameLineWhere => 0,
1793 } else if terminator == "=" {
1798 if density == Density::Tall || preds_str.contains('\n') ||
1799 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1800 Some(format!("\n{}where {}",
1801 (indent + extra_indent).to_string(context.config),
1804 Some(format!(" where {}", preds_str))
1808 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> Option<String> {
1809 Some(format!("{}{}{}", try_opt!(format_visibility(vis)), item_name, ident))
1812 fn format_generics(context: &RewriteContext,
1813 generics: &ast::Generics,
1816 brace_style: BraceStyle,
1817 force_same_line_brace: bool,
1819 generics_offset: Indent,
1822 let mut result = try_opt!(rewrite_generics(context,
1825 context.config.max_width,
1829 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1830 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1831 let where_clause_str = try_opt!(rewrite_where_clause(context,
1832 &generics.where_clause,
1835 context.block_indent,
1841 result.push_str(&where_clause_str);
1842 if !force_same_line_brace &&
1843 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1845 result.push_str(&context.block_indent.to_string(context.config));
1849 result.push_str(opener);
1851 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1853 result.push_str(&context.block_indent.to_string(context.config));
1857 result.push_str(opener);