1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use utils::{CodeMapSpanUtils, format_mutability, format_visibility, contains_skip, end_typaram,
15 wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
17 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
18 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
19 use comment::{FindUncommented, contains_comment};
20 use visitor::FmtVisitor;
21 use rewrite::{Rewrite, RewriteContext};
22 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use syntax::{ast, abi, ptr, codemap};
25 use syntax::codemap::{Span, BytePos, mk_sp};
26 use syntax::parse::token;
27 use syntax::ast::ImplItem;
29 // Statements of the form
30 // let pat: ty = init;
31 impl Rewrite for ast::Local {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33 let mut result = "let ".to_owned();
34 let pattern_offset = offset + result.len();
36 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
39 result.push_str(&pat_str);
41 // String that is placed within the assignment pattern and expression.
43 let mut infix = String::new();
45 if let Some(ref ty) = self.ty {
48 let indent = offset + last_line_width(&result) + 2;
49 let budget = try_opt!(width.checked_sub(indent.width() + 1));
50 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
53 infix.push_str(&rewrite);
56 if self.init.is_some() {
63 result.push_str(&infix);
65 if let Some(ref ex) = self.init {
66 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68 // 1 = trailing semicolon;
70 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
78 impl<'a> FmtVisitor<'a> {
79 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
80 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
81 self.buffer.push_str(&abi_str);
83 let snippet = self.snippet(span);
84 let brace_pos = snippet.find_uncommented("{").unwrap();
86 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
87 self.buffer.push_str("{");
89 // FIXME: this skips comments between the extern keyword and the opening
91 self.last_pos = span.lo + BytePos(brace_pos as u32);
92 self.block_indent = self.block_indent.block_indent(self.config);
94 for item in &fm.items {
95 self.format_foreign_item(&*item);
98 self.block_indent = self.block_indent.block_unindent(self.config);
99 self.format_missing_with_indent(span.hi - BytePos(1));
102 self.buffer.push_str("}");
103 self.last_pos = span.hi;
106 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
107 self.format_missing_with_indent(item.span.lo);
108 // Drop semicolon or it will be interpreted as comment.
109 // FIXME: this may be a faulty span from libsyntax.
110 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
113 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
114 let indent = self.block_indent;
115 let rewrite = rewrite_fn_base(&self.get_context(),
121 ast::Unsafety::Normal,
122 ast::Constness::NotConst,
123 // These are not actually rust functions,
124 // but we format them as such.
132 Some((new_fn, _)) => {
133 self.buffer.push_str(&new_fn);
134 self.buffer.push_str(";");
136 None => self.format_missing(item.span.hi),
139 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
140 // FIXME(#21): we're dropping potential comments in between the
141 // function keywords here.
142 let vis = format_visibility(&item.vis);
143 let mut_str = if is_mutable {
148 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
149 let offset = self.block_indent + prefix.len();
151 let width = self.config.max_width - offset.width() - 1;
152 let rewrite = ty.rewrite(&self.get_context(), width, offset);
156 self.buffer.push_str(&prefix);
157 self.buffer.push_str(&result);
158 self.buffer.push_str(";");
160 None => self.format_missing(item.span.hi),
165 self.last_pos = item.span.hi;
168 pub fn rewrite_fn(&mut self,
172 explicit_self: Option<&ast::ExplicitSelf>,
173 generics: &ast::Generics,
174 unsafety: ast::Unsafety,
175 constness: ast::Constness,
177 vis: &ast::Visibility,
181 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
182 let context = self.get_context();
184 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
185 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
186 !context.config.fn_empty_single_line;
188 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
202 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
203 newline_brace = false;
204 } else if force_newline_brace {
205 newline_brace = true;
208 // Prepare for the function body by possibly adding a newline and
210 // FIXME we'll miss anything between the end of the signature and the
211 // start of the body, but we need more spans from the compiler to solve
215 result.push_str(&indent.to_string(self.config));
220 self.single_line_fn(&result, block).or_else(|| Some(result))
223 pub fn rewrite_required_fn(&mut self,
226 sig: &ast::MethodSig,
229 // Drop semicolon or it will be interpreted as comment.
230 let span = mk_sp(span.lo, span.hi - BytePos(1));
231 let context = self.get_context();
233 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
237 Some(&sig.explicit_self),
242 &ast::Visibility::Inherited,
247 // Re-attach semicolon
253 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
254 if fn_str.contains('\n') {
258 let codemap = self.get_context().codemap;
260 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
261 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
262 return Some(format!("{}{{}}", fn_str));
265 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
267 if let Some(ref e) = block.expr {
268 let suffix = if semicolon_for_expr(e) {
274 e.rewrite(&self.get_context(),
275 self.config.max_width - self.block_indent.width(),
278 .or_else(|| Some(self.snippet(e.span)))
279 } else if let Some(ref stmt) = block.stmts.first() {
280 stmt.rewrite(&self.get_context(),
281 self.config.max_width - self.block_indent.width(),
288 if let Some(res) = rewrite {
289 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
290 if !res.contains('\n') && width <= self.config.max_width {
291 return Some(format!("{}{{ {} }}", fn_str, res));
299 pub fn visit_enum(&mut self,
301 vis: &ast::Visibility,
302 enum_def: &ast::EnumDef,
303 generics: &ast::Generics,
305 self.buffer.push_str(&format_header("enum ", ident, vis));
307 let enum_snippet = self.snippet(span);
308 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
309 let generics_str = format_generics(&self.get_context(),
313 self.config.item_brace_style,
314 enum_def.variants.is_empty(),
316 self.block_indent.block_indent(self.config),
317 mk_sp(span.lo, body_start))
319 self.buffer.push_str(&generics_str);
321 self.last_pos = body_start;
323 self.block_indent = self.block_indent.block_indent(self.config);
324 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
326 Some(ref body_str) => self.buffer.push_str(&body_str),
327 None => self.format_missing(span.hi - BytePos(1)),
329 self.block_indent = self.block_indent.block_unindent(self.config);
331 if variant_list.is_some() {
332 self.buffer.push_str(&self.block_indent.to_string(self.config));
334 self.buffer.push_str("}");
335 self.last_pos = span.hi;
338 // Format the body of an enum definition
339 fn format_variant_list(&self,
340 enum_def: &ast::EnumDef,
344 if enum_def.variants.is_empty() {
347 let mut result = String::with_capacity(1024);
349 let indentation = self.block_indent.to_string(self.config);
350 result.push_str(&indentation);
352 let items = itemize_list(self.codemap,
353 enum_def.variants.iter(),
356 if !f.node.attrs.is_empty() {
357 f.node.attrs[0].span.lo
363 |f| self.format_variant(f),
367 let budget = self.config.max_width - self.block_indent.width() - 2;
368 let fmt = ListFormatting {
369 tactic: DefinitiveListTactic::Vertical,
371 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
372 indent: self.block_indent,
374 ends_with_newline: true,
378 let list = try_opt!(write_list(items, &fmt));
379 result.push_str(&list);
384 // Variant of an enum.
385 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
386 if contains_skip(&field.node.attrs) {
387 let lo = field.node.attrs[0].span.lo;
388 let span = mk_sp(lo, field.span.hi);
389 return Some(self.snippet(span));
392 let indent = self.block_indent;
393 let mut result = try_opt!(field.node
395 .rewrite(&self.get_context(),
396 self.config.max_width - indent.width(),
398 if !result.is_empty() {
400 result.push_str(&indent.to_string(self.config));
403 let context = self.get_context();
404 let variant_body = match field.node.data {
405 ast::VariantData::Tuple(..) |
406 ast::VariantData::Struct(..) => {
407 // FIXME: Should limit the width, as we have a trailing comma
408 format_struct(&context,
411 &ast::Visibility::Inherited,
416 Some(self.config.struct_variant_width))
418 ast::VariantData::Unit(..) => {
419 let tag = if let Some(ref expr) = field.node.disr_expr {
420 format!("{} = {}", field.node.name, self.snippet(expr.span))
422 field.node.name.to_string()
426 self.config.max_width,
427 self.config.max_width - indent.width(),
432 if let Some(variant_str) = variant_body {
433 result.push_str(&variant_str);
441 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
442 if let ast::ItemKind::Impl(unsafety,
447 ref items) = item.node {
448 let mut result = String::new();
449 result.push_str(&*format_visibility(&item.vis));
450 result.push_str(format_unsafety(unsafety));
451 result.push_str("impl");
453 let lo = context.codemap.span_after(item.span, "impl");
454 let hi = match *trait_ref {
455 Some(ref tr) => tr.path.span.lo,
456 None => self_ty.span.lo,
458 let generics_str = try_opt!(rewrite_generics(context,
461 context.config.max_width,
462 offset + result.len(),
464 result.push_str(&generics_str);
466 // FIXME might need to linebreak in the impl header, here would be a
469 if polarity == ast::ImplPolarity::Negative {
470 result.push_str("!");
472 if let Some(ref trait_ref) = *trait_ref {
473 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
474 let indent = offset + result.len();
475 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
476 result.push_str(" for ");
479 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
480 let indent = offset + result.len();
481 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
483 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
484 let where_clause_str = try_opt!(rewrite_where_clause(context,
485 &generics.where_clause,
487 context.config.item_brace_style,
488 context.block_indent,
490 context.config.where_density,
495 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
496 result.push_str(&where_clause_str);
497 if where_clause_str.contains('\n') {
498 let white_space = offset.to_string(context.config);
499 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
501 result.push_str(" {}");
506 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
508 let width = context.block_indent.width() + context.config.tab_spaces - 1;
509 let where_indent = Indent::new(0, width);
510 result.push_str(&where_indent.to_string(context.config));
512 result.push_str(&where_clause_str);
514 match context.config.item_brace_style {
515 BraceStyle::AlwaysNextLine => result.push('\n'),
516 BraceStyle::PreferSameLine => result.push(' '),
517 BraceStyle::SameLineWhere => {
518 if !where_clause_str.is_empty() {
520 result.push_str(&offset.to_string(context.config));
529 let snippet = context.snippet(item.span);
530 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
532 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
533 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
534 visitor.block_indent = context.block_indent.block_indent(context.config);
535 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
538 visitor.visit_impl_item(&item);
541 visitor.format_missing(item.span.hi - BytePos(1));
543 let inner_indent_str = visitor.block_indent.to_string(context.config);
544 let outer_indent_str = context.block_indent.to_string(context.config);
547 result.push_str(&inner_indent_str);
548 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
550 result.push_str(&outer_indent_str);
553 if result.chars().last().unwrap() == '{' {
564 fn is_impl_single_line(context: &RewriteContext,
565 items: &Vec<ImplItem>,
567 where_clause_str: &str,
570 let snippet = context.snippet(item.span);
571 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
573 Some(context.config.impl_empty_single_line && items.is_empty() &&
574 result.len() + where_clause_str.len() <= context.config.max_width &&
575 !contains_comment(&snippet[open_pos..]))
578 pub fn format_struct(context: &RewriteContext,
581 vis: &ast::Visibility,
582 struct_def: &ast::VariantData,
583 generics: Option<&ast::Generics>,
586 one_line_width: Option<usize>)
589 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
590 ast::VariantData::Tuple(ref fields, _) => {
591 format_tuple_struct(context,
600 ast::VariantData::Struct(ref fields, _) => {
601 format_struct_struct(context,
614 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
615 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
617 let mut result = String::new();
618 let header = format!("{}{}trait {}",
619 format_visibility(&item.vis),
620 format_unsafety(unsafety),
623 result.push_str(&header);
625 let body_lo = context.codemap.span_after(item.span, "{");
627 let generics_str = try_opt!(rewrite_generics(context,
630 context.config.max_width,
631 offset + result.len(),
632 mk_sp(item.span.lo, body_lo)));
633 result.push_str(&generics_str);
635 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
638 context.config.max_width));
639 // If the trait, generics, and trait bound cannot fit on the same line,
640 // put the trait bounds on an indented new line
641 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
642 context.config.ideal_width {
644 let width = context.block_indent.width() + context.config.tab_spaces;
645 let trait_indent = Indent::new(0, width);
646 result.push_str(&trait_indent.to_string(context.config));
648 result.push_str(&trait_bound_str);
650 let has_body = !trait_items.is_empty();
653 if (context.config.where_density == Density::Compressed &&
654 (!result.contains('\n') ||
655 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
656 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
657 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
658 !result.contains('\n')) {
664 let where_budget = try_opt!(context.config
666 .checked_sub(last_line_width(&result)));
667 let where_clause_str = try_opt!(rewrite_where_clause(context,
668 &generics.where_clause,
670 context.config.item_brace_style,
671 context.block_indent,
677 // If the where clause cannot fit on the same line,
678 // put the where clause on a new line
679 if !where_clause_str.contains('\n') &&
680 last_line_width(&result) + where_clause_str.len() + offset.width() >
681 context.config.ideal_width {
683 let width = context.block_indent.width() + context.config.tab_spaces - 1;
684 let where_indent = Indent::new(0, width);
685 result.push_str(&where_indent.to_string(context.config));
687 result.push_str(&where_clause_str);
689 match context.config.item_brace_style {
690 BraceStyle::AlwaysNextLine => {
692 result.push_str(&offset.to_string(context.config));
694 BraceStyle::PreferSameLine => result.push(' '),
695 BraceStyle::SameLineWhere => {
696 if !where_clause_str.is_empty() &&
697 (trait_items.len() > 0 || result.contains('\n')) {
699 result.push_str(&offset.to_string(context.config));
707 let snippet = context.snippet(item.span);
708 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
710 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
711 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
712 visitor.block_indent = context.block_indent.block_indent(context.config);
713 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
715 for item in trait_items {
716 visitor.visit_trait_item(&item);
719 visitor.format_missing(item.span.hi - BytePos(1));
721 let inner_indent_str = visitor.block_indent.to_string(context.config);
722 let outer_indent_str = context.block_indent.to_string(context.config);
725 result.push_str(&inner_indent_str);
726 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
728 result.push_str(&outer_indent_str);
729 } else if result.contains('\n') {
740 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
741 format!("{};", format_header(item_name, ident, vis))
744 fn format_struct_struct(context: &RewriteContext,
747 vis: &ast::Visibility,
748 fields: &[ast::StructField],
749 generics: Option<&ast::Generics>,
752 one_line_width: Option<usize>)
754 let mut result = String::with_capacity(1024);
756 let header_str = format_header(item_name, ident, vis);
757 result.push_str(&header_str);
759 let body_lo = context.codemap.span_after(span, "{");
761 let generics_str = match generics {
763 try_opt!(format_generics(context,
767 context.config.item_brace_style,
770 offset + header_str.len(),
771 mk_sp(span.lo, body_lo)))
774 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
775 format!("\n{}{{", context.block_indent.to_string(context.config))
781 result.push_str(&generics_str);
783 // FIXME(#919): properly format empty structs and their comments.
784 if fields.is_empty() {
785 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
789 let item_indent = offset.block_indent(context.config);
791 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
793 let items = itemize_list(context.codemap,
797 // Include attributes and doc comments, if present
798 if !field.attrs.is_empty() {
799 field.attrs[0].span.lo
804 |field| field.ty.span.hi,
805 |field| field.rewrite(context, item_budget, item_indent),
806 context.codemap.span_after(span, "{"),
808 .collect::<Vec<_>>();
810 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
812 let tactic = match one_line_width {
813 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
814 None => DefinitiveListTactic::Vertical,
817 let fmt = ListFormatting {
820 trailing_separator: context.config.struct_trailing_comma,
823 ends_with_newline: true,
824 config: context.config,
826 let items_str = try_opt!(write_list(&items, &fmt));
827 if one_line_width.is_some() && !items_str.contains('\n') {
828 Some(format!("{} {} }}", result, items_str))
830 Some(format!("{}\n{}{}\n{}}}",
832 offset.block_indent(context.config).to_string(context.config),
834 offset.to_string(context.config)))
838 fn format_tuple_struct(context: &RewriteContext,
841 vis: &ast::Visibility,
842 fields: &[ast::StructField],
843 generics: Option<&ast::Generics>,
847 let mut result = String::with_capacity(1024);
849 let header_str = format_header(item_name, ident, vis);
850 result.push_str(&header_str);
852 // FIXME(#919): don't lose comments on empty tuple structs.
853 let body_lo = if fields.is_empty() {
859 let where_clause_str = match generics {
860 Some(ref generics) => {
861 let generics_str = try_opt!(rewrite_generics(context,
864 context.config.max_width,
865 offset + header_str.len(),
866 mk_sp(span.lo, body_lo)));
867 result.push_str(&generics_str);
869 let where_budget = try_opt!(context.config
871 .checked_sub(last_line_width(&result)));
872 try_opt!(rewrite_where_clause(context,
873 &generics.where_clause,
875 context.config.item_brace_style,
876 context.block_indent,
883 None => "".to_owned(),
887 let item_indent = context.block_indent + result.len();
889 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
891 let items = itemize_list(context.codemap,
895 // Include attributes and doc comments, if present
896 if !field.attrs.is_empty() {
897 field.attrs[0].span.lo
902 |field| field.ty.span.hi,
903 |field| field.rewrite(context, item_budget, item_indent),
904 context.codemap.span_after(span, "("),
906 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
907 result.push_str(&body);
910 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
911 (result.contains('\n') ||
912 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
913 context.config.max_width) {
914 // We need to put the where clause on a new line, but we didn'to_string
915 // know that earlier, so the where clause will not be indented properly.
917 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
918 .to_string(context.config));
920 result.push_str(&where_clause_str);
925 pub fn rewrite_type_alias(context: &RewriteContext,
929 generics: &ast::Generics,
930 vis: &ast::Visibility,
933 let mut result = String::new();
935 result.push_str(&format_visibility(&vis));
936 result.push_str("type ");
937 result.push_str(&ident.to_string());
939 let generics_indent = indent + result.len();
940 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
941 let generics_width = context.config.max_width - " =".len();
942 let generics_str = try_opt!(rewrite_generics(context,
949 result.push_str(&generics_str);
951 let where_budget = try_opt!(context.config
953 .checked_sub(last_line_width(&result)));
954 let where_clause_str = try_opt!(rewrite_where_clause(context,
955 &generics.where_clause,
957 context.config.item_brace_style,
960 context.config.where_density,
964 result.push_str(&where_clause_str);
965 result.push_str(" = ");
967 let line_width = last_line_width(&result);
968 // This checked_sub may fail as the extra space after '=' is not taken into account
969 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
970 let budget = context.config
972 .checked_sub(indent.width() + line_width + ";".len())
974 let type_indent = indent + line_width;
975 // Try to fit the type on the same line
976 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
978 // The line was too short, try to put the type on the next line
980 // Remove the space after '='
982 let type_indent = indent.block_indent(context.config);
984 result.push_str(&type_indent.to_string(context.config));
985 let budget = try_opt!(context.config
987 .checked_sub(type_indent.width() + ";".len()));
988 ty.rewrite(context, budget, type_indent)
990 result.push_str(&ty_str);
991 result.push_str(";");
995 impl Rewrite for ast::StructField {
996 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
997 if contains_skip(&self.attrs) {
998 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
999 return wrap_str(span, context.config.max_width, width, offset);
1002 let name = self.ident;
1003 let vis = format_visibility(&self.vis);
1004 let mut attr_str = try_opt!(self.attrs
1005 .rewrite(context, context.config.max_width - offset.width(), offset));
1006 if !attr_str.is_empty() {
1007 attr_str.push('\n');
1008 attr_str.push_str(&offset.to_string(context.config));
1011 let result = match name {
1012 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1013 None => format!("{}{}", attr_str, vis),
1016 let last_line_width = last_line_width(&result);
1017 let budget = try_opt!(width.checked_sub(last_line_width));
1018 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1019 Some(result + &rewrite)
1023 pub fn rewrite_static(prefix: &str,
1024 vis: &ast::Visibility,
1027 mutability: ast::Mutability,
1028 expr_opt: Option<&ptr::P<ast::Expr>>,
1029 context: &RewriteContext)
1031 let prefix = format!("{}{} {}{}: ",
1032 format_visibility(vis),
1034 format_mutability(mutability),
1037 let ty_str = try_opt!(ty.rewrite(context,
1038 context.config.max_width - context.block_indent.width() -
1040 context.block_indent));
1042 if let Some(ref expr) = expr_opt {
1043 let lhs = format!("{}{} =", prefix, ty_str);
1045 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1046 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1049 let lhs = format!("{}{};", prefix, ty_str);
1054 pub fn rewrite_associated_type(ident: ast::Ident,
1055 ty_opt: Option<&ptr::P<ast::Ty>>,
1056 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1057 context: &RewriteContext,
1060 let prefix = format!("type {}", ident);
1062 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1063 let bounds: &[_] = &ty_param_bounds;
1064 let bound_str = bounds.iter()
1065 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1066 .collect::<Vec<String>>()
1068 if bounds.len() > 0 {
1069 format!(": {}", bound_str)
1077 if let Some(ty) = ty_opt {
1078 let ty_str = try_opt!(ty.rewrite(context,
1079 context.config.max_width - context.block_indent.width() -
1082 context.block_indent));
1083 Some(format!("{} = {};", prefix, ty_str))
1085 Some(format!("{}{};", prefix, type_bounds_str))
1089 impl Rewrite for ast::FunctionRetTy {
1090 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1092 ast::FunctionRetTy::Default(_) => Some(String::new()),
1093 ast::FunctionRetTy::None(_) => {
1095 Some("-> !".to_owned())
1100 ast::FunctionRetTy::Ty(ref ty) => {
1101 let inner_width = try_opt!(width.checked_sub(3));
1102 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1108 impl Rewrite for ast::Arg {
1109 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1110 if is_named_arg(self) {
1111 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1113 if self.ty.node != ast::TyKind::Infer {
1114 result.push_str(": ");
1115 let max_width = try_opt!(width.checked_sub(result.len()));
1116 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1117 result.push_str(&ty_str);
1122 self.ty.rewrite(context, width, offset)
1127 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1129 context: &RewriteContext)
1131 match explicit_self.node {
1132 ast::SelfKind::Region(lt, m, _) => {
1133 let mut_str = format_mutability(m);
1137 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1138 Some(format!("&{} {}self", lifetime_str, mut_str))
1140 None => Some(format!("&{}self", mut_str)),
1143 ast::SelfKind::Explicit(ref ty, _) => {
1144 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1146 let mutability = explicit_self_mutability(&args[0]);
1147 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1149 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1151 ast::SelfKind::Value(_) => {
1152 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1154 let mutability = explicit_self_mutability(&args[0]);
1156 Some(format!("{}self", format_mutability(mutability)))
1162 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1163 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1164 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1165 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1172 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1173 if is_named_arg(arg) {
1180 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1182 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1183 _ => arg.ty.span.hi,
1187 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1188 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1189 ident.node != token::keywords::Invalid.ident()
1195 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1197 ast::FunctionRetTy::None(ref span) |
1198 ast::FunctionRetTy::Default(ref span) => span.clone(),
1199 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1203 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1204 // Note that ty.span is the span for ty.ident, not the whole item.
1205 let lo = ty.span.lo;
1206 if let Some(ref def) = ty.default {
1207 return mk_sp(lo, def.span.hi);
1209 if ty.bounds.is_empty() {
1212 let hi = match ty.bounds[ty.bounds.len() - 1] {
1213 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1214 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1219 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1221 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1222 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1223 ast::WherePredicate::EqPredicate(ref p) => p.span,
1227 // Return type is (result, force_new_line_for_brace)
1228 fn rewrite_fn_base(context: &RewriteContext,
1232 explicit_self: Option<&ast::ExplicitSelf>,
1233 generics: &ast::Generics,
1234 unsafety: ast::Unsafety,
1235 constness: ast::Constness,
1237 vis: &ast::Visibility,
1239 newline_brace: bool,
1241 -> Option<(String, bool)> {
1242 let mut force_new_line_for_brace = false;
1243 // FIXME we'll lose any comments in between parts of the function decl, but
1244 // anyone who comments there probably deserves what they get.
1246 let where_clause = &generics.where_clause;
1248 let mut result = String::with_capacity(1024);
1249 // Vis unsafety abi.
1250 result.push_str(&*format_visibility(vis));
1252 if let ast::Constness::Const = constness {
1253 result.push_str("const ");
1256 result.push_str(::utils::format_unsafety(unsafety));
1258 if abi != abi::Abi::Rust {
1259 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1263 result.push_str("fn ");
1264 result.push_str(&ident.to_string());
1267 let generics_indent = indent + result.len();
1268 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1269 let generics_str = try_opt!(rewrite_generics(context,
1272 context.config.max_width,
1275 result.push_str(&generics_str);
1277 // Note that if the width and indent really matter, we'll re-layout the
1278 // return type later anyway.
1279 let ret_str = try_opt!(fd.output
1280 .rewrite(&context, context.config.max_width - indent.width(), indent));
1282 let multi_line_ret_str = ret_str.contains('\n');
1283 let ret_str_len = if multi_line_ret_str {
1290 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1291 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1293 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1294 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1295 arg_indent = indent.block_indent(context.config);
1296 multi_line_budget = context.config.max_width - arg_indent.width();
1299 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1304 // Check if vertical layout was forced by compute_budget_for_args.
1305 if one_line_budget == 0 {
1306 if context.config.fn_args_paren_newline {
1308 result.push_str(&arg_indent.to_string(context.config));
1309 arg_indent = arg_indent + 1; // extra space for `(`
1312 result.push_str("(\n");
1313 result.push_str(&arg_indent.to_string(context.config));
1319 if multi_line_ret_str {
1320 one_line_budget = 0;
1323 // A conservative estimation, to goal is to be over all parens in generics
1324 let args_start = generics.ty_params
1326 .map_or(span.lo, |tp| end_typaram(tp));
1327 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1328 span_for_return(&fd.output).lo);
1329 let arg_str = try_opt!(rewrite_args(context,
1339 let multi_line_arg_str = arg_str.contains('\n');
1341 let put_args_in_block = match context.config.fn_args_layout {
1342 FnArgLayoutStyle::Block => multi_line_arg_str,
1343 FnArgLayoutStyle::BlockAlways => true,
1345 } && fd.inputs.len() > 0;
1347 if put_args_in_block {
1348 arg_indent = indent.block_indent(context.config);
1350 result.push_str(&arg_indent.to_string(context.config));
1351 result.push_str(&arg_str);
1353 result.push_str(&indent.to_string(context.config));
1356 result.push_str(&arg_str);
1361 if !ret_str.is_empty() {
1362 let ret_should_indent = match context.config.fn_args_layout {
1363 // If our args are block layout then we surely must have space.
1364 FnArgLayoutStyle::Block if put_args_in_block => false,
1365 FnArgLayoutStyle::BlockAlways => false,
1367 // If we've already gone multi-line, or the return type would push
1368 // over the max width, then put the return type on a new line.
1369 result.contains("\n") || multi_line_ret_str ||
1370 result.len() + indent.width() + ret_str_len > context.config.max_width
1373 let ret_indent = if ret_should_indent {
1374 let indent = match context.config.fn_return_indent {
1375 ReturnIndent::WithWhereClause => indent + 4,
1376 // Aligning with non-existent args looks silly.
1377 _ if arg_str.is_empty() => {
1378 force_new_line_for_brace = true;
1381 // FIXME: we might want to check that using the arg indent
1382 // doesn't blow our budget, and if it does, then fallback to
1383 // the where clause indent.
1388 result.push_str(&indent.to_string(context.config));
1392 Indent::new(indent.width(), result.len())
1395 if multi_line_ret_str {
1396 // Now that we know the proper indent and width, we need to
1397 // re-layout the return type.
1399 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1400 let ret_str = try_opt!(fd.output
1401 .rewrite(context, budget, ret_indent));
1402 result.push_str(&ret_str);
1404 result.push_str(&ret_str);
1407 // Comment between return type and the end of the decl.
1408 let snippet_lo = fd.output.span().hi;
1409 if where_clause.predicates.is_empty() {
1410 let snippet_hi = span.hi;
1411 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1412 let snippet = snippet.trim();
1413 if !snippet.is_empty() {
1415 result.push_str(snippet);
1418 // FIXME it would be nice to catch comments between the return type
1419 // and the where clause, but we don't have a span for the where
1424 let should_compress_where = match context.config.where_density {
1425 Density::Compressed => !result.contains('\n') || put_args_in_block,
1426 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1428 } || (put_args_in_block && ret_str.is_empty());
1430 let where_density = if should_compress_where {
1437 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1438 let where_clause_str = try_opt!(rewrite_where_clause(context,
1441 context.config.fn_brace_style,
1449 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1450 !where_clause_str.contains('\n') {
1454 result.push_str(&where_clause_str);
1456 Some((result, force_new_line_for_brace))
1459 fn rewrite_args(context: &RewriteContext,
1461 explicit_self: Option<&ast::ExplicitSelf>,
1462 one_line_budget: usize,
1463 multi_line_budget: usize,
1469 let mut arg_item_strs = try_opt!(args.iter()
1470 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1471 .collect::<Option<Vec<_>>>());
1473 // Account for sugary self.
1474 // FIXME: the comment for the self argument is dropped. This is blocked
1475 // on rust issue #27522.
1477 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1478 .map_or(1, |self_str| {
1479 arg_item_strs[0] = self_str;
1483 // Comments between args.
1484 let mut arg_items = Vec::new();
1486 arg_items.push(ListItem::from_str(""));
1489 // FIXME(#21): if there are no args, there might still be a comment, but
1490 // without spans for the comment or parens, there is no chance of
1491 // getting it right. You also don't get to put a comment on self, unless
1493 if args.len() >= min_args || variadic {
1494 let comment_span_start = if min_args == 2 {
1495 let second_arg_start = if arg_has_pattern(&args[1]) {
1500 let reduced_span = mk_sp(span.lo, second_arg_start);
1502 context.codemap.span_after_last(reduced_span, ",")
1507 enum ArgumentKind<'a> {
1508 Regular(&'a ast::Arg),
1512 let variadic_arg = if variadic {
1513 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1514 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1515 Some(ArgumentKind::Variadic(variadic_start))
1520 let more_items = itemize_list(context.codemap,
1521 args[min_args - 1..]
1523 .map(ArgumentKind::Regular)
1524 .chain(variadic_arg),
1528 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1529 ArgumentKind::Variadic(start) => start,
1534 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1535 ArgumentKind::Variadic(start) => start + BytePos(3),
1540 ArgumentKind::Regular(..) => None,
1541 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1547 arg_items.extend(more_items);
1550 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1551 item.item = Some(arg);
1554 let indent = match context.config.fn_arg_indent {
1555 BlockIndentStyle::Inherit => indent,
1556 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1557 BlockIndentStyle::Visual => arg_indent,
1560 let tactic = definitive_tactic(&arg_items,
1561 context.config.fn_args_density.to_list_tactic(),
1563 let budget = match tactic {
1564 DefinitiveListTactic::Horizontal => one_line_budget,
1565 _ => multi_line_budget,
1568 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1570 let end_with_newline = match context.config.fn_args_layout {
1571 FnArgLayoutStyle::Block |
1572 FnArgLayoutStyle::BlockAlways => true,
1576 let fmt = ListFormatting {
1579 trailing_separator: SeparatorTactic::Never,
1582 ends_with_newline: end_with_newline,
1583 config: context.config,
1586 write_list(&arg_items, &fmt)
1589 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1590 if let ast::PatKind::Ident(_,
1592 node: ast::Ident { name: ast::Name(0u32), .. },
1602 fn compute_budgets_for_args(context: &RewriteContext,
1606 newline_brace: bool)
1607 -> Option<((usize, usize, Indent))> {
1608 // Try keeping everything on the same line.
1609 if !result.contains("\n") {
1610 // 3 = `() `, space is before ret_string.
1611 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1615 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1617 if one_line_budget > 0 {
1619 let multi_line_budget =
1620 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1622 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1626 // Didn't work. we must force vertical layout and put args on a newline.
1627 let new_indent = indent.block_indent(context.config);
1628 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1629 let max_space = context.config.max_width;
1630 if used_space <= max_space {
1631 Some((0, max_space - used_space, new_indent))
1633 // Whoops! bankrupt.
1638 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1639 match config.fn_brace_style {
1640 BraceStyle::AlwaysNextLine => true,
1641 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1646 fn rewrite_generics(context: &RewriteContext,
1647 generics: &ast::Generics,
1650 generics_offset: Indent,
1653 // FIXME: convert bounds to where clauses where they get too big or if
1654 // there is a where clause at all.
1655 let lifetimes: &[_] = &generics.lifetimes;
1656 let tys: &[_] = &generics.ty_params;
1657 if lifetimes.is_empty() && tys.is_empty() {
1658 return Some(String::new());
1661 let offset = match context.config.generics_indent {
1662 BlockIndentStyle::Inherit => offset,
1663 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1665 BlockIndentStyle::Visual => generics_offset + 1,
1668 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1669 // FIXME: might need to insert a newline if the generics are really long.
1671 // Strings for the generics.
1672 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1673 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1675 // Extract comments between generics.
1676 let lt_spans = lifetimes.iter().map(|l| {
1677 let hi = if l.bounds.is_empty() {
1680 l.bounds[l.bounds.len() - 1].span.hi
1682 mk_sp(l.lifetime.span.lo, hi)
1684 let ty_spans = tys.iter().map(span_for_ty_param);
1686 let items = itemize_list(context.codemap,
1687 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1691 // FIXME: don't clone
1692 |&(_, ref str)| str.clone(),
1693 context.codemap.span_after(span, "<"),
1695 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1697 Some(format!("<{}>", list_str))
1700 fn rewrite_trait_bounds(context: &RewriteContext,
1701 type_param_bounds: &ast::TyParamBounds,
1705 let bounds: &[_] = &type_param_bounds;
1707 if bounds.is_empty() {
1708 return Some(String::new());
1711 let bound_str = bounds.iter()
1712 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1713 .collect::<Vec<String>>()
1716 let mut result = String::new();
1717 result.push_str(": ");
1718 result.push_str(&bound_str);
1722 fn rewrite_where_clause(context: &RewriteContext,
1723 where_clause: &ast::WhereClause,
1725 brace_style: BraceStyle,
1730 allow_trailing_comma: bool,
1731 span_end: Option<BytePos>)
1733 if where_clause.predicates.is_empty() {
1734 return Some(String::new());
1737 let extra_indent = match context.config.where_indent {
1738 BlockIndentStyle::Inherit => Indent::empty(),
1739 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1742 let offset = match context.config.where_pred_indent {
1743 BlockIndentStyle::Inherit => indent + extra_indent,
1744 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1745 // 6 = "where ".len()
1746 BlockIndentStyle::Visual => indent + extra_indent + 6,
1748 // FIXME: if where_pred_indent != Visual, then the budgets below might
1749 // be out by a char or two.
1751 let budget = context.config.max_width - offset.width();
1752 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1753 // If we don't have the start of the next span, then use the end of the
1754 // predicates, but that means we miss comments.
1755 let len = where_clause.predicates.len();
1756 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1757 let span_end = span_end.unwrap_or(end_of_preds);
1758 let items = itemize_list(context.codemap,
1759 where_clause.predicates.iter(),
1761 |pred| span_for_where_pred(pred).lo,
1762 |pred| span_for_where_pred(pred).hi,
1763 |pred| pred.rewrite(&context, budget, offset),
1766 let item_vec = items.collect::<Vec<_>>();
1767 // FIXME: we don't need to collect here if the where_layout isn't
1768 // HorizontalVertical.
1769 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1770 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1772 let fmt = ListFormatting {
1775 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1778 ends_with_newline: true,
1779 config: context.config,
1781 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1783 let end_length = if terminator == "{" {
1784 // If the brace is on the next line we don't need to count it otherwise it needs two
1787 BraceStyle::AlwaysNextLine => 0,
1788 BraceStyle::PreferSameLine => 2,
1789 BraceStyle::SameLineWhere => 0,
1791 } else if terminator == "=" {
1796 if density == Density::Tall || preds_str.contains('\n') ||
1797 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1798 Some(format!("\n{}where {}",
1799 (indent + extra_indent).to_string(context.config),
1802 Some(format!(" where {}", preds_str))
1806 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1807 format!("{}{}{}", format_visibility(vis), item_name, ident)
1810 fn format_generics(context: &RewriteContext,
1811 generics: &ast::Generics,
1814 brace_style: BraceStyle,
1815 force_same_line_brace: bool,
1817 generics_offset: Indent,
1820 let mut result = try_opt!(rewrite_generics(context,
1823 context.config.max_width,
1827 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1828 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1829 let where_clause_str = try_opt!(rewrite_where_clause(context,
1830 &generics.where_clause,
1833 context.block_indent,
1839 result.push_str(&where_clause_str);
1840 if !force_same_line_brace &&
1841 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1843 result.push_str(&context.block_indent.to_string(context.config));
1847 result.push_str(opener);
1849 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1851 result.push_str(&context.block_indent.to_string(context.config));
1855 result.push_str(opener);