1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16 last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
17 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
18 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
19 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
25 use syntax::{ast, abi, ptr, codemap};
26 use syntax::codemap::{Span, BytePos, mk_sp};
27 use syntax::parse::token;
28 use syntax::ast::ImplItem;
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
34 let mut result = "let ".to_owned();
35 let pattern_offset = offset + result.len();
37 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
39 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
40 result.push_str(&pat_str);
42 // String that is placed within the assignment pattern and expression.
44 let mut infix = String::new();
46 if let Some(ref ty) = self.ty {
49 let indent = offset + last_line_width(&result) + 2;
50 let budget = try_opt!(width.checked_sub(indent.width() + 1));
51 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
54 infix.push_str(&rewrite);
57 if self.init.is_some() {
64 result.push_str(&infix);
66 if let Some(ref ex) = self.init {
67 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
69 // 1 = trailing semicolon;
71 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
79 impl<'a> FmtVisitor<'a> {
80 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
81 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
82 self.buffer.push_str(&abi_str);
84 let snippet = self.snippet(span);
85 let brace_pos = snippet.find_uncommented("{").unwrap();
87 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
88 self.buffer.push_str("{");
90 // FIXME: this skips comments between the extern keyword and the opening
92 self.last_pos = span.lo + BytePos(brace_pos as u32);
93 self.block_indent = self.block_indent.block_indent(self.config);
95 for item in &fm.items {
96 self.format_foreign_item(&*item);
99 self.block_indent = self.block_indent.block_unindent(self.config);
100 self.format_missing_with_indent(span.hi - BytePos(1));
103 self.buffer.push_str("}");
104 self.last_pos = span.hi;
107 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
108 self.format_missing_with_indent(item.span.lo);
109 // Drop semicolon or it will be interpreted as comment.
110 // FIXME: this may be a faulty span from libsyntax.
111 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
114 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
115 let indent = self.block_indent;
116 let rewrite = rewrite_fn_base(&self.get_context(),
121 ast::Unsafety::Normal,
122 ast::Constness::NotConst,
123 ast::Defaultness::Final,
124 // These are not actually rust functions,
125 // but we format them as such.
133 Some((new_fn, _)) => {
134 self.buffer.push_str(&new_fn);
135 self.buffer.push_str(";");
137 None => self.format_missing(item.span.hi),
140 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
141 // FIXME(#21): we're dropping potential comments in between the
142 // function keywords here.
143 let vis = format_visibility(&item.vis);
144 let mut_str = if is_mutable { "mut " } else { "" };
145 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
146 let offset = self.block_indent + prefix.len();
148 let width = self.config.max_width - offset.width() - 1;
149 let rewrite = ty.rewrite(&self.get_context(), width, offset);
153 self.buffer.push_str(&prefix);
154 self.buffer.push_str(&result);
155 self.buffer.push_str(";");
157 None => self.format_missing(item.span.hi),
162 self.last_pos = item.span.hi;
165 pub fn rewrite_fn(&mut self,
169 generics: &ast::Generics,
170 unsafety: ast::Unsafety,
171 constness: ast::Constness,
172 defaultness: ast::Defaultness,
174 vis: &ast::Visibility,
178 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
179 let context = self.get_context();
181 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
182 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
183 !context.config.fn_empty_single_line;
185 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
199 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
200 newline_brace = false;
201 } else if force_newline_brace {
202 newline_brace = true;
205 // Prepare for the function body by possibly adding a newline and
207 // FIXME we'll miss anything between the end of the signature and the
208 // start of the body, but we need more spans from the compiler to solve
212 result.push_str(&indent.to_string(self.config));
217 self.single_line_fn(&result, block).or_else(|| Some(result))
220 pub fn rewrite_required_fn(&mut self,
223 sig: &ast::MethodSig,
226 // Drop semicolon or it will be interpreted as comment.
227 let span = mk_sp(span.lo, span.hi - BytePos(1));
228 let context = self.get_context();
230 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
237 ast::Defaultness::Final,
239 &ast::Visibility::Inherited,
244 // Re-attach semicolon
250 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
251 if fn_str.contains('\n') {
255 let codemap = self.get_context().codemap;
257 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
258 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
259 return Some(format!("{}{{}}", fn_str));
262 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
264 if let Some(ref e) = block.expr {
265 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
267 e.rewrite(&self.get_context(),
268 self.config.max_width - self.block_indent.width(),
271 .or_else(|| Some(self.snippet(e.span)))
272 } else if let Some(ref stmt) = block.stmts.first() {
273 stmt.rewrite(&self.get_context(),
274 self.config.max_width - self.block_indent.width(),
281 if let Some(res) = rewrite {
282 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
283 if !res.contains('\n') && width <= self.config.max_width {
284 return Some(format!("{}{{ {} }}", fn_str, res));
292 pub fn visit_enum(&mut self,
294 vis: &ast::Visibility,
295 enum_def: &ast::EnumDef,
296 generics: &ast::Generics,
298 self.buffer.push_str(&format_header("enum ", ident, vis));
300 let enum_snippet = self.snippet(span);
301 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
302 let generics_str = format_generics(&self.get_context(),
306 self.config.item_brace_style,
307 enum_def.variants.is_empty(),
309 self.block_indent.block_indent(self.config),
310 mk_sp(span.lo, body_start))
312 self.buffer.push_str(&generics_str);
314 self.last_pos = body_start;
316 self.block_indent = self.block_indent.block_indent(self.config);
317 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
319 Some(ref body_str) => self.buffer.push_str(&body_str),
320 None => self.format_missing(span.hi - BytePos(1)),
322 self.block_indent = self.block_indent.block_unindent(self.config);
324 if variant_list.is_some() {
325 self.buffer.push_str(&self.block_indent.to_string(self.config));
327 self.buffer.push_str("}");
328 self.last_pos = span.hi;
331 // Format the body of an enum definition
332 fn format_variant_list(&self,
333 enum_def: &ast::EnumDef,
337 if enum_def.variants.is_empty() {
340 let mut result = String::with_capacity(1024);
342 let indentation = self.block_indent.to_string(self.config);
343 result.push_str(&indentation);
345 let items = itemize_list(self.codemap,
346 enum_def.variants.iter(),
349 if !f.node.attrs.is_empty() {
350 f.node.attrs[0].span.lo
356 |f| self.format_variant(f),
360 let budget = self.config.max_width - self.block_indent.width() - 2;
361 let fmt = ListFormatting {
362 tactic: DefinitiveListTactic::Vertical,
364 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
365 indent: self.block_indent,
367 ends_with_newline: true,
371 let list = try_opt!(write_list(items, &fmt));
372 result.push_str(&list);
377 // Variant of an enum.
378 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
379 if contains_skip(&field.node.attrs) {
380 let lo = field.node.attrs[0].span.lo;
381 let span = mk_sp(lo, field.span.hi);
382 return Some(self.snippet(span));
385 let indent = self.block_indent;
386 let mut result = try_opt!(field.node
388 .rewrite(&self.get_context(),
389 self.config.max_width - indent.width(),
391 if !result.is_empty() {
393 result.push_str(&indent.to_string(self.config));
396 let context = self.get_context();
397 let variant_body = match field.node.data {
398 ast::VariantData::Tuple(..) |
399 ast::VariantData::Struct(..) => {
400 // FIXME: Should limit the width, as we have a trailing comma
401 format_struct(&context,
404 &ast::Visibility::Inherited,
409 Some(self.config.struct_variant_width))
411 ast::VariantData::Unit(..) => {
412 let tag = if let Some(ref expr) = field.node.disr_expr {
413 format!("{} = {}", field.node.name, self.snippet(expr.span))
415 field.node.name.to_string()
419 self.config.max_width,
420 self.config.max_width - indent.width(),
425 if let Some(variant_str) = variant_body {
426 result.push_str(&variant_str);
434 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
435 if let ast::ItemKind::Impl(unsafety,
440 ref items) = item.node {
441 let mut result = String::new();
442 result.push_str(&*format_visibility(&item.vis));
443 result.push_str(format_unsafety(unsafety));
444 result.push_str("impl");
446 let lo = context.codemap.span_after(item.span, "impl");
447 let hi = match *trait_ref {
448 Some(ref tr) => tr.path.span.lo,
449 None => self_ty.span.lo,
451 let generics_str = try_opt!(rewrite_generics(context,
454 context.config.max_width,
455 offset + result.len(),
457 result.push_str(&generics_str);
459 // FIXME might need to linebreak in the impl header, here would be a
462 if polarity == ast::ImplPolarity::Negative {
463 result.push_str("!");
465 if let Some(ref trait_ref) = *trait_ref {
466 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
467 let indent = offset + result.len();
468 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
469 result.push_str(" for ");
472 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
473 let indent = offset + result.len();
474 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
476 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
477 let where_clause_str = try_opt!(rewrite_where_clause(context,
478 &generics.where_clause,
480 context.config.item_brace_style,
481 context.block_indent,
483 context.config.where_density,
488 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
489 result.push_str(&where_clause_str);
490 if where_clause_str.contains('\n') {
491 let white_space = offset.to_string(context.config);
492 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
494 result.push_str(" {}");
499 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
501 let width = context.block_indent.width() + context.config.tab_spaces - 1;
502 let where_indent = Indent::new(0, width);
503 result.push_str(&where_indent.to_string(context.config));
505 result.push_str(&where_clause_str);
507 match context.config.item_brace_style {
508 BraceStyle::AlwaysNextLine => result.push('\n'),
509 BraceStyle::PreferSameLine => result.push(' '),
510 BraceStyle::SameLineWhere => {
511 if !where_clause_str.is_empty() {
513 result.push_str(&offset.to_string(context.config));
522 let snippet = context.snippet(item.span);
523 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
525 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
526 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
527 visitor.block_indent = context.block_indent.block_indent(context.config);
528 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
531 visitor.visit_impl_item(&item);
534 visitor.format_missing(item.span.hi - BytePos(1));
536 let inner_indent_str = visitor.block_indent.to_string(context.config);
537 let outer_indent_str = context.block_indent.to_string(context.config);
540 result.push_str(&inner_indent_str);
541 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
543 result.push_str(&outer_indent_str);
546 if result.chars().last().unwrap() == '{' {
557 fn is_impl_single_line(context: &RewriteContext,
558 items: &Vec<ImplItem>,
560 where_clause_str: &str,
563 let snippet = context.snippet(item.span);
564 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
566 Some(context.config.impl_empty_single_line && items.is_empty() &&
567 result.len() + where_clause_str.len() <= context.config.max_width &&
568 !contains_comment(&snippet[open_pos..]))
571 pub fn format_struct(context: &RewriteContext,
574 vis: &ast::Visibility,
575 struct_def: &ast::VariantData,
576 generics: Option<&ast::Generics>,
579 one_line_width: Option<usize>)
582 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
583 ast::VariantData::Tuple(ref fields, _) => {
584 format_tuple_struct(context,
593 ast::VariantData::Struct(ref fields, _) => {
594 format_struct_struct(context,
607 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
608 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
610 let mut result = String::new();
611 let header = format!("{}{}trait {}",
612 format_visibility(&item.vis),
613 format_unsafety(unsafety),
616 result.push_str(&header);
618 let body_lo = context.codemap.span_after(item.span, "{");
620 let generics_str = try_opt!(rewrite_generics(context,
623 context.config.max_width,
624 offset + result.len(),
625 mk_sp(item.span.lo, body_lo)));
626 result.push_str(&generics_str);
628 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
631 context.config.max_width));
632 // If the trait, generics, and trait bound cannot fit on the same line,
633 // put the trait bounds on an indented new line
634 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
635 context.config.ideal_width {
637 let width = context.block_indent.width() + context.config.tab_spaces;
638 let trait_indent = Indent::new(0, width);
639 result.push_str(&trait_indent.to_string(context.config));
641 result.push_str(&trait_bound_str);
643 let has_body = !trait_items.is_empty();
646 if (context.config.where_density == Density::Compressed &&
647 (!result.contains('\n') ||
648 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
649 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
650 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
651 !result.contains('\n')) {
657 let where_budget = try_opt!(context.config
659 .checked_sub(last_line_width(&result)));
660 let where_clause_str = try_opt!(rewrite_where_clause(context,
661 &generics.where_clause,
663 context.config.item_brace_style,
664 context.block_indent,
670 // If the where clause cannot fit on the same line,
671 // put the where clause on a new line
672 if !where_clause_str.contains('\n') &&
673 last_line_width(&result) + where_clause_str.len() + offset.width() >
674 context.config.ideal_width {
676 let width = context.block_indent.width() + context.config.tab_spaces - 1;
677 let where_indent = Indent::new(0, width);
678 result.push_str(&where_indent.to_string(context.config));
680 result.push_str(&where_clause_str);
682 match context.config.item_brace_style {
683 BraceStyle::AlwaysNextLine => {
685 result.push_str(&offset.to_string(context.config));
687 BraceStyle::PreferSameLine => result.push(' '),
688 BraceStyle::SameLineWhere => {
689 if !where_clause_str.is_empty() &&
690 (trait_items.len() > 0 || result.contains('\n')) {
692 result.push_str(&offset.to_string(context.config));
700 let snippet = context.snippet(item.span);
701 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
703 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
704 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
705 visitor.block_indent = context.block_indent.block_indent(context.config);
706 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
708 for item in trait_items {
709 visitor.visit_trait_item(&item);
712 visitor.format_missing(item.span.hi - BytePos(1));
714 let inner_indent_str = visitor.block_indent.to_string(context.config);
715 let outer_indent_str = context.block_indent.to_string(context.config);
718 result.push_str(&inner_indent_str);
719 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
721 result.push_str(&outer_indent_str);
722 } else if result.contains('\n') {
733 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
734 format!("{};", format_header(item_name, ident, vis))
737 fn format_struct_struct(context: &RewriteContext,
740 vis: &ast::Visibility,
741 fields: &[ast::StructField],
742 generics: Option<&ast::Generics>,
745 one_line_width: Option<usize>)
747 let mut result = String::with_capacity(1024);
749 let header_str = format_header(item_name, ident, vis);
750 result.push_str(&header_str);
752 let body_lo = context.codemap.span_after(span, "{");
754 let generics_str = match generics {
756 try_opt!(format_generics(context,
760 context.config.item_brace_style,
763 offset + header_str.len(),
764 mk_sp(span.lo, body_lo)))
767 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
768 format!("\n{}{{", context.block_indent.to_string(context.config))
774 result.push_str(&generics_str);
776 // FIXME(#919): properly format empty structs and their comments.
777 if fields.is_empty() {
778 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
782 let item_indent = offset.block_indent(context.config);
784 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
786 let items = itemize_list(context.codemap,
790 // Include attributes and doc comments, if present
791 if !field.attrs.is_empty() {
792 field.attrs[0].span.lo
797 |field| field.ty.span.hi,
798 |field| field.rewrite(context, item_budget, item_indent),
799 context.codemap.span_after(span, "{"),
801 .collect::<Vec<_>>();
803 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
805 let tactic = match one_line_width {
806 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
807 None => DefinitiveListTactic::Vertical,
810 let fmt = ListFormatting {
813 trailing_separator: context.config.struct_trailing_comma,
816 ends_with_newline: true,
817 config: context.config,
819 let items_str = try_opt!(write_list(&items, &fmt));
820 if one_line_width.is_some() && !items_str.contains('\n') {
821 Some(format!("{} {} }}", result, items_str))
823 Some(format!("{}\n{}{}\n{}}}",
825 offset.block_indent(context.config).to_string(context.config),
827 offset.to_string(context.config)))
831 fn format_tuple_struct(context: &RewriteContext,
834 vis: &ast::Visibility,
835 fields: &[ast::StructField],
836 generics: Option<&ast::Generics>,
840 let mut result = String::with_capacity(1024);
842 let header_str = format_header(item_name, ident, vis);
843 result.push_str(&header_str);
845 // FIXME(#919): don't lose comments on empty tuple structs.
846 let body_lo = if fields.is_empty() {
852 let where_clause_str = match generics {
853 Some(ref generics) => {
854 let generics_str = try_opt!(rewrite_generics(context,
857 context.config.max_width,
858 offset + header_str.len(),
859 mk_sp(span.lo, body_lo)));
860 result.push_str(&generics_str);
862 let where_budget = try_opt!(context.config
864 .checked_sub(last_line_width(&result)));
865 try_opt!(rewrite_where_clause(context,
866 &generics.where_clause,
868 context.config.item_brace_style,
869 context.block_indent,
876 None => "".to_owned(),
880 let item_indent = context.block_indent + result.len();
882 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
884 let items = itemize_list(context.codemap,
888 // Include attributes and doc comments, if present
889 if !field.attrs.is_empty() {
890 field.attrs[0].span.lo
895 |field| field.ty.span.hi,
896 |field| field.rewrite(context, item_budget, item_indent),
897 context.codemap.span_after(span, "("),
899 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
900 result.push_str(&body);
903 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
904 (result.contains('\n') ||
905 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
906 context.config.max_width) {
907 // We need to put the where clause on a new line, but we didn'to_string
908 // know that earlier, so the where clause will not be indented properly.
910 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
911 .to_string(context.config));
913 result.push_str(&where_clause_str);
918 pub fn rewrite_type_alias(context: &RewriteContext,
922 generics: &ast::Generics,
923 vis: &ast::Visibility,
926 let mut result = String::new();
928 result.push_str(&format_visibility(&vis));
929 result.push_str("type ");
930 result.push_str(&ident.to_string());
932 let generics_indent = indent + result.len();
933 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
934 let generics_width = context.config.max_width - " =".len();
935 let generics_str = try_opt!(rewrite_generics(context,
942 result.push_str(&generics_str);
944 let where_budget = try_opt!(context.config
946 .checked_sub(last_line_width(&result)));
947 let where_clause_str = try_opt!(rewrite_where_clause(context,
948 &generics.where_clause,
950 context.config.item_brace_style,
953 context.config.where_density,
957 result.push_str(&where_clause_str);
958 result.push_str(" = ");
960 let line_width = last_line_width(&result);
961 // This checked_sub may fail as the extra space after '=' is not taken into account
962 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
963 let budget = context.config
965 .checked_sub(indent.width() + line_width + ";".len())
967 let type_indent = indent + line_width;
968 // Try to fit the type on the same line
969 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
971 // The line was too short, try to put the type on the next line
973 // Remove the space after '='
975 let type_indent = indent.block_indent(context.config);
977 result.push_str(&type_indent.to_string(context.config));
978 let budget = try_opt!(context.config
980 .checked_sub(type_indent.width() + ";".len()));
981 ty.rewrite(context, budget, type_indent)
983 result.push_str(&ty_str);
984 result.push_str(";");
988 impl Rewrite for ast::StructField {
989 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
990 if contains_skip(&self.attrs) {
991 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
992 return wrap_str(span, context.config.max_width, width, offset);
995 let name = self.ident;
996 let vis = format_visibility(&self.vis);
997 let mut attr_str = try_opt!(self.attrs
998 .rewrite(context, context.config.max_width - offset.width(), offset));
999 if !attr_str.is_empty() {
1000 attr_str.push('\n');
1001 attr_str.push_str(&offset.to_string(context.config));
1004 let result = match name {
1005 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1006 None => format!("{}{}", attr_str, vis),
1009 let last_line_width = last_line_width(&result);
1010 let budget = try_opt!(width.checked_sub(last_line_width));
1011 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1012 Some(result + &rewrite)
1016 pub fn rewrite_static(prefix: &str,
1017 vis: &ast::Visibility,
1020 mutability: ast::Mutability,
1021 expr_opt: Option<&ptr::P<ast::Expr>>,
1022 context: &RewriteContext)
1024 let prefix = format!("{}{} {}{}: ",
1025 format_visibility(vis),
1027 format_mutability(mutability),
1030 let ty_str = try_opt!(ty.rewrite(context,
1031 context.config.max_width - context.block_indent.width() -
1033 context.block_indent));
1035 if let Some(ref expr) = expr_opt {
1036 let lhs = format!("{}{} =", prefix, ty_str);
1038 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1039 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1042 let lhs = format!("{}{};", prefix, ty_str);
1047 pub fn rewrite_associated_type(ident: ast::Ident,
1048 ty_opt: Option<&ptr::P<ast::Ty>>,
1049 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1050 context: &RewriteContext,
1053 let prefix = format!("type {}", ident);
1055 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1056 let bounds: &[_] = &ty_param_bounds;
1057 let bound_str = bounds.iter()
1058 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1059 .collect::<Vec<String>>()
1061 if bounds.len() > 0 {
1062 format!(": {}", bound_str)
1070 if let Some(ty) = ty_opt {
1071 let ty_str = try_opt!(ty.rewrite(context,
1072 context.config.max_width - context.block_indent.width() -
1075 context.block_indent));
1076 Some(format!("{} = {};", prefix, ty_str))
1078 Some(format!("{}{};", prefix, type_bounds_str))
1082 impl Rewrite for ast::FunctionRetTy {
1083 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1085 ast::FunctionRetTy::Default(_) => Some(String::new()),
1086 ast::FunctionRetTy::None(_) => {
1088 Some("-> !".to_owned())
1093 ast::FunctionRetTy::Ty(ref ty) => {
1094 let inner_width = try_opt!(width.checked_sub(3));
1095 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1101 impl Rewrite for ast::Arg {
1102 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1103 if is_named_arg(self) {
1104 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1106 if self.ty.node != ast::TyKind::Infer {
1107 result.push_str(": ");
1108 let max_width = try_opt!(width.checked_sub(result.len()));
1109 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1110 result.push_str(&ty_str);
1115 self.ty.rewrite(context, width, offset)
1120 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1122 context: &RewriteContext)
1124 match explicit_self.node {
1125 ast::SelfKind::Region(lt, m) => {
1126 let mut_str = format_mutability(m);
1130 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1131 Some(format!("&{} {}self", lifetime_str, mut_str))
1133 None => Some(format!("&{}self", mut_str)),
1136 ast::SelfKind::Explicit(ref ty, _) => {
1137 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1139 let mutability = explicit_self_mutability(&args[0]);
1140 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1142 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1144 ast::SelfKind::Value(_) => {
1145 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1147 let mutability = explicit_self_mutability(&args[0]);
1149 Some(format!("{}self", format_mutability(mutability)))
1154 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1155 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1156 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1157 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1164 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1165 if is_named_arg(arg) {
1172 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1174 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1175 _ => arg.ty.span.hi,
1179 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1180 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1181 ident.node != token::keywords::Invalid.ident()
1187 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1189 ast::FunctionRetTy::None(ref span) |
1190 ast::FunctionRetTy::Default(ref span) => span.clone(),
1191 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1195 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1196 // Note that ty.span is the span for ty.ident, not the whole item.
1197 let lo = ty.span.lo;
1198 if let Some(ref def) = ty.default {
1199 return mk_sp(lo, def.span.hi);
1201 if ty.bounds.is_empty() {
1204 let hi = match ty.bounds[ty.bounds.len() - 1] {
1205 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1206 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1211 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1213 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1214 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1215 ast::WherePredicate::EqPredicate(ref p) => p.span,
1219 // Return type is (result, force_new_line_for_brace)
1220 fn rewrite_fn_base(context: &RewriteContext,
1224 generics: &ast::Generics,
1225 unsafety: ast::Unsafety,
1226 constness: ast::Constness,
1227 defaultness: ast::Defaultness,
1229 vis: &ast::Visibility,
1231 newline_brace: bool,
1233 -> Option<(String, bool)> {
1234 let mut force_new_line_for_brace = false;
1235 // FIXME we'll lose any comments in between parts of the function decl, but
1236 // anyone who comments there probably deserves what they get.
1238 let where_clause = &generics.where_clause;
1240 let mut result = String::with_capacity(1024);
1241 // Vis unsafety abi.
1242 result.push_str(&*format_visibility(vis));
1244 if let ast::Defaultness::Default = defaultness {
1245 result.push_str("default ");
1248 if let ast::Constness::Const = constness {
1249 result.push_str("const ");
1252 result.push_str(::utils::format_unsafety(unsafety));
1254 if abi != abi::Abi::Rust {
1255 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1259 result.push_str("fn ");
1260 result.push_str(&ident.to_string());
1263 let generics_indent = indent + result.len();
1264 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1265 let generics_str = try_opt!(rewrite_generics(context,
1268 context.config.max_width,
1271 result.push_str(&generics_str);
1273 // Note that if the width and indent really matter, we'll re-layout the
1274 // return type later anyway.
1275 let ret_str = try_opt!(fd.output
1276 .rewrite(&context, context.config.max_width - indent.width(), indent));
1278 let multi_line_ret_str = ret_str.contains('\n');
1279 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1282 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1283 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1285 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1286 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1287 arg_indent = indent.block_indent(context.config);
1288 multi_line_budget = context.config.max_width - arg_indent.width();
1291 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1296 // Check if vertical layout was forced by compute_budget_for_args.
1297 if one_line_budget == 0 {
1298 if context.config.fn_args_paren_newline {
1300 result.push_str(&arg_indent.to_string(context.config));
1301 arg_indent = arg_indent + 1; // extra space for `(`
1304 result.push_str("(\n");
1305 result.push_str(&arg_indent.to_string(context.config));
1311 if multi_line_ret_str {
1312 one_line_budget = 0;
1315 // A conservative estimation, to goal is to be over all parens in generics
1316 let args_start = generics.ty_params
1318 .map_or(span.lo, |tp| end_typaram(tp));
1319 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1320 span_for_return(&fd.output).lo);
1321 let arg_str = try_opt!(rewrite_args(context,
1323 fd.get_self().as_ref(),
1331 let multi_line_arg_str = arg_str.contains('\n');
1333 let put_args_in_block = match context.config.fn_args_layout {
1334 FnArgLayoutStyle::Block => multi_line_arg_str,
1335 FnArgLayoutStyle::BlockAlways => true,
1337 } && fd.inputs.len() > 0;
1339 if put_args_in_block {
1340 arg_indent = indent.block_indent(context.config);
1342 result.push_str(&arg_indent.to_string(context.config));
1343 result.push_str(&arg_str);
1345 result.push_str(&indent.to_string(context.config));
1348 result.push_str(&arg_str);
1353 if !ret_str.is_empty() {
1354 let ret_should_indent = match context.config.fn_args_layout {
1355 // If our args are block layout then we surely must have space.
1356 FnArgLayoutStyle::Block if put_args_in_block => false,
1357 FnArgLayoutStyle::BlockAlways => false,
1359 // If we've already gone multi-line, or the return type would push
1360 // over the max width, then put the return type on a new line.
1361 result.contains("\n") || multi_line_ret_str ||
1362 result.len() + indent.width() + ret_str_len > context.config.max_width
1365 let ret_indent = if ret_should_indent {
1366 let indent = match context.config.fn_return_indent {
1367 ReturnIndent::WithWhereClause => indent + 4,
1368 // Aligning with non-existent args looks silly.
1369 _ if arg_str.is_empty() => {
1370 force_new_line_for_brace = true;
1373 // FIXME: we might want to check that using the arg indent
1374 // doesn't blow our budget, and if it does, then fallback to
1375 // the where clause indent.
1380 result.push_str(&indent.to_string(context.config));
1384 Indent::new(indent.width(), result.len())
1387 if multi_line_ret_str {
1388 // Now that we know the proper indent and width, we need to
1389 // re-layout the return type.
1391 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1392 let ret_str = try_opt!(fd.output
1393 .rewrite(context, budget, ret_indent));
1394 result.push_str(&ret_str);
1396 result.push_str(&ret_str);
1399 // Comment between return type and the end of the decl.
1400 let snippet_lo = fd.output.span().hi;
1401 if where_clause.predicates.is_empty() {
1402 let snippet_hi = span.hi;
1403 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1404 let snippet = snippet.trim();
1405 if !snippet.is_empty() {
1407 result.push_str(snippet);
1410 // FIXME it would be nice to catch comments between the return type
1411 // and the where clause, but we don't have a span for the where
1416 let should_compress_where = match context.config.where_density {
1417 Density::Compressed => !result.contains('\n') || put_args_in_block,
1418 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1420 } || (put_args_in_block && ret_str.is_empty());
1422 let where_density = if should_compress_where {
1429 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1430 let where_clause_str = try_opt!(rewrite_where_clause(context,
1433 context.config.fn_brace_style,
1441 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1442 !where_clause_str.contains('\n') {
1446 result.push_str(&where_clause_str);
1448 Some((result, force_new_line_for_brace))
1451 fn rewrite_args(context: &RewriteContext,
1453 explicit_self: Option<&ast::ExplicitSelf>,
1454 one_line_budget: usize,
1455 multi_line_budget: usize,
1461 let mut arg_item_strs = try_opt!(args.iter()
1462 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1463 .collect::<Option<Vec<_>>>());
1465 // Account for sugary self.
1466 // FIXME: the comment for the self argument is dropped. This is blocked
1467 // on rust issue #27522.
1469 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1470 .map_or(1, |self_str| {
1471 arg_item_strs[0] = self_str;
1475 // Comments between args.
1476 let mut arg_items = Vec::new();
1478 arg_items.push(ListItem::from_str(""));
1481 // FIXME(#21): if there are no args, there might still be a comment, but
1482 // without spans for the comment or parens, there is no chance of
1483 // getting it right. You also don't get to put a comment on self, unless
1485 if args.len() >= min_args || variadic {
1486 let comment_span_start = if min_args == 2 {
1487 let second_arg_start = if arg_has_pattern(&args[1]) {
1492 let reduced_span = mk_sp(span.lo, second_arg_start);
1494 context.codemap.span_after_last(reduced_span, ",")
1499 enum ArgumentKind<'a> {
1500 Regular(&'a ast::Arg),
1504 let variadic_arg = if variadic {
1505 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1506 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1507 Some(ArgumentKind::Variadic(variadic_start))
1512 let more_items = itemize_list(context.codemap,
1513 args[min_args - 1..]
1515 .map(ArgumentKind::Regular)
1516 .chain(variadic_arg),
1520 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1521 ArgumentKind::Variadic(start) => start,
1526 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1527 ArgumentKind::Variadic(start) => start + BytePos(3),
1532 ArgumentKind::Regular(..) => None,
1533 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1539 arg_items.extend(more_items);
1542 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1543 item.item = Some(arg);
1546 let indent = match context.config.fn_arg_indent {
1547 BlockIndentStyle::Inherit => indent,
1548 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1549 BlockIndentStyle::Visual => arg_indent,
1552 let tactic = definitive_tactic(&arg_items,
1553 context.config.fn_args_density.to_list_tactic(),
1555 let budget = match tactic {
1556 DefinitiveListTactic::Horizontal => one_line_budget,
1557 _ => multi_line_budget,
1560 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1562 let end_with_newline = match context.config.fn_args_layout {
1563 FnArgLayoutStyle::Block |
1564 FnArgLayoutStyle::BlockAlways => true,
1568 let fmt = ListFormatting {
1571 trailing_separator: SeparatorTactic::Never,
1574 ends_with_newline: end_with_newline,
1575 config: context.config,
1578 write_list(&arg_items, &fmt)
1581 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1582 if let ast::PatKind::Ident(_,
1584 node: ast::Ident { name: ast::Name(0u32), .. },
1594 fn compute_budgets_for_args(context: &RewriteContext,
1598 newline_brace: bool)
1599 -> Option<((usize, usize, Indent))> {
1600 // Try keeping everything on the same line.
1601 if !result.contains("\n") {
1602 // 3 = `() `, space is before ret_string.
1603 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1607 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1609 if one_line_budget > 0 {
1611 let multi_line_budget =
1612 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1614 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1618 // Didn't work. we must force vertical layout and put args on a newline.
1619 let new_indent = indent.block_indent(context.config);
1620 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1621 let max_space = context.config.max_width;
1622 if used_space <= max_space {
1623 Some((0, max_space - used_space, new_indent))
1625 // Whoops! bankrupt.
1630 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1631 match config.fn_brace_style {
1632 BraceStyle::AlwaysNextLine => true,
1633 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1638 fn rewrite_generics(context: &RewriteContext,
1639 generics: &ast::Generics,
1642 generics_offset: Indent,
1645 // FIXME: convert bounds to where clauses where they get too big or if
1646 // there is a where clause at all.
1647 let lifetimes: &[_] = &generics.lifetimes;
1648 let tys: &[_] = &generics.ty_params;
1649 if lifetimes.is_empty() && tys.is_empty() {
1650 return Some(String::new());
1653 let offset = match context.config.generics_indent {
1654 BlockIndentStyle::Inherit => offset,
1655 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1657 BlockIndentStyle::Visual => generics_offset + 1,
1660 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1661 // FIXME: might need to insert a newline if the generics are really long.
1663 // Strings for the generics.
1664 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1665 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1667 // Extract comments between generics.
1668 let lt_spans = lifetimes.iter().map(|l| {
1669 let hi = if l.bounds.is_empty() {
1672 l.bounds[l.bounds.len() - 1].span.hi
1674 mk_sp(l.lifetime.span.lo, hi)
1676 let ty_spans = tys.iter().map(span_for_ty_param);
1678 let items = itemize_list(context.codemap,
1679 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1683 // FIXME: don't clone
1684 |&(_, ref str)| str.clone(),
1685 context.codemap.span_after(span, "<"),
1687 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1689 Some(format!("<{}>", list_str))
1692 fn rewrite_trait_bounds(context: &RewriteContext,
1693 type_param_bounds: &ast::TyParamBounds,
1697 let bounds: &[_] = &type_param_bounds;
1699 if bounds.is_empty() {
1700 return Some(String::new());
1703 let bound_str = bounds.iter()
1704 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1705 .collect::<Vec<String>>()
1708 let mut result = String::new();
1709 result.push_str(": ");
1710 result.push_str(&bound_str);
1714 fn rewrite_where_clause(context: &RewriteContext,
1715 where_clause: &ast::WhereClause,
1717 brace_style: BraceStyle,
1722 allow_trailing_comma: bool,
1723 span_end: Option<BytePos>)
1725 if where_clause.predicates.is_empty() {
1726 return Some(String::new());
1729 let extra_indent = match context.config.where_indent {
1730 BlockIndentStyle::Inherit => Indent::empty(),
1731 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1734 let offset = match context.config.where_pred_indent {
1735 BlockIndentStyle::Inherit => indent + extra_indent,
1736 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1737 // 6 = "where ".len()
1738 BlockIndentStyle::Visual => indent + extra_indent + 6,
1740 // FIXME: if where_pred_indent != Visual, then the budgets below might
1741 // be out by a char or two.
1743 let budget = context.config.max_width - offset.width();
1744 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1745 // If we don't have the start of the next span, then use the end of the
1746 // predicates, but that means we miss comments.
1747 let len = where_clause.predicates.len();
1748 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1749 let span_end = span_end.unwrap_or(end_of_preds);
1750 let items = itemize_list(context.codemap,
1751 where_clause.predicates.iter(),
1753 |pred| span_for_where_pred(pred).lo,
1754 |pred| span_for_where_pred(pred).hi,
1755 |pred| pred.rewrite(&context, budget, offset),
1758 let item_vec = items.collect::<Vec<_>>();
1759 // FIXME: we don't need to collect here if the where_layout isn't
1760 // HorizontalVertical.
1761 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1762 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1764 let fmt = ListFormatting {
1767 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1770 ends_with_newline: true,
1771 config: context.config,
1773 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1775 let end_length = if terminator == "{" {
1776 // If the brace is on the next line we don't need to count it otherwise it needs two
1779 BraceStyle::AlwaysNextLine => 0,
1780 BraceStyle::PreferSameLine => 2,
1781 BraceStyle::SameLineWhere => 0,
1783 } else if terminator == "=" {
1788 if density == Density::Tall || preds_str.contains('\n') ||
1789 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1790 Some(format!("\n{}where {}",
1791 (indent + extra_indent).to_string(context.config),
1794 Some(format!(" where {}", preds_str))
1798 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1799 format!("{}{}{}", format_visibility(vis), item_name, ident)
1802 fn format_generics(context: &RewriteContext,
1803 generics: &ast::Generics,
1806 brace_style: BraceStyle,
1807 force_same_line_brace: bool,
1809 generics_offset: Indent,
1812 let mut result = try_opt!(rewrite_generics(context,
1815 context.config.max_width,
1819 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1820 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1821 let where_clause_str = try_opt!(rewrite_where_clause(context,
1822 &generics.where_clause,
1825 context.block_indent,
1831 result.push_str(&where_clause_str);
1832 if !force_same_line_brace &&
1833 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1835 result.push_str(&context.block_indent.to_string(context.config));
1839 result.push_str(opener);
1841 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1843 result.push_str(&context.block_indent.to_string(context.config));
1847 result.push_str(opener);