1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use utils::{CodeMapSpanUtils, format_mutability, format_visibility, contains_skip, end_typaram,
15 wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
17 DefinitiveListTactic, definitive_tactic, format_item_list};
18 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
19 use comment::{FindUncommented, contains_comment};
20 use visitor::FmtVisitor;
21 use rewrite::{Rewrite, RewriteContext};
22 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use syntax::{ast, abi, ptr, codemap};
25 use syntax::codemap::{Span, BytePos, mk_sp};
26 use syntax::parse::token;
27 use syntax::ast::ImplItem;
29 // Statements of the form
30 // let pat: ty = init;
31 impl Rewrite for ast::Local {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33 let mut result = "let ".to_owned();
34 let pattern_offset = offset + result.len();
36 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
39 result.push_str(&pat_str);
41 // String that is placed within the assignment pattern and expression.
43 let mut infix = String::new();
45 if let Some(ref ty) = self.ty {
48 let indent = offset + last_line_width(&result) + 2;
49 let budget = try_opt!(width.checked_sub(indent.width() + 1));
50 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
53 infix.push_str(&rewrite);
56 if self.init.is_some() {
63 result.push_str(&infix);
65 if let Some(ref ex) = self.init {
66 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68 // 1 = trailing semicolon;
69 result = try_opt!(rewrite_assign_rhs(&context,
73 context.block_indent));
81 impl<'a> FmtVisitor<'a> {
82 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
83 self.buffer.push_str(&::utils::format_abi(fm.abi));
85 let snippet = self.snippet(span);
86 let brace_pos = snippet.find_uncommented("{").unwrap();
88 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
89 self.buffer.push_str("{");
91 // FIXME: this skips comments between the extern keyword and the opening
93 self.last_pos = span.lo + BytePos(brace_pos as u32);
94 self.block_indent = self.block_indent.block_indent(self.config);
96 for item in &fm.items {
97 self.format_foreign_item(&*item);
100 self.block_indent = self.block_indent.block_unindent(self.config);
101 self.format_missing_with_indent(span.hi - BytePos(1));
104 self.buffer.push_str("}");
105 self.last_pos = span.hi;
108 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
109 self.format_missing_with_indent(item.span.lo);
110 // Drop semicolon or it will be interpreted as comment.
111 // FIXME: this may be a faulty span from libsyntax.
112 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
115 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
116 let indent = self.block_indent;
117 let rewrite = rewrite_fn_base(&self.get_context(),
123 ast::Unsafety::Normal,
124 ast::Constness::NotConst,
125 // These are not actually rust functions,
126 // but we format them as such.
134 Some((new_fn, _)) => {
135 self.buffer.push_str(&new_fn);
136 self.buffer.push_str(";");
138 None => self.format_missing(item.span.hi),
141 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
142 // FIXME(#21): we're dropping potential comments in between the
143 // function keywords here.
144 let mut_str = if is_mutable {
149 let prefix = format!("{}static {}{}: ",
150 format_visibility(item.vis),
153 let offset = self.block_indent + prefix.len();
155 let width = self.config.max_width - offset.width() - 1;
156 let rewrite = ty.rewrite(&self.get_context(), width, offset);
160 self.buffer.push_str(&prefix);
161 self.buffer.push_str(&result);
162 self.buffer.push_str(";");
164 None => self.format_missing(item.span.hi),
169 self.last_pos = item.span.hi;
172 pub fn rewrite_fn(&mut self,
176 explicit_self: Option<&ast::ExplicitSelf>,
177 generics: &ast::Generics,
178 unsafety: ast::Unsafety,
179 constness: ast::Constness,
181 vis: ast::Visibility,
185 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
186 let context = self.get_context();
188 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
189 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
190 !context.config.fn_empty_single_line;
192 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
206 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
207 newline_brace = false;
208 } else if force_newline_brace {
209 newline_brace = true;
212 // Prepare for the function body by possibly adding a newline and
214 // FIXME we'll miss anything between the end of the signature and the
215 // start of the body, but we need more spans from the compiler to solve
219 result.push_str(&indent.to_string(self.config));
224 self.single_line_fn(&result, block).or_else(|| Some(result))
227 pub fn rewrite_required_fn(&mut self,
230 sig: &ast::MethodSig,
233 // Drop semicolon or it will be interpreted as comment.
234 let span = mk_sp(span.lo, span.hi - BytePos(1));
235 let context = self.get_context();
237 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
241 Some(&sig.explicit_self),
246 ast::Visibility::Inherited,
251 // Re-attach semicolon
257 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
258 if fn_str.contains('\n') {
262 let codemap = self.get_context().codemap;
264 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
265 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
266 return Some(format!("{}{{}}", fn_str));
269 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
271 if let Some(ref e) = block.expr {
272 let suffix = if semicolon_for_expr(e) {
278 e.rewrite(&self.get_context(),
279 self.config.max_width - self.block_indent.width(),
282 .or_else(|| Some(self.snippet(e.span)))
283 } else if let Some(ref stmt) = block.stmts.first() {
284 stmt.rewrite(&self.get_context(),
285 self.config.max_width - self.block_indent.width(),
292 if let Some(res) = rewrite {
293 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
294 if !res.contains('\n') && width <= self.config.max_width {
295 return Some(format!("{}{{ {} }}", fn_str, res));
303 pub fn visit_enum(&mut self,
305 vis: ast::Visibility,
306 enum_def: &ast::EnumDef,
307 generics: &ast::Generics,
309 let header_str = format_header("enum ", ident, vis);
310 self.buffer.push_str(&header_str);
312 let enum_snippet = self.snippet(span);
313 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
314 let generics_str = format_generics(&self.get_context(),
318 self.config.item_brace_style,
319 enum_def.variants.is_empty(),
321 self.block_indent.block_indent(self.config),
322 mk_sp(span.lo, body_start))
324 self.buffer.push_str(&generics_str);
326 self.last_pos = body_start;
328 self.block_indent = self.block_indent.block_indent(self.config);
329 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
331 Some(ref body_str) => self.buffer.push_str(&body_str),
332 None => self.format_missing(span.hi - BytePos(1)),
334 self.block_indent = self.block_indent.block_unindent(self.config);
336 if variant_list.is_some() {
337 self.buffer.push_str(&self.block_indent.to_string(self.config));
339 self.buffer.push_str("}");
340 self.last_pos = span.hi;
343 // Format the body of an enum definition
344 fn format_variant_list(&self,
345 enum_def: &ast::EnumDef,
349 if enum_def.variants.is_empty() {
352 let mut result = String::with_capacity(1024);
354 let indentation = self.block_indent.to_string(self.config);
355 result.push_str(&indentation);
357 let items = itemize_list(self.codemap,
358 enum_def.variants.iter(),
361 if !f.node.attrs.is_empty() {
362 f.node.attrs[0].span.lo
368 |f| self.format_variant(f),
372 let budget = self.config.max_width - self.block_indent.width() - 2;
373 let fmt = ListFormatting {
374 tactic: DefinitiveListTactic::Vertical,
376 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
377 indent: self.block_indent,
379 ends_with_newline: true,
383 let list = try_opt!(write_list(items, &fmt));
384 result.push_str(&list);
389 // Variant of an enum.
390 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
391 if contains_skip(&field.node.attrs) {
392 let lo = field.node.attrs[0].span.lo;
393 let span = mk_sp(lo, field.span.hi);
394 return Some(self.snippet(span));
397 let indent = self.block_indent;
398 let mut result = try_opt!(field.node
400 .rewrite(&self.get_context(),
401 self.config.max_width - indent.width(),
403 if !result.is_empty() {
405 result.push_str(&indent.to_string(self.config));
408 let context = self.get_context();
409 let variant_body = match field.node.data {
410 ast::VariantData::Tuple(..) |
411 ast::VariantData::Struct(..) => {
412 // FIXME: Should limit the width, as we have a trailing comma
413 format_struct(&context,
416 ast::Visibility::Inherited,
422 ast::VariantData::Unit(..) => {
423 let tag = if let Some(ref expr) = field.node.disr_expr {
424 format!("{} = {}", field.node.name, self.snippet(expr.span))
426 field.node.name.to_string()
430 self.config.max_width,
431 self.config.max_width - indent.width(),
436 if let Some(variant_str) = variant_body {
437 result.push_str(&variant_str);
445 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
446 if let ast::ItemKind::Impl(unsafety,
451 ref items) = item.node {
452 let mut result = String::new();
453 result.push_str(format_visibility(item.vis));
454 result.push_str(format_unsafety(unsafety));
455 result.push_str("impl");
457 let lo = context.codemap.span_after(item.span, "impl");
458 let hi = match *trait_ref {
459 Some(ref tr) => tr.path.span.lo,
460 None => self_ty.span.lo,
462 let generics_str = try_opt!(rewrite_generics(context,
465 context.config.max_width,
466 offset + result.len(),
468 result.push_str(&generics_str);
470 // FIXME might need to linebreak in the impl header, here would be a
473 if polarity == ast::ImplPolarity::Negative {
474 result.push_str("!");
476 if let Some(ref trait_ref) = *trait_ref {
477 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
478 let indent = offset + result.len();
479 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
480 result.push_str(" for ");
483 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
484 let indent = offset + result.len();
485 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
487 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
488 let where_clause_str = try_opt!(rewrite_where_clause(context,
489 &generics.where_clause,
491 context.config.item_brace_style,
492 context.block_indent,
494 context.config.where_density,
499 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
500 result.push_str(&where_clause_str);
501 if where_clause_str.contains('\n') {
502 let white_space = offset.to_string(context.config);
503 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
505 result.push_str(" {}");
510 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
512 let width = context.block_indent.width() + context.config.tab_spaces - 1;
513 let where_indent = Indent::new(0, width);
514 result.push_str(&where_indent.to_string(context.config));
516 result.push_str(&where_clause_str);
518 match context.config.item_brace_style {
519 BraceStyle::AlwaysNextLine => result.push('\n'),
520 BraceStyle::PreferSameLine => result.push(' '),
521 BraceStyle::SameLineWhere => {
522 if !where_clause_str.is_empty() {
524 result.push_str(&offset.to_string(context.config));
533 let snippet = context.snippet(item.span);
534 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
536 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
537 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
538 visitor.block_indent = context.block_indent.block_indent(context.config);
539 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
542 visitor.visit_impl_item(&item);
545 visitor.format_missing(item.span.hi - BytePos(1));
547 let inner_indent_str = visitor.block_indent.to_string(context.config);
548 let outer_indent_str = context.block_indent.to_string(context.config);
551 result.push_str(&inner_indent_str);
552 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
554 result.push_str(&outer_indent_str);
557 if result.chars().last().unwrap() == '{' {
568 fn is_impl_single_line(context: &RewriteContext,
569 items: &Vec<ImplItem>,
571 where_clause_str: &str,
574 let snippet = context.snippet(item.span);
575 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
577 Some(context.config.impl_empty_single_line && items.is_empty() &&
578 result.len() + where_clause_str.len() <= context.config.max_width &&
579 !contains_comment(&snippet[open_pos..]))
582 pub fn format_struct(context: &RewriteContext,
585 vis: ast::Visibility,
586 struct_def: &ast::VariantData,
587 generics: Option<&ast::Generics>,
592 ast::VariantData::Unit(..) => format_unit_struct(item_name, ident, vis),
593 ast::VariantData::Tuple(ref fields, _) => {
594 format_tuple_struct(context,
603 ast::VariantData::Struct(ref fields, _) => {
604 format_struct_struct(context,
616 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
617 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
619 let mut result = String::new();
620 let header = format!("{}{}trait {}",
621 format_visibility(item.vis),
622 format_unsafety(unsafety),
625 result.push_str(&header);
627 let body_lo = context.codemap.span_after(item.span, "{");
629 let generics_str = try_opt!(rewrite_generics(context,
632 context.config.max_width,
633 offset + result.len(),
634 mk_sp(item.span.lo, body_lo)));
635 result.push_str(&generics_str);
637 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
640 context.config.max_width));
641 // If the trait, generics, and trait bound cannot fit on the same line,
642 // put the trait bounds on an indented new line
643 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
644 context.config.ideal_width {
646 let width = context.block_indent.width() + context.config.tab_spaces;
647 let trait_indent = Indent::new(0, width);
648 result.push_str(&trait_indent.to_string(context.config));
650 result.push_str(&trait_bound_str);
652 let has_body = !trait_items.is_empty();
654 let where_density = if (context.config.where_density == Density::Compressed &&
655 (!result.contains('\n') ||
656 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
657 (context.config.fn_args_layout == FnArgLayoutStyle::Block &&
658 result.is_empty()) ||
659 (context.config.where_density == Density::CompressedIfEmpty &&
661 !result.contains('\n')) {
667 let where_budget = try_opt!(context.config
669 .checked_sub(last_line_width(&result)));
670 let where_clause_str = try_opt!(rewrite_where_clause(context,
671 &generics.where_clause,
673 context.config.item_brace_style,
674 context.block_indent,
680 // If the where clause cannot fit on the same line,
681 // put the where clause on a new line
682 if !where_clause_str.contains('\n') &&
683 last_line_width(&result) + where_clause_str.len() + offset.width() >
684 context.config.ideal_width {
686 let width = context.block_indent.width() + context.config.tab_spaces - 1;
687 let where_indent = Indent::new(0, width);
688 result.push_str(&where_indent.to_string(context.config));
690 result.push_str(&where_clause_str);
692 match context.config.item_brace_style {
693 BraceStyle::AlwaysNextLine => {
695 result.push_str(&offset.to_string(context.config));
697 BraceStyle::PreferSameLine => result.push(' '),
698 BraceStyle::SameLineWhere => {
699 if !where_clause_str.is_empty() &&
700 (trait_items.len() > 0 || result.contains('\n')) {
702 result.push_str(&offset.to_string(context.config));
710 let snippet = context.snippet(item.span);
711 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
713 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
714 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
715 visitor.block_indent = context.block_indent.block_indent(context.config);
716 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
718 for item in trait_items {
719 visitor.visit_trait_item(&item);
722 visitor.format_missing(item.span.hi - BytePos(1));
724 let inner_indent_str = visitor.block_indent.to_string(context.config);
725 let outer_indent_str = context.block_indent.to_string(context.config);
728 result.push_str(&inner_indent_str);
729 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
731 result.push_str(&outer_indent_str);
732 } else if result.contains('\n') {
743 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> Option<String> {
744 let mut result = String::with_capacity(1024);
746 let header_str = format_header(item_name, ident, vis);
747 result.push_str(&header_str);
753 fn format_struct_struct(context: &RewriteContext,
756 vis: ast::Visibility,
757 fields: &[ast::StructField],
758 generics: Option<&ast::Generics>,
762 let mut result = String::with_capacity(1024);
764 let header_str = format_header(item_name, ident, vis);
765 result.push_str(&header_str);
767 let body_lo = context.codemap.span_after(span, "{");
769 let generics_str = match generics {
771 try_opt!(format_generics(context,
775 context.config.item_brace_style,
778 offset + header_str.len(),
779 mk_sp(span.lo, body_lo)))
782 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
783 format!("\n{}{{", context.block_indent.to_string(context.config))
789 result.push_str(&generics_str);
791 // FIXME(#919): properly format empty structs and their comments.
792 if fields.is_empty() {
793 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
797 let item_indent = offset.block_indent(context.config);
799 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
801 let items = itemize_list(context.codemap,
805 // Include attributes and doc comments, if present
806 if !field.node.attrs.is_empty() {
807 field.node.attrs[0].span.lo
812 |field| field.node.ty.span.hi,
813 |field| field.rewrite(context, item_budget, item_indent),
814 context.codemap.span_after(span, "{"),
817 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
818 let fmt = ListFormatting {
819 tactic: DefinitiveListTactic::Vertical,
821 trailing_separator: context.config.struct_trailing_comma,
824 ends_with_newline: true,
825 config: context.config,
827 Some(format!("{}\n{}{}\n{}}}",
829 offset.block_indent(context.config).to_string(context.config),
830 try_opt!(write_list(items, &fmt)),
831 offset.to_string(context.config)))
834 fn format_tuple_struct(context: &RewriteContext,
837 vis: ast::Visibility,
838 fields: &[ast::StructField],
839 generics: Option<&ast::Generics>,
843 let mut result = String::with_capacity(1024);
845 let header_str = format_header(item_name, ident, vis);
846 result.push_str(&header_str);
848 // FIXME(#919): don't lose comments on empty tuple structs.
849 let body_lo = if fields.is_empty() {
855 let where_clause_str = match generics {
856 Some(ref generics) => {
857 let generics_str = try_opt!(rewrite_generics(context,
860 context.config.max_width,
861 offset + header_str.len(),
862 mk_sp(span.lo, body_lo)));
863 result.push_str(&generics_str);
865 let where_budget = try_opt!(context.config
867 .checked_sub(last_line_width(&result)));
868 try_opt!(rewrite_where_clause(context,
869 &generics.where_clause,
871 context.config.item_brace_style,
872 context.block_indent,
879 None => "".to_owned(),
883 let item_indent = context.block_indent + result.len();
885 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
887 let items = itemize_list(context.codemap,
891 // Include attributes and doc comments, if present
892 if !field.node.attrs.is_empty() {
893 field.node.attrs[0].span.lo
898 |field| field.node.ty.span.hi,
899 |field| field.rewrite(context, item_budget, item_indent),
900 context.codemap.span_after(span, "("),
902 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
903 result.push_str(&body);
906 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
907 (result.contains('\n') ||
908 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
909 context.config.max_width) {
910 // We need to put the where clause on a new line, but we didn'to_string
911 // know that earlier, so the where clause will not be indented properly.
913 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
914 .to_string(context.config));
916 result.push_str(&where_clause_str);
921 pub fn rewrite_type_alias(context: &RewriteContext,
925 generics: &ast::Generics,
926 vis: ast::Visibility,
929 let mut result = String::new();
931 result.push_str(&format_visibility(vis));
932 result.push_str("type ");
933 result.push_str(&ident.to_string());
935 let generics_indent = indent + result.len();
936 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
937 let generics_width = context.config.max_width - " =".len();
938 let generics_str = try_opt!(rewrite_generics(context,
945 result.push_str(&generics_str);
947 let where_budget = try_opt!(context.config
949 .checked_sub(last_line_width(&result)));
950 let where_clause_str = try_opt!(rewrite_where_clause(context,
951 &generics.where_clause,
953 context.config.item_brace_style,
956 context.config.where_density,
960 result.push_str(&where_clause_str);
961 result.push_str(" = ");
963 let line_width = last_line_width(&result);
964 // This checked_sub may fail as the extra space after '=' is not taken into account
965 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
966 let budget = context.config
968 .checked_sub(indent.width() + line_width + ";".len())
970 let type_indent = indent + line_width;
971 // Try to fit the type on the same line
972 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
974 // The line was too short, try to put the type on the next line
976 // Remove the space after '='
978 let type_indent = indent.block_indent(context.config);
980 result.push_str(&type_indent.to_string(context.config));
981 let budget = try_opt!(context.config
983 .checked_sub(type_indent.width() +
985 ty.rewrite(context, budget, type_indent)
987 result.push_str(&ty_str);
988 result.push_str(";");
992 impl Rewrite for ast::StructField {
993 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
994 if contains_skip(&self.node.attrs) {
995 let span = context.snippet(mk_sp(self.node.attrs[0].span.lo, self.span.hi));
996 return wrap_str(span, context.config.max_width, width, offset);
999 let name = match self.node.kind {
1000 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
1001 ast::StructFieldKind::UnnamedField(_) => None,
1003 let vis = match self.node.kind {
1004 ast::StructFieldKind::NamedField(_, vis) |
1005 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
1007 let mut attr_str = try_opt!(self.node
1010 context.config.max_width - offset.width(),
1012 if !attr_str.is_empty() {
1013 attr_str.push('\n');
1014 attr_str.push_str(&offset.to_string(context.config));
1017 let result = match name {
1018 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1019 None => format!("{}{}", attr_str, vis),
1022 let last_line_width = last_line_width(&result);
1023 let budget = try_opt!(width.checked_sub(last_line_width));
1024 let rewrite = try_opt!(self.node.ty.rewrite(context, budget, offset + last_line_width));
1025 Some(result + &rewrite)
1029 pub fn rewrite_static(prefix: &str,
1030 vis: ast::Visibility,
1033 mutability: ast::Mutability,
1034 expr_opt: Option<&ptr::P<ast::Expr>>,
1035 context: &RewriteContext)
1037 let prefix = format!("{}{} {}{}: ",
1038 format_visibility(vis),
1040 format_mutability(mutability),
1043 let ty_str = try_opt!(ty.rewrite(context,
1044 context.config.max_width - context.block_indent.width() -
1046 context.block_indent));
1048 if let Some(ref expr) = expr_opt {
1049 let lhs = format!("{}{} =", prefix, ty_str);
1051 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1052 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1055 let lhs = format!("{}{};", prefix, ty_str);
1060 pub fn rewrite_associated_type(ident: ast::Ident,
1061 ty_opt: Option<&ptr::P<ast::Ty>>,
1062 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1063 context: &RewriteContext,
1066 let prefix = format!("type {}", ident);
1068 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1069 let bounds: &[_] = &ty_param_bounds.as_slice();
1070 let bound_str = bounds.iter()
1071 .filter_map(|ty_bound| {
1072 ty_bound.rewrite(context, context.config.max_width, indent)
1074 .collect::<Vec<String>>()
1076 if bounds.len() > 0 {
1077 format!(": {}", bound_str)
1085 if let Some(ty) = ty_opt {
1086 let ty_str = try_opt!(ty.rewrite(context,
1087 context.config.max_width - context.block_indent.width() -
1090 context.block_indent));
1091 Some(format!("{} = {};", prefix, ty_str))
1093 Some(format!("{}{};", prefix, type_bounds_str))
1097 impl Rewrite for ast::FunctionRetTy {
1098 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1100 ast::FunctionRetTy::Default(_) => Some(String::new()),
1101 ast::FunctionRetTy::None(_) => {
1103 Some("-> !".to_owned())
1108 ast::FunctionRetTy::Ty(ref ty) => {
1109 let inner_width = try_opt!(width.checked_sub(3));
1110 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1116 impl Rewrite for ast::Arg {
1117 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1118 if is_named_arg(self) {
1119 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1121 if self.ty.node != ast::TyKind::Infer {
1122 result.push_str(": ");
1123 let max_width = try_opt!(width.checked_sub(result.len()));
1124 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1125 result.push_str(&ty_str);
1130 self.ty.rewrite(context, width, offset)
1135 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1137 context: &RewriteContext)
1139 match explicit_self.node {
1140 ast::SelfKind::Region(lt, m, _) => {
1141 let mut_str = format_mutability(m);
1144 let lifetime_str = try_opt!(l.rewrite(context,
1147 Some(format!("&{} {}self", lifetime_str, mut_str))
1149 None => Some(format!("&{}self", mut_str)),
1152 ast::SelfKind::Explicit(ref ty, _) => {
1153 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1155 let mutability = explicit_self_mutability(&args[0]);
1156 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1158 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1160 ast::SelfKind::Value(_) => {
1161 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1163 let mutability = explicit_self_mutability(&args[0]);
1165 Some(format!("{}self", format_mutability(mutability)))
1171 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1172 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1173 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1174 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1181 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1182 if is_named_arg(arg) {
1189 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1191 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1192 _ => arg.ty.span.hi,
1196 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1197 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1198 ident.node != token::special_idents::invalid
1204 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1206 ast::FunctionRetTy::None(ref span) |
1207 ast::FunctionRetTy::Default(ref span) => span.clone(),
1208 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1212 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1213 // Note that ty.span is the span for ty.ident, not the whole item.
1214 let lo = ty.span.lo;
1215 if let Some(ref def) = ty.default {
1216 return mk_sp(lo, def.span.hi);
1218 if ty.bounds.is_empty() {
1221 let hi = match ty.bounds[ty.bounds.len() - 1] {
1222 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1223 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1228 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1230 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1231 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1232 ast::WherePredicate::EqPredicate(ref p) => p.span,
1236 // Return type is (result, force_new_line_for_brace)
1237 fn rewrite_fn_base(context: &RewriteContext,
1241 explicit_self: Option<&ast::ExplicitSelf>,
1242 generics: &ast::Generics,
1243 unsafety: ast::Unsafety,
1244 constness: ast::Constness,
1246 vis: ast::Visibility,
1248 newline_brace: bool,
1250 -> Option<(String, bool)> {
1251 let mut force_new_line_for_brace = false;
1252 // FIXME we'll lose any comments in between parts of the function decl, but
1253 // anyone who comments there probably deserves what they get.
1255 let where_clause = &generics.where_clause;
1257 let mut result = String::with_capacity(1024);
1258 // Vis unsafety abi.
1259 result.push_str(format_visibility(vis));
1261 if let ast::Constness::Const = constness {
1262 result.push_str("const ");
1265 result.push_str(::utils::format_unsafety(unsafety));
1267 if abi != abi::Abi::Rust {
1268 result.push_str(&::utils::format_abi(abi));
1272 result.push_str("fn ");
1273 result.push_str(&ident.to_string());
1276 let generics_indent = indent + result.len();
1277 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1278 let generics_str = try_opt!(rewrite_generics(context,
1281 context.config.max_width,
1284 result.push_str(&generics_str);
1286 // Note that if the width and indent really matter, we'll re-layout the
1287 // return type later anyway.
1288 let ret_str = try_opt!(fd.output
1289 .rewrite(&context, context.config.max_width - indent.width(), indent));
1291 let multi_line_ret_str = ret_str.contains('\n');
1292 let ret_str_len = if multi_line_ret_str {
1299 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1300 compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace);
1302 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1303 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1304 arg_indent = indent.block_indent(context.config);
1305 multi_line_budget = context.config.max_width - arg_indent.width();
1308 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1313 // Check if vertical layout was forced by compute_budget_for_args.
1314 if one_line_budget == 0 {
1315 if context.config.fn_args_paren_newline {
1317 result.push_str(&arg_indent.to_string(context.config));
1318 arg_indent = arg_indent + 1; // extra space for `(`
1321 result.push_str("(\n");
1322 result.push_str(&arg_indent.to_string(context.config));
1328 if multi_line_ret_str {
1329 one_line_budget = 0;
1332 // A conservative estimation, to goal is to be over all parens in generics
1333 let args_start = generics.ty_params
1335 .map_or(span.lo, |tp| end_typaram(tp));
1336 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1337 span_for_return(&fd.output).lo);
1338 let arg_str = try_opt!(rewrite_args(context,
1348 let multi_line_arg_str = arg_str.contains('\n');
1350 let put_args_in_block = match context.config.fn_args_layout {
1351 FnArgLayoutStyle::Block => multi_line_arg_str,
1352 FnArgLayoutStyle::BlockAlways => true,
1354 } && fd.inputs.len() > 0;
1356 if put_args_in_block {
1357 arg_indent = indent.block_indent(context.config);
1359 result.push_str(&arg_indent.to_string(context.config));
1360 result.push_str(&arg_str);
1362 result.push_str(&indent.to_string(context.config));
1365 result.push_str(&arg_str);
1370 if !ret_str.is_empty() {
1371 let ret_should_indent = match context.config.fn_args_layout {
1372 // If our args are block layout then we surely must have space.
1373 FnArgLayoutStyle::Block if put_args_in_block => false,
1374 FnArgLayoutStyle::BlockAlways => false,
1376 // If we've already gone multi-line, or the return type would push
1377 // over the max width, then put the return type on a new line.
1378 result.contains("\n") || multi_line_ret_str ||
1379 result.len() + indent.width() + ret_str_len > context.config.max_width
1382 let ret_indent = if ret_should_indent {
1383 let indent = match context.config.fn_return_indent {
1384 ReturnIndent::WithWhereClause => indent + 4,
1385 // Aligning with non-existent args looks silly.
1386 _ if arg_str.is_empty() => {
1387 force_new_line_for_brace = true;
1390 // FIXME: we might want to check that using the arg indent
1391 // doesn't blow our budget, and if it does, then fallback to
1392 // the where clause indent.
1397 result.push_str(&indent.to_string(context.config));
1401 Indent::new(indent.width(), result.len())
1404 if multi_line_ret_str {
1405 // Now that we know the proper indent and width, we need to
1406 // re-layout the return type.
1408 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1409 let ret_str = try_opt!(fd.output
1410 .rewrite(context, budget, ret_indent));
1411 result.push_str(&ret_str);
1413 result.push_str(&ret_str);
1416 // Comment between return type and the end of the decl.
1417 let snippet_lo = fd.output.span().hi;
1418 if where_clause.predicates.is_empty() {
1419 let snippet_hi = span.hi;
1420 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1421 let snippet = snippet.trim();
1422 if !snippet.is_empty() {
1424 result.push_str(snippet);
1427 // FIXME it would be nice to catch comments between the return type
1428 // and the where clause, but we don't have a span for the where
1433 let should_compress_where = match context.config.where_density {
1434 Density::Compressed => !result.contains('\n') || put_args_in_block,
1435 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1437 } || (put_args_in_block && ret_str.is_empty());
1439 let where_density = if should_compress_where {
1446 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1447 let where_clause_str = try_opt!(rewrite_where_clause(context,
1450 context.config.fn_brace_style,
1458 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1459 !where_clause_str.contains('\n') {
1463 result.push_str(&where_clause_str);
1465 Some((result, force_new_line_for_brace))
1468 fn rewrite_args(context: &RewriteContext,
1470 explicit_self: Option<&ast::ExplicitSelf>,
1471 one_line_budget: usize,
1472 multi_line_budget: usize,
1478 let mut arg_item_strs = try_opt!(args.iter()
1480 arg.rewrite(&context, multi_line_budget, arg_indent)
1482 .collect::<Option<Vec<_>>>());
1484 // Account for sugary self.
1485 // FIXME: the comment for the self argument is dropped. This is blocked
1486 // on rust issue #27522.
1487 let min_args = explicit_self.and_then(|explicit_self| {
1488 rewrite_explicit_self(explicit_self, args, context)
1490 .map_or(1, |self_str| {
1491 arg_item_strs[0] = self_str;
1495 // Comments between args.
1496 let mut arg_items = Vec::new();
1498 arg_items.push(ListItem::from_str(""));
1501 // FIXME(#21): if there are no args, there might still be a comment, but
1502 // without spans for the comment or parens, there is no chance of
1503 // getting it right. You also don't get to put a comment on self, unless
1505 if args.len() >= min_args || variadic {
1506 let comment_span_start = if min_args == 2 {
1507 let second_arg_start = if arg_has_pattern(&args[1]) {
1512 let reduced_span = mk_sp(span.lo, second_arg_start);
1514 context.codemap.span_after_last(reduced_span, ",")
1519 enum ArgumentKind<'a> {
1520 Regular(&'a ast::Arg),
1524 let variadic_arg = if variadic {
1525 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1526 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1527 Some(ArgumentKind::Variadic(variadic_start))
1532 let more_items = itemize_list(context.codemap,
1533 args[min_args - 1..]
1535 .map(ArgumentKind::Regular)
1536 .chain(variadic_arg),
1540 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1541 ArgumentKind::Variadic(start) => start,
1546 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1547 ArgumentKind::Variadic(start) => start + BytePos(3),
1552 ArgumentKind::Regular(..) => None,
1553 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1559 arg_items.extend(more_items);
1562 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1563 item.item = Some(arg);
1566 let indent = match context.config.fn_arg_indent {
1567 BlockIndentStyle::Inherit => indent,
1568 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1569 BlockIndentStyle::Visual => arg_indent,
1572 let tactic = definitive_tactic(&arg_items,
1573 context.config.fn_args_density.to_list_tactic(),
1575 let budget = match tactic {
1576 DefinitiveListTactic::Horizontal => one_line_budget,
1577 _ => multi_line_budget,
1580 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1582 let end_with_newline = match context.config.fn_args_layout {
1583 FnArgLayoutStyle::Block |
1584 FnArgLayoutStyle::BlockAlways => true,
1588 let fmt = ListFormatting {
1591 trailing_separator: SeparatorTactic::Never,
1594 ends_with_newline: end_with_newline,
1595 config: context.config,
1598 write_list(&arg_items, &fmt)
1601 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1602 if let ast::PatKind::Ident(_,
1604 node: ast::Ident { name: ast::Name(0u32), .. },
1614 fn compute_budgets_for_args(context: &RewriteContext,
1618 newline_brace: bool)
1619 -> (usize, usize, Indent) {
1620 // Try keeping everything on the same line.
1621 if !result.contains("\n") {
1622 // 3 = `() `, space is before ret_string.
1623 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1627 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1629 if one_line_budget > 0 {
1630 let multi_line_budget = context.config.max_width -
1631 (indent.width() + result.len() + "()".len());
1633 return (one_line_budget, multi_line_budget, indent + result.len() + 1);
1637 // Didn't work. we must force vertical layout and put args on a newline.
1638 let new_indent = indent.block_indent(context.config);
1639 let used_space = new_indent.width() + 2; // account for `(` and `)`
1640 let max_space = context.config.max_width;
1641 if used_space <= max_space {
1642 (0, max_space - used_space, new_indent)
1644 // Whoops! bankrupt.
1645 // FIXME: take evasive action, perhaps kill the indent or something.
1646 panic!("in compute_budgets_for_args");
1650 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1651 match config.fn_brace_style {
1652 BraceStyle::AlwaysNextLine => true,
1653 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1658 fn rewrite_generics(context: &RewriteContext,
1659 generics: &ast::Generics,
1662 generics_offset: Indent,
1665 // FIXME: convert bounds to where clauses where they get too big or if
1666 // there is a where clause at all.
1667 let lifetimes: &[_] = &generics.lifetimes;
1668 let tys: &[_] = &generics.ty_params;
1669 if lifetimes.is_empty() && tys.is_empty() {
1670 return Some(String::new());
1673 let offset = match context.config.generics_indent {
1674 BlockIndentStyle::Inherit => offset,
1675 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1677 BlockIndentStyle::Visual => generics_offset + 1,
1680 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1681 // FIXME: might need to insert a newline if the generics are really long.
1683 // Strings for the generics.
1684 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1685 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1687 // Extract comments between generics.
1688 let lt_spans = lifetimes.iter().map(|l| {
1689 let hi = if l.bounds.is_empty() {
1692 l.bounds[l.bounds.len() - 1].span.hi
1694 mk_sp(l.lifetime.span.lo, hi)
1696 let ty_spans = tys.iter().map(span_for_ty_param);
1698 let items = itemize_list(context.codemap,
1699 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1703 // FIXME: don't clone
1704 |&(_, ref str)| str.clone(),
1705 context.codemap.span_after(span, "<"),
1707 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1709 Some(format!("<{}>", list_str))
1712 fn rewrite_trait_bounds(context: &RewriteContext,
1713 type_param_bounds: &ast::TyParamBounds,
1717 let bounds: &[_] = &type_param_bounds.as_slice();
1719 if bounds.is_empty() {
1720 return Some(String::new());
1723 let bound_str = bounds.iter()
1724 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1725 .collect::<Vec<String>>()
1728 let mut result = String::new();
1729 result.push_str(": ");
1730 result.push_str(&bound_str);
1734 fn rewrite_where_clause(context: &RewriteContext,
1735 where_clause: &ast::WhereClause,
1737 brace_style: BraceStyle,
1742 allow_trailing_comma: bool,
1743 span_end: Option<BytePos>)
1745 if where_clause.predicates.is_empty() {
1746 return Some(String::new());
1749 let extra_indent = match context.config.where_indent {
1750 BlockIndentStyle::Inherit => Indent::empty(),
1751 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1754 let offset = match context.config.where_pred_indent {
1755 BlockIndentStyle::Inherit => indent + extra_indent,
1756 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1757 // 6 = "where ".len()
1758 BlockIndentStyle::Visual => indent + extra_indent + 6,
1760 // FIXME: if where_pred_indent != Visual, then the budgets below might
1761 // be out by a char or two.
1763 let budget = context.config.max_width - offset.width();
1764 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1765 // If we don't have the start of the next span, then use the end of the
1766 // predicates, but that means we miss comments.
1767 let len = where_clause.predicates.len();
1768 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1769 let span_end = span_end.unwrap_or(end_of_preds);
1770 let items = itemize_list(context.codemap,
1771 where_clause.predicates.iter(),
1773 |pred| span_for_where_pred(pred).lo,
1774 |pred| span_for_where_pred(pred).hi,
1775 |pred| pred.rewrite(&context, budget, offset),
1778 let item_vec = items.collect::<Vec<_>>();
1779 // FIXME: we don't need to collect here if the where_layout isn't
1780 // HorizontalVertical.
1781 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1782 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1784 let fmt = ListFormatting {
1787 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1790 ends_with_newline: true,
1791 config: context.config,
1793 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1795 let end_length = if terminator == "{" {
1796 // If the brace is on the next line we don't need to count it otherwise it needs two
1799 BraceStyle::AlwaysNextLine => 0,
1800 BraceStyle::PreferSameLine => 2,
1801 BraceStyle::SameLineWhere => 0,
1803 } else if terminator == "=" {
1808 if density == Density::Tall || preds_str.contains('\n') ||
1809 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1810 Some(format!("\n{}where {}",
1811 (indent + extra_indent).to_string(context.config),
1814 Some(format!(" where {}", preds_str))
1818 fn format_header(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
1819 format!("{}{}{}", format_visibility(vis), item_name, ident)
1822 fn format_generics(context: &RewriteContext,
1823 generics: &ast::Generics,
1826 brace_style: BraceStyle,
1827 force_same_line_brace: bool,
1829 generics_offset: Indent,
1832 let mut result = try_opt!(rewrite_generics(context,
1835 context.config.max_width,
1839 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1840 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1841 let where_clause_str = try_opt!(rewrite_where_clause(context,
1842 &generics.where_clause,
1845 context.block_indent,
1851 result.push_str(&where_clause_str);
1852 if !force_same_line_brace &&
1853 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1855 result.push_str(&context.block_indent.to_string(context.config));
1859 result.push_str(opener);
1861 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1863 result.push_str(&context.block_indent.to_string(context.config));
1867 result.push_str(opener);