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 mut_str = if is_mutable {
150 let prefix = format!("{}static {}{}: ",
151 format_visibility(item.vis),
154 let offset = self.block_indent + prefix.len();
156 let width = self.config.max_width - offset.width() - 1;
157 let rewrite = ty.rewrite(&self.get_context(), width, offset);
161 self.buffer.push_str(&prefix);
162 self.buffer.push_str(&result);
163 self.buffer.push_str(";");
165 None => self.format_missing(item.span.hi),
170 self.last_pos = item.span.hi;
173 pub fn rewrite_fn(&mut self,
177 explicit_self: Option<&ast::ExplicitSelf>,
178 generics: &ast::Generics,
179 unsafety: ast::Unsafety,
180 constness: ast::Constness,
182 vis: ast::Visibility,
186 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
187 let context = self.get_context();
189 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
190 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
191 !context.config.fn_empty_single_line;
193 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
207 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
208 newline_brace = false;
209 } else if force_newline_brace {
210 newline_brace = true;
213 // Prepare for the function body by possibly adding a newline and
215 // FIXME we'll miss anything between the end of the signature and the
216 // start of the body, but we need more spans from the compiler to solve
220 result.push_str(&indent.to_string(self.config));
225 self.single_line_fn(&result, block).or_else(|| Some(result))
228 pub fn rewrite_required_fn(&mut self,
231 sig: &ast::MethodSig,
234 // Drop semicolon or it will be interpreted as comment.
235 let span = mk_sp(span.lo, span.hi - BytePos(1));
236 let context = self.get_context();
238 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
242 Some(&sig.explicit_self),
247 ast::Visibility::Inherited,
252 // Re-attach semicolon
258 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
259 if fn_str.contains('\n') {
263 let codemap = self.get_context().codemap;
265 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
266 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
267 return Some(format!("{}{{}}", fn_str));
270 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
272 if let Some(ref e) = block.expr {
273 let suffix = if semicolon_for_expr(e) {
279 e.rewrite(&self.get_context(),
280 self.config.max_width - self.block_indent.width(),
283 .or_else(|| Some(self.snippet(e.span)))
284 } else if let Some(ref stmt) = block.stmts.first() {
285 stmt.rewrite(&self.get_context(),
286 self.config.max_width - self.block_indent.width(),
293 if let Some(res) = rewrite {
294 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
295 if !res.contains('\n') && width <= self.config.max_width {
296 return Some(format!("{}{{ {} }}", fn_str, res));
304 pub fn visit_enum(&mut self,
306 vis: ast::Visibility,
307 enum_def: &ast::EnumDef,
308 generics: &ast::Generics,
310 let header_str = format_header("enum ", ident, vis);
311 self.buffer.push_str(&header_str);
313 let enum_snippet = self.snippet(span);
314 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
315 let generics_str = format_generics(&self.get_context(),
319 self.config.item_brace_style,
320 enum_def.variants.is_empty(),
322 self.block_indent.block_indent(self.config),
323 mk_sp(span.lo, body_start))
325 self.buffer.push_str(&generics_str);
327 self.last_pos = body_start;
329 self.block_indent = self.block_indent.block_indent(self.config);
330 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
332 Some(ref body_str) => self.buffer.push_str(&body_str),
333 None => self.format_missing(span.hi - BytePos(1)),
335 self.block_indent = self.block_indent.block_unindent(self.config);
337 if variant_list.is_some() {
338 self.buffer.push_str(&self.block_indent.to_string(self.config));
340 self.buffer.push_str("}");
341 self.last_pos = span.hi;
344 // Format the body of an enum definition
345 fn format_variant_list(&self,
346 enum_def: &ast::EnumDef,
350 if enum_def.variants.is_empty() {
353 let mut result = String::with_capacity(1024);
355 let indentation = self.block_indent.to_string(self.config);
356 result.push_str(&indentation);
358 let items = itemize_list(self.codemap,
359 enum_def.variants.iter(),
362 if !f.node.attrs.is_empty() {
363 f.node.attrs[0].span.lo
369 |f| self.format_variant(f),
373 let budget = self.config.max_width - self.block_indent.width() - 2;
374 let fmt = ListFormatting {
375 tactic: DefinitiveListTactic::Vertical,
377 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
378 indent: self.block_indent,
380 ends_with_newline: true,
384 let list = try_opt!(write_list(items, &fmt));
385 result.push_str(&list);
390 // Variant of an enum.
391 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
392 if contains_skip(&field.node.attrs) {
393 let lo = field.node.attrs[0].span.lo;
394 let span = mk_sp(lo, field.span.hi);
395 return Some(self.snippet(span));
398 let indent = self.block_indent;
399 let mut result = try_opt!(field.node
401 .rewrite(&self.get_context(),
402 self.config.max_width - indent.width(),
404 if !result.is_empty() {
406 result.push_str(&indent.to_string(self.config));
409 let context = self.get_context();
410 let variant_body = match field.node.data {
411 ast::VariantData::Tuple(..) |
412 ast::VariantData::Struct(..) => {
413 // FIXME: Should limit the width, as we have a trailing comma
414 format_struct(&context,
417 ast::Visibility::Inherited,
423 ast::VariantData::Unit(..) => {
424 let tag = if let Some(ref expr) = field.node.disr_expr {
425 format!("{} = {}", field.node.name, self.snippet(expr.span))
427 field.node.name.to_string()
431 self.config.max_width,
432 self.config.max_width - indent.width(),
437 if let Some(variant_str) = variant_body {
438 result.push_str(&variant_str);
446 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
447 if let ast::ItemKind::Impl(unsafety,
452 ref items) = item.node {
453 let mut result = String::new();
454 result.push_str(format_visibility(item.vis));
455 result.push_str(format_unsafety(unsafety));
456 result.push_str("impl");
458 let lo = context.codemap.span_after(item.span, "impl");
459 let hi = match *trait_ref {
460 Some(ref tr) => tr.path.span.lo,
461 None => self_ty.span.lo,
463 let generics_str = try_opt!(rewrite_generics(context,
466 context.config.max_width,
467 offset + result.len(),
469 result.push_str(&generics_str);
471 // FIXME might need to linebreak in the impl header, here would be a
474 if polarity == ast::ImplPolarity::Negative {
475 result.push_str("!");
477 if let Some(ref trait_ref) = *trait_ref {
478 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
479 let indent = offset + result.len();
480 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
481 result.push_str(" for ");
484 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
485 let indent = offset + result.len();
486 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
488 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
489 let where_clause_str = try_opt!(rewrite_where_clause(context,
490 &generics.where_clause,
492 context.config.item_brace_style,
493 context.block_indent,
495 context.config.where_density,
500 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
501 result.push_str(&where_clause_str);
502 if where_clause_str.contains('\n') {
503 let white_space = offset.to_string(context.config);
504 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
506 result.push_str(" {}");
511 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
513 let width = context.block_indent.width() + context.config.tab_spaces - 1;
514 let where_indent = Indent::new(0, width);
515 result.push_str(&where_indent.to_string(context.config));
517 result.push_str(&where_clause_str);
519 match context.config.item_brace_style {
520 BraceStyle::AlwaysNextLine => result.push('\n'),
521 BraceStyle::PreferSameLine => result.push(' '),
522 BraceStyle::SameLineWhere => {
523 if !where_clause_str.is_empty() {
525 result.push_str(&offset.to_string(context.config));
534 let snippet = context.snippet(item.span);
535 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
537 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
538 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
539 visitor.block_indent = context.block_indent.block_indent(context.config);
540 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
543 visitor.visit_impl_item(&item);
546 visitor.format_missing(item.span.hi - BytePos(1));
548 let inner_indent_str = visitor.block_indent.to_string(context.config);
549 let outer_indent_str = context.block_indent.to_string(context.config);
552 result.push_str(&inner_indent_str);
553 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
555 result.push_str(&outer_indent_str);
558 if result.chars().last().unwrap() == '{' {
569 fn is_impl_single_line(context: &RewriteContext,
570 items: &Vec<ImplItem>,
572 where_clause_str: &str,
575 let snippet = context.snippet(item.span);
576 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
578 Some(context.config.impl_empty_single_line && items.is_empty() &&
579 result.len() + where_clause_str.len() <= context.config.max_width &&
580 !contains_comment(&snippet[open_pos..]))
583 pub fn format_struct(context: &RewriteContext,
586 vis: ast::Visibility,
587 struct_def: &ast::VariantData,
588 generics: Option<&ast::Generics>,
593 ast::VariantData::Unit(..) => format_unit_struct(item_name, ident, vis),
594 ast::VariantData::Tuple(ref fields, _) => {
595 format_tuple_struct(context,
604 ast::VariantData::Struct(ref fields, _) => {
605 format_struct_struct(context,
617 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
618 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
620 let mut result = String::new();
621 let header = format!("{}{}trait {}",
622 format_visibility(item.vis),
623 format_unsafety(unsafety),
626 result.push_str(&header);
628 let body_lo = context.codemap.span_after(item.span, "{");
630 let generics_str = try_opt!(rewrite_generics(context,
633 context.config.max_width,
634 offset + result.len(),
635 mk_sp(item.span.lo, body_lo)));
636 result.push_str(&generics_str);
638 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
641 context.config.max_width));
642 // If the trait, generics, and trait bound cannot fit on the same line,
643 // put the trait bounds on an indented new line
644 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
645 context.config.ideal_width {
647 let width = context.block_indent.width() + context.config.tab_spaces;
648 let trait_indent = Indent::new(0, width);
649 result.push_str(&trait_indent.to_string(context.config));
651 result.push_str(&trait_bound_str);
653 let has_body = !trait_items.is_empty();
655 let where_density = if (context.config.where_density == Density::Compressed &&
656 (!result.contains('\n') ||
657 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
658 (context.config.fn_args_layout == FnArgLayoutStyle::Block &&
659 result.is_empty()) ||
660 (context.config.where_density == Density::CompressedIfEmpty &&
662 !result.contains('\n')) {
668 let where_budget = try_opt!(context.config
670 .checked_sub(last_line_width(&result)));
671 let where_clause_str = try_opt!(rewrite_where_clause(context,
672 &generics.where_clause,
674 context.config.item_brace_style,
675 context.block_indent,
681 // If the where clause cannot fit on the same line,
682 // put the where clause on a new line
683 if !where_clause_str.contains('\n') &&
684 last_line_width(&result) + where_clause_str.len() + offset.width() >
685 context.config.ideal_width {
687 let width = context.block_indent.width() + context.config.tab_spaces - 1;
688 let where_indent = Indent::new(0, width);
689 result.push_str(&where_indent.to_string(context.config));
691 result.push_str(&where_clause_str);
693 match context.config.item_brace_style {
694 BraceStyle::AlwaysNextLine => {
696 result.push_str(&offset.to_string(context.config));
698 BraceStyle::PreferSameLine => result.push(' '),
699 BraceStyle::SameLineWhere => {
700 if !where_clause_str.is_empty() &&
701 (trait_items.len() > 0 || result.contains('\n')) {
703 result.push_str(&offset.to_string(context.config));
711 let snippet = context.snippet(item.span);
712 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
714 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
715 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
716 visitor.block_indent = context.block_indent.block_indent(context.config);
717 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
719 for item in trait_items {
720 visitor.visit_trait_item(&item);
723 visitor.format_missing(item.span.hi - BytePos(1));
725 let inner_indent_str = visitor.block_indent.to_string(context.config);
726 let outer_indent_str = context.block_indent.to_string(context.config);
729 result.push_str(&inner_indent_str);
730 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
732 result.push_str(&outer_indent_str);
733 } else if result.contains('\n') {
744 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> Option<String> {
745 let mut result = String::with_capacity(1024);
747 let header_str = format_header(item_name, ident, vis);
748 result.push_str(&header_str);
754 fn format_struct_struct(context: &RewriteContext,
757 vis: ast::Visibility,
758 fields: &[ast::StructField],
759 generics: Option<&ast::Generics>,
763 let mut result = String::with_capacity(1024);
765 let header_str = format_header(item_name, ident, vis);
766 result.push_str(&header_str);
768 let body_lo = context.codemap.span_after(span, "{");
770 let generics_str = match generics {
772 try_opt!(format_generics(context,
776 context.config.item_brace_style,
779 offset + header_str.len(),
780 mk_sp(span.lo, body_lo)))
783 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
784 format!("\n{}{{", context.block_indent.to_string(context.config))
790 result.push_str(&generics_str);
792 // FIXME(#919): properly format empty structs and their comments.
793 if fields.is_empty() {
794 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
798 let item_indent = offset.block_indent(context.config);
800 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
802 let items = itemize_list(context.codemap,
806 // Include attributes and doc comments, if present
807 if !field.node.attrs.is_empty() {
808 field.node.attrs[0].span.lo
813 |field| field.node.ty.span.hi,
814 |field| field.rewrite(context, item_budget, item_indent),
815 context.codemap.span_after(span, "{"),
818 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
819 let fmt = ListFormatting {
820 tactic: DefinitiveListTactic::Vertical,
822 trailing_separator: context.config.struct_trailing_comma,
825 ends_with_newline: true,
826 config: context.config,
828 Some(format!("{}\n{}{}\n{}}}",
830 offset.block_indent(context.config).to_string(context.config),
831 try_opt!(write_list(items, &fmt)),
832 offset.to_string(context.config)))
835 fn format_tuple_struct(context: &RewriteContext,
838 vis: ast::Visibility,
839 fields: &[ast::StructField],
840 generics: Option<&ast::Generics>,
844 let mut result = String::with_capacity(1024);
846 let header_str = format_header(item_name, ident, vis);
847 result.push_str(&header_str);
849 // FIXME(#919): don't lose comments on empty tuple structs.
850 let body_lo = if fields.is_empty() {
856 let where_clause_str = match generics {
857 Some(ref generics) => {
858 let generics_str = try_opt!(rewrite_generics(context,
861 context.config.max_width,
862 offset + header_str.len(),
863 mk_sp(span.lo, body_lo)));
864 result.push_str(&generics_str);
866 let where_budget = try_opt!(context.config
868 .checked_sub(last_line_width(&result)));
869 try_opt!(rewrite_where_clause(context,
870 &generics.where_clause,
872 context.config.item_brace_style,
873 context.block_indent,
880 None => "".to_owned(),
884 let item_indent = context.block_indent + result.len();
886 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
888 let items = itemize_list(context.codemap,
892 // Include attributes and doc comments, if present
893 if !field.node.attrs.is_empty() {
894 field.node.attrs[0].span.lo
899 |field| field.node.ty.span.hi,
900 |field| field.rewrite(context, item_budget, item_indent),
901 context.codemap.span_after(span, "("),
903 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
904 result.push_str(&body);
907 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
908 (result.contains('\n') ||
909 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
910 context.config.max_width) {
911 // We need to put the where clause on a new line, but we didn'to_string
912 // know that earlier, so the where clause will not be indented properly.
914 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
915 .to_string(context.config));
917 result.push_str(&where_clause_str);
922 pub fn rewrite_type_alias(context: &RewriteContext,
926 generics: &ast::Generics,
927 vis: ast::Visibility,
930 let mut result = String::new();
932 result.push_str(&format_visibility(vis));
933 result.push_str("type ");
934 result.push_str(&ident.to_string());
936 let generics_indent = indent + result.len();
937 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
938 let generics_width = context.config.max_width - " =".len();
939 let generics_str = try_opt!(rewrite_generics(context,
946 result.push_str(&generics_str);
948 let where_budget = try_opt!(context.config
950 .checked_sub(last_line_width(&result)));
951 let where_clause_str = try_opt!(rewrite_where_clause(context,
952 &generics.where_clause,
954 context.config.item_brace_style,
957 context.config.where_density,
961 result.push_str(&where_clause_str);
962 result.push_str(" = ");
964 let line_width = last_line_width(&result);
965 // This checked_sub may fail as the extra space after '=' is not taken into account
966 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
967 let budget = context.config
969 .checked_sub(indent.width() + line_width + ";".len())
971 let type_indent = indent + line_width;
972 // Try to fit the type on the same line
973 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
975 // The line was too short, try to put the type on the next line
977 // Remove the space after '='
979 let type_indent = indent.block_indent(context.config);
981 result.push_str(&type_indent.to_string(context.config));
982 let budget = try_opt!(context.config
984 .checked_sub(type_indent.width() + ";".len()));
985 ty.rewrite(context, budget, type_indent)
987 result.push_str(&ty_str);
988 result.push_str(";");
992 impl Rewrite for ast::StructField {
993 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
994 if contains_skip(&self.node.attrs) {
995 let span = context.snippet(mk_sp(self.node.attrs[0].span.lo, self.span.hi));
996 return wrap_str(span, context.config.max_width, width, offset);
999 let name = match self.node.kind {
1000 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
1001 ast::StructFieldKind::UnnamedField(_) => None,
1003 let vis = match self.node.kind {
1004 ast::StructFieldKind::NamedField(_, vis) |
1005 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
1007 let mut attr_str = try_opt!(self.node
1009 .rewrite(context, context.config.max_width - offset.width(), offset));
1010 if !attr_str.is_empty() {
1011 attr_str.push('\n');
1012 attr_str.push_str(&offset.to_string(context.config));
1015 let result = match name {
1016 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1017 None => format!("{}{}", attr_str, vis),
1020 let last_line_width = last_line_width(&result);
1021 let budget = try_opt!(width.checked_sub(last_line_width));
1022 let rewrite = try_opt!(self.node.ty.rewrite(context, budget, offset + last_line_width));
1023 Some(result + &rewrite)
1027 pub fn rewrite_static(prefix: &str,
1028 vis: ast::Visibility,
1031 mutability: ast::Mutability,
1032 expr_opt: Option<&ptr::P<ast::Expr>>,
1033 context: &RewriteContext)
1035 let prefix = format!("{}{} {}{}: ",
1036 format_visibility(vis),
1038 format_mutability(mutability),
1041 let ty_str = try_opt!(ty.rewrite(context,
1042 context.config.max_width - context.block_indent.width() -
1044 context.block_indent));
1046 if let Some(ref expr) = expr_opt {
1047 let lhs = format!("{}{} =", prefix, ty_str);
1049 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1050 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1053 let lhs = format!("{}{};", prefix, ty_str);
1058 pub fn rewrite_associated_type(ident: ast::Ident,
1059 ty_opt: Option<&ptr::P<ast::Ty>>,
1060 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1061 context: &RewriteContext,
1064 let prefix = format!("type {}", ident);
1066 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1067 let bounds: &[_] = &ty_param_bounds.as_slice();
1068 let bound_str = bounds.iter()
1069 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1070 .collect::<Vec<String>>()
1072 if bounds.len() > 0 {
1073 format!(": {}", bound_str)
1081 if let Some(ty) = ty_opt {
1082 let ty_str = try_opt!(ty.rewrite(context,
1083 context.config.max_width - context.block_indent.width() -
1086 context.block_indent));
1087 Some(format!("{} = {};", prefix, ty_str))
1089 Some(format!("{}{};", prefix, type_bounds_str))
1093 impl Rewrite for ast::FunctionRetTy {
1094 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1096 ast::FunctionRetTy::Default(_) => Some(String::new()),
1097 ast::FunctionRetTy::None(_) => {
1099 Some("-> !".to_owned())
1104 ast::FunctionRetTy::Ty(ref ty) => {
1105 let inner_width = try_opt!(width.checked_sub(3));
1106 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1112 impl Rewrite for ast::Arg {
1113 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1114 if is_named_arg(self) {
1115 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1117 if self.ty.node != ast::TyKind::Infer {
1118 result.push_str(": ");
1119 let max_width = try_opt!(width.checked_sub(result.len()));
1120 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1121 result.push_str(&ty_str);
1126 self.ty.rewrite(context, width, offset)
1131 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1133 context: &RewriteContext)
1135 match explicit_self.node {
1136 ast::SelfKind::Region(lt, m, _) => {
1137 let mut_str = format_mutability(m);
1140 let lifetime_str = try_opt!(l.rewrite(context,
1143 Some(format!("&{} {}self", lifetime_str, mut_str))
1145 None => Some(format!("&{}self", mut_str)),
1148 ast::SelfKind::Explicit(ref ty, _) => {
1149 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1151 let mutability = explicit_self_mutability(&args[0]);
1152 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1154 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1156 ast::SelfKind::Value(_) => {
1157 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1159 let mutability = explicit_self_mutability(&args[0]);
1161 Some(format!("{}self", format_mutability(mutability)))
1167 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1168 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1169 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1170 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1177 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1178 if is_named_arg(arg) {
1185 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1187 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1188 _ => arg.ty.span.hi,
1192 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1193 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1194 ident.node != token::special_idents::invalid
1200 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1202 ast::FunctionRetTy::None(ref span) |
1203 ast::FunctionRetTy::Default(ref span) => span.clone(),
1204 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1208 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1209 // Note that ty.span is the span for ty.ident, not the whole item.
1210 let lo = ty.span.lo;
1211 if let Some(ref def) = ty.default {
1212 return mk_sp(lo, def.span.hi);
1214 if ty.bounds.is_empty() {
1217 let hi = match ty.bounds[ty.bounds.len() - 1] {
1218 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1219 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1224 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1226 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1227 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1228 ast::WherePredicate::EqPredicate(ref p) => p.span,
1232 // Return type is (result, force_new_line_for_brace)
1233 fn rewrite_fn_base(context: &RewriteContext,
1237 explicit_self: Option<&ast::ExplicitSelf>,
1238 generics: &ast::Generics,
1239 unsafety: ast::Unsafety,
1240 constness: ast::Constness,
1242 vis: ast::Visibility,
1244 newline_brace: bool,
1246 -> Option<(String, bool)> {
1247 let mut force_new_line_for_brace = false;
1248 // FIXME we'll lose any comments in between parts of the function decl, but
1249 // anyone who comments there probably deserves what they get.
1251 let where_clause = &generics.where_clause;
1253 let mut result = String::with_capacity(1024);
1254 // Vis unsafety abi.
1255 result.push_str(format_visibility(vis));
1257 if let ast::Constness::Const = constness {
1258 result.push_str("const ");
1261 result.push_str(::utils::format_unsafety(unsafety));
1263 if abi != abi::Abi::Rust {
1264 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1268 result.push_str("fn ");
1269 result.push_str(&ident.to_string());
1272 let generics_indent = indent + result.len();
1273 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1274 let generics_str = try_opt!(rewrite_generics(context,
1277 context.config.max_width,
1280 result.push_str(&generics_str);
1282 // Note that if the width and indent really matter, we'll re-layout the
1283 // return type later anyway.
1284 let ret_str = try_opt!(fd.output
1285 .rewrite(&context, context.config.max_width - indent.width(), indent));
1287 let multi_line_ret_str = ret_str.contains('\n');
1288 let ret_str_len = if multi_line_ret_str {
1295 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1296 compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace);
1298 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1299 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1300 arg_indent = indent.block_indent(context.config);
1301 multi_line_budget = context.config.max_width - arg_indent.width();
1304 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1309 // Check if vertical layout was forced by compute_budget_for_args.
1310 if one_line_budget == 0 {
1311 if context.config.fn_args_paren_newline {
1313 result.push_str(&arg_indent.to_string(context.config));
1314 arg_indent = arg_indent + 1; // extra space for `(`
1317 result.push_str("(\n");
1318 result.push_str(&arg_indent.to_string(context.config));
1324 if multi_line_ret_str {
1325 one_line_budget = 0;
1328 // A conservative estimation, to goal is to be over all parens in generics
1329 let args_start = generics.ty_params
1331 .map_or(span.lo, |tp| end_typaram(tp));
1332 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1333 span_for_return(&fd.output).lo);
1334 let arg_str = try_opt!(rewrite_args(context,
1344 let multi_line_arg_str = arg_str.contains('\n');
1346 let put_args_in_block = match context.config.fn_args_layout {
1347 FnArgLayoutStyle::Block => multi_line_arg_str,
1348 FnArgLayoutStyle::BlockAlways => true,
1350 } && fd.inputs.len() > 0;
1352 if put_args_in_block {
1353 arg_indent = indent.block_indent(context.config);
1355 result.push_str(&arg_indent.to_string(context.config));
1356 result.push_str(&arg_str);
1358 result.push_str(&indent.to_string(context.config));
1361 result.push_str(&arg_str);
1366 if !ret_str.is_empty() {
1367 let ret_should_indent = match context.config.fn_args_layout {
1368 // If our args are block layout then we surely must have space.
1369 FnArgLayoutStyle::Block if put_args_in_block => false,
1370 FnArgLayoutStyle::BlockAlways => false,
1372 // If we've already gone multi-line, or the return type would push
1373 // over the max width, then put the return type on a new line.
1374 result.contains("\n") || multi_line_ret_str ||
1375 result.len() + indent.width() + ret_str_len > context.config.max_width
1378 let ret_indent = if ret_should_indent {
1379 let indent = match context.config.fn_return_indent {
1380 ReturnIndent::WithWhereClause => indent + 4,
1381 // Aligning with non-existent args looks silly.
1382 _ if arg_str.is_empty() => {
1383 force_new_line_for_brace = true;
1386 // FIXME: we might want to check that using the arg indent
1387 // doesn't blow our budget, and if it does, then fallback to
1388 // the where clause indent.
1393 result.push_str(&indent.to_string(context.config));
1397 Indent::new(indent.width(), result.len())
1400 if multi_line_ret_str {
1401 // Now that we know the proper indent and width, we need to
1402 // re-layout the return type.
1404 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1405 let ret_str = try_opt!(fd.output
1406 .rewrite(context, budget, ret_indent));
1407 result.push_str(&ret_str);
1409 result.push_str(&ret_str);
1412 // Comment between return type and the end of the decl.
1413 let snippet_lo = fd.output.span().hi;
1414 if where_clause.predicates.is_empty() {
1415 let snippet_hi = span.hi;
1416 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1417 let snippet = snippet.trim();
1418 if !snippet.is_empty() {
1420 result.push_str(snippet);
1423 // FIXME it would be nice to catch comments between the return type
1424 // and the where clause, but we don't have a span for the where
1429 let should_compress_where = match context.config.where_density {
1430 Density::Compressed => !result.contains('\n') || put_args_in_block,
1431 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1433 } || (put_args_in_block && ret_str.is_empty());
1435 let where_density = if should_compress_where {
1442 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1443 let where_clause_str = try_opt!(rewrite_where_clause(context,
1446 context.config.fn_brace_style,
1454 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1455 !where_clause_str.contains('\n') {
1459 result.push_str(&where_clause_str);
1461 Some((result, force_new_line_for_brace))
1464 fn rewrite_args(context: &RewriteContext,
1466 explicit_self: Option<&ast::ExplicitSelf>,
1467 one_line_budget: usize,
1468 multi_line_budget: usize,
1474 let mut arg_item_strs = try_opt!(args.iter()
1475 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1476 .collect::<Option<Vec<_>>>());
1478 // Account for sugary self.
1479 // FIXME: the comment for the self argument is dropped. This is blocked
1480 // on rust issue #27522.
1482 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1483 .map_or(1, |self_str| {
1484 arg_item_strs[0] = self_str;
1488 // Comments between args.
1489 let mut arg_items = Vec::new();
1491 arg_items.push(ListItem::from_str(""));
1494 // FIXME(#21): if there are no args, there might still be a comment, but
1495 // without spans for the comment or parens, there is no chance of
1496 // getting it right. You also don't get to put a comment on self, unless
1498 if args.len() >= min_args || variadic {
1499 let comment_span_start = if min_args == 2 {
1500 let second_arg_start = if arg_has_pattern(&args[1]) {
1505 let reduced_span = mk_sp(span.lo, second_arg_start);
1507 context.codemap.span_after_last(reduced_span, ",")
1512 enum ArgumentKind<'a> {
1513 Regular(&'a ast::Arg),
1517 let variadic_arg = if variadic {
1518 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1519 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1520 Some(ArgumentKind::Variadic(variadic_start))
1525 let more_items = itemize_list(context.codemap,
1526 args[min_args - 1..]
1528 .map(ArgumentKind::Regular)
1529 .chain(variadic_arg),
1533 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1534 ArgumentKind::Variadic(start) => start,
1539 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1540 ArgumentKind::Variadic(start) => start + BytePos(3),
1545 ArgumentKind::Regular(..) => None,
1546 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1552 arg_items.extend(more_items);
1555 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1556 item.item = Some(arg);
1559 let indent = match context.config.fn_arg_indent {
1560 BlockIndentStyle::Inherit => indent,
1561 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1562 BlockIndentStyle::Visual => arg_indent,
1565 let tactic = definitive_tactic(&arg_items,
1566 context.config.fn_args_density.to_list_tactic(),
1568 let budget = match tactic {
1569 DefinitiveListTactic::Horizontal => one_line_budget,
1570 _ => multi_line_budget,
1573 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1575 let end_with_newline = match context.config.fn_args_layout {
1576 FnArgLayoutStyle::Block |
1577 FnArgLayoutStyle::BlockAlways => true,
1581 let fmt = ListFormatting {
1584 trailing_separator: SeparatorTactic::Never,
1587 ends_with_newline: end_with_newline,
1588 config: context.config,
1591 write_list(&arg_items, &fmt)
1594 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1595 if let ast::PatKind::Ident(_,
1597 node: ast::Ident { name: ast::Name(0u32), .. },
1607 fn compute_budgets_for_args(context: &RewriteContext,
1611 newline_brace: bool)
1612 -> (usize, usize, Indent) {
1613 // Try keeping everything on the same line.
1614 if !result.contains("\n") {
1615 // 3 = `() `, space is before ret_string.
1616 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1620 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1622 if one_line_budget > 0 {
1623 let multi_line_budget = context.config.max_width -
1624 (indent.width() + result.len() + "()".len());
1626 return (one_line_budget, multi_line_budget, indent + result.len() + 1);
1630 // Didn't work. we must force vertical layout and put args on a newline.
1631 let new_indent = indent.block_indent(context.config);
1632 let used_space = new_indent.width() + 2; // account for `(` and `)`
1633 let max_space = context.config.max_width;
1634 if used_space <= max_space {
1635 (0, max_space - used_space, new_indent)
1637 // Whoops! bankrupt.
1638 // FIXME: take evasive action, perhaps kill the indent or something.
1639 panic!("in compute_budgets_for_args");
1643 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1644 match config.fn_brace_style {
1645 BraceStyle::AlwaysNextLine => true,
1646 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1651 fn rewrite_generics(context: &RewriteContext,
1652 generics: &ast::Generics,
1655 generics_offset: Indent,
1658 // FIXME: convert bounds to where clauses where they get too big or if
1659 // there is a where clause at all.
1660 let lifetimes: &[_] = &generics.lifetimes;
1661 let tys: &[_] = &generics.ty_params;
1662 if lifetimes.is_empty() && tys.is_empty() {
1663 return Some(String::new());
1666 let offset = match context.config.generics_indent {
1667 BlockIndentStyle::Inherit => offset,
1668 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1670 BlockIndentStyle::Visual => generics_offset + 1,
1673 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1674 // FIXME: might need to insert a newline if the generics are really long.
1676 // Strings for the generics.
1677 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1678 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1680 // Extract comments between generics.
1681 let lt_spans = lifetimes.iter().map(|l| {
1682 let hi = if l.bounds.is_empty() {
1685 l.bounds[l.bounds.len() - 1].span.hi
1687 mk_sp(l.lifetime.span.lo, hi)
1689 let ty_spans = tys.iter().map(span_for_ty_param);
1691 let items = itemize_list(context.codemap,
1692 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1696 // FIXME: don't clone
1697 |&(_, ref str)| str.clone(),
1698 context.codemap.span_after(span, "<"),
1700 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1702 Some(format!("<{}>", list_str))
1705 fn rewrite_trait_bounds(context: &RewriteContext,
1706 type_param_bounds: &ast::TyParamBounds,
1710 let bounds: &[_] = &type_param_bounds.as_slice();
1712 if bounds.is_empty() {
1713 return Some(String::new());
1716 let bound_str = bounds.iter()
1717 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1718 .collect::<Vec<String>>()
1721 let mut result = String::new();
1722 result.push_str(": ");
1723 result.push_str(&bound_str);
1727 fn rewrite_where_clause(context: &RewriteContext,
1728 where_clause: &ast::WhereClause,
1730 brace_style: BraceStyle,
1735 allow_trailing_comma: bool,
1736 span_end: Option<BytePos>)
1738 if where_clause.predicates.is_empty() {
1739 return Some(String::new());
1742 let extra_indent = match context.config.where_indent {
1743 BlockIndentStyle::Inherit => Indent::empty(),
1744 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1747 let offset = match context.config.where_pred_indent {
1748 BlockIndentStyle::Inherit => indent + extra_indent,
1749 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1750 // 6 = "where ".len()
1751 BlockIndentStyle::Visual => indent + extra_indent + 6,
1753 // FIXME: if where_pred_indent != Visual, then the budgets below might
1754 // be out by a char or two.
1756 let budget = context.config.max_width - offset.width();
1757 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1758 // If we don't have the start of the next span, then use the end of the
1759 // predicates, but that means we miss comments.
1760 let len = where_clause.predicates.len();
1761 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1762 let span_end = span_end.unwrap_or(end_of_preds);
1763 let items = itemize_list(context.codemap,
1764 where_clause.predicates.iter(),
1766 |pred| span_for_where_pred(pred).lo,
1767 |pred| span_for_where_pred(pred).hi,
1768 |pred| pred.rewrite(&context, budget, offset),
1771 let item_vec = items.collect::<Vec<_>>();
1772 // FIXME: we don't need to collect here if the where_layout isn't
1773 // HorizontalVertical.
1774 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1775 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1777 let fmt = ListFormatting {
1780 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1783 ends_with_newline: true,
1784 config: context.config,
1786 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1788 let end_length = if terminator == "{" {
1789 // If the brace is on the next line we don't need to count it otherwise it needs two
1792 BraceStyle::AlwaysNextLine => 0,
1793 BraceStyle::PreferSameLine => 2,
1794 BraceStyle::SameLineWhere => 0,
1796 } else if terminator == "=" {
1801 if density == Density::Tall || preds_str.contains('\n') ||
1802 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1803 Some(format!("\n{}where {}",
1804 (indent + extra_indent).to_string(context.config),
1807 Some(format!(" where {}", preds_str))
1811 fn format_header(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
1812 format!("{}{}{}", format_visibility(vis), item_name, ident)
1815 fn format_generics(context: &RewriteContext,
1816 generics: &ast::Generics,
1819 brace_style: BraceStyle,
1820 force_same_line_brace: bool,
1822 generics_offset: Indent,
1825 let mut result = try_opt!(rewrite_generics(context,
1828 context.config.max_width,
1832 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1833 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1834 let where_clause_str = try_opt!(rewrite_where_clause(context,
1835 &generics.where_clause,
1838 context.block_indent,
1844 result.push_str(&where_clause_str);
1845 if !force_same_line_brace &&
1846 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1848 result.push_str(&context.block_indent.to_string(context.config));
1852 result.push_str(opener);
1854 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1856 result.push_str(&context.block_indent.to_string(context.config));
1860 result.push_str(opener);