1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use utils::{CodeMapSpanUtils, format_mutability, format_visibility, contains_skip, end_typaram,
15 wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
17 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
18 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
19 use comment::{FindUncommented, contains_comment};
20 use visitor::FmtVisitor;
21 use rewrite::{Rewrite, RewriteContext};
22 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use syntax::{ast, abi, ptr, codemap};
25 use syntax::codemap::{Span, BytePos, mk_sp};
26 use syntax::parse::token;
27 use syntax::ast::ImplItem;
29 // Statements of the form
30 // let pat: ty = init;
31 impl Rewrite for ast::Local {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33 let mut result = "let ".to_owned();
34 let pattern_offset = offset + result.len();
36 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
39 result.push_str(&pat_str);
41 // String that is placed within the assignment pattern and expression.
43 let mut infix = String::new();
45 if let Some(ref ty) = self.ty {
48 let indent = offset + last_line_width(&result) + 2;
49 let budget = try_opt!(width.checked_sub(indent.width() + 1));
50 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
53 infix.push_str(&rewrite);
56 if self.init.is_some() {
63 result.push_str(&infix);
65 if let Some(ref ex) = self.init {
66 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68 // 1 = trailing semicolon;
70 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
78 impl<'a> FmtVisitor<'a> {
79 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
80 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
81 self.buffer.push_str(&abi_str);
83 let snippet = self.snippet(span);
84 let brace_pos = snippet.find_uncommented("{").unwrap();
86 if fm.items.is_empty() && !contains_comment(&snippet[brace_pos..]) {
87 self.buffer.push_str("{");
89 // FIXME: this skips comments between the extern keyword and the opening
91 self.last_pos = span.lo + BytePos(brace_pos as u32);
92 self.block_indent = self.block_indent.block_indent(self.config);
94 for item in &fm.items {
95 self.format_foreign_item(&*item);
98 self.block_indent = self.block_indent.block_unindent(self.config);
99 self.format_missing_with_indent(span.hi - BytePos(1));
102 self.buffer.push_str("}");
103 self.last_pos = span.hi;
106 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
107 self.format_missing_with_indent(item.span.lo);
108 // Drop semicolon or it will be interpreted as comment.
109 // FIXME: this may be a faulty span from libsyntax.
110 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
113 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
114 let indent = self.block_indent;
115 let rewrite = rewrite_fn_base(&self.get_context(),
121 ast::Unsafety::Normal,
122 ast::Constness::NotConst,
123 // These are not actually rust functions,
124 // but we format them as such.
132 Some((new_fn, _)) => {
133 self.buffer.push_str(&new_fn);
134 self.buffer.push_str(";");
136 None => self.format_missing(item.span.hi),
139 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
140 // FIXME(#21): we're dropping potential comments in between the
141 // function keywords here.
142 let vis = match format_visibility(&item.vis) {
146 let mut_str = if is_mutable {
151 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
152 let offset = self.block_indent + prefix.len();
154 let width = self.config.max_width - offset.width() - 1;
155 let rewrite = ty.rewrite(&self.get_context(), width, offset);
159 self.buffer.push_str(&prefix);
160 self.buffer.push_str(&result);
161 self.buffer.push_str(";");
163 None => self.format_missing(item.span.hi),
168 self.last_pos = item.span.hi;
171 pub fn rewrite_fn(&mut self,
175 explicit_self: Option<&ast::ExplicitSelf>,
176 generics: &ast::Generics,
177 unsafety: ast::Unsafety,
178 constness: ast::Constness,
180 vis: &ast::Visibility,
184 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
185 let context = self.get_context();
187 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
188 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
189 !context.config.fn_empty_single_line;
191 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
205 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
206 newline_brace = false;
207 } else if force_newline_brace {
208 newline_brace = true;
211 // Prepare for the function body by possibly adding a newline and
213 // FIXME we'll miss anything between the end of the signature and the
214 // start of the body, but we need more spans from the compiler to solve
218 result.push_str(&indent.to_string(self.config));
223 self.single_line_fn(&result, block).or_else(|| Some(result))
226 pub fn rewrite_required_fn(&mut self,
229 sig: &ast::MethodSig,
232 // Drop semicolon or it will be interpreted as comment.
233 let span = mk_sp(span.lo, span.hi - BytePos(1));
234 let context = self.get_context();
236 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
240 Some(&sig.explicit_self),
245 &ast::Visibility::Inherited,
250 // Re-attach semicolon
256 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
257 if fn_str.contains('\n') {
261 let codemap = self.get_context().codemap;
263 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
264 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
265 return Some(format!("{}{{}}", fn_str));
268 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
270 if let Some(ref e) = block.expr {
271 let suffix = if semicolon_for_expr(e) {
277 e.rewrite(&self.get_context(),
278 self.config.max_width - self.block_indent.width(),
281 .or_else(|| Some(self.snippet(e.span)))
282 } else if let Some(ref stmt) = block.stmts.first() {
283 stmt.rewrite(&self.get_context(),
284 self.config.max_width - self.block_indent.width(),
291 if let Some(res) = rewrite {
292 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
293 if !res.contains('\n') && width <= self.config.max_width {
294 return Some(format!("{}{{ {} }}", fn_str, res));
302 pub fn visit_enum(&mut self,
304 vis: &ast::Visibility,
305 enum_def: &ast::EnumDef,
306 generics: &ast::Generics,
308 let header_str = match format_header("enum ", ident, vis) {
312 self.buffer.push_str(&header_str);
314 let enum_snippet = self.snippet(span);
315 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
316 let generics_str = format_generics(&self.get_context(),
320 self.config.item_brace_style,
321 enum_def.variants.is_empty(),
323 self.block_indent.block_indent(self.config),
324 mk_sp(span.lo, body_start))
326 self.buffer.push_str(&generics_str);
328 self.last_pos = body_start;
330 self.block_indent = self.block_indent.block_indent(self.config);
331 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
333 Some(ref body_str) => self.buffer.push_str(&body_str),
334 None => self.format_missing(span.hi - BytePos(1)),
336 self.block_indent = self.block_indent.block_unindent(self.config);
338 if variant_list.is_some() {
339 self.buffer.push_str(&self.block_indent.to_string(self.config));
341 self.buffer.push_str("}");
342 self.last_pos = span.hi;
345 // Format the body of an enum definition
346 fn format_variant_list(&self,
347 enum_def: &ast::EnumDef,
351 if enum_def.variants.is_empty() {
354 let mut result = String::with_capacity(1024);
356 let indentation = self.block_indent.to_string(self.config);
357 result.push_str(&indentation);
359 let items = itemize_list(self.codemap,
360 enum_def.variants.iter(),
363 if !f.node.attrs.is_empty() {
364 f.node.attrs[0].span.lo
370 |f| self.format_variant(f),
374 let budget = self.config.max_width - self.block_indent.width() - 2;
375 let fmt = ListFormatting {
376 tactic: DefinitiveListTactic::Vertical,
378 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
379 indent: self.block_indent,
381 ends_with_newline: true,
385 let list = try_opt!(write_list(items, &fmt));
386 result.push_str(&list);
391 // Variant of an enum.
392 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
393 if contains_skip(&field.node.attrs) {
394 let lo = field.node.attrs[0].span.lo;
395 let span = mk_sp(lo, field.span.hi);
396 return Some(self.snippet(span));
399 let indent = self.block_indent;
400 let mut result = try_opt!(field.node
402 .rewrite(&self.get_context(),
403 self.config.max_width - indent.width(),
405 if !result.is_empty() {
407 result.push_str(&indent.to_string(self.config));
410 let context = self.get_context();
411 let variant_body = match field.node.data {
412 ast::VariantData::Tuple(..) |
413 ast::VariantData::Struct(..) => {
414 // FIXME: Should limit the width, as we have a trailing comma
415 format_struct(&context,
418 &ast::Visibility::Inherited,
423 Some(self.config.struct_variant_width))
425 ast::VariantData::Unit(..) => {
426 let tag = if let Some(ref expr) = field.node.disr_expr {
427 format!("{} = {}", field.node.name, self.snippet(expr.span))
429 field.node.name.to_string()
433 self.config.max_width,
434 self.config.max_width - indent.width(),
439 if let Some(variant_str) = variant_body {
440 result.push_str(&variant_str);
448 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
449 if let ast::ItemKind::Impl(unsafety,
454 ref items) = item.node {
455 let mut result = String::new();
456 result.push_str(try_opt!(format_visibility(&item.vis)));
457 result.push_str(format_unsafety(unsafety));
458 result.push_str("impl");
460 let lo = context.codemap.span_after(item.span, "impl");
461 let hi = match *trait_ref {
462 Some(ref tr) => tr.path.span.lo,
463 None => self_ty.span.lo,
465 let generics_str = try_opt!(rewrite_generics(context,
468 context.config.max_width,
469 offset + result.len(),
471 result.push_str(&generics_str);
473 // FIXME might need to linebreak in the impl header, here would be a
476 if polarity == ast::ImplPolarity::Negative {
477 result.push_str("!");
479 if let Some(ref trait_ref) = *trait_ref {
480 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
481 let indent = offset + result.len();
482 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
483 result.push_str(" for ");
486 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
487 let indent = offset + result.len();
488 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
490 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
491 let where_clause_str = try_opt!(rewrite_where_clause(context,
492 &generics.where_clause,
494 context.config.item_brace_style,
495 context.block_indent,
497 context.config.where_density,
502 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
503 result.push_str(&where_clause_str);
504 if where_clause_str.contains('\n') {
505 let white_space = offset.to_string(context.config);
506 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
508 result.push_str(" {}");
513 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
515 let width = context.block_indent.width() + context.config.tab_spaces - 1;
516 let where_indent = Indent::new(0, width);
517 result.push_str(&where_indent.to_string(context.config));
519 result.push_str(&where_clause_str);
521 match context.config.item_brace_style {
522 BraceStyle::AlwaysNextLine => result.push('\n'),
523 BraceStyle::PreferSameLine => result.push(' '),
524 BraceStyle::SameLineWhere => {
525 if !where_clause_str.is_empty() {
527 result.push_str(&offset.to_string(context.config));
536 let snippet = context.snippet(item.span);
537 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
539 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
540 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
541 visitor.block_indent = context.block_indent.block_indent(context.config);
542 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
545 visitor.visit_impl_item(&item);
548 visitor.format_missing(item.span.hi - BytePos(1));
550 let inner_indent_str = visitor.block_indent.to_string(context.config);
551 let outer_indent_str = context.block_indent.to_string(context.config);
554 result.push_str(&inner_indent_str);
555 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
557 result.push_str(&outer_indent_str);
560 if result.chars().last().unwrap() == '{' {
571 fn is_impl_single_line(context: &RewriteContext,
572 items: &Vec<ImplItem>,
574 where_clause_str: &str,
577 let snippet = context.snippet(item.span);
578 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
580 Some(context.config.impl_empty_single_line && items.is_empty() &&
581 result.len() + where_clause_str.len() <= context.config.max_width &&
582 !contains_comment(&snippet[open_pos..]))
585 pub fn format_struct(context: &RewriteContext,
588 vis: &ast::Visibility,
589 struct_def: &ast::VariantData,
590 generics: Option<&ast::Generics>,
593 one_line_width: Option<usize>)
596 ast::VariantData::Unit(..) => format_unit_struct(item_name, ident, vis),
597 ast::VariantData::Tuple(ref fields, _) => {
598 format_tuple_struct(context,
607 ast::VariantData::Struct(ref fields, _) => {
608 format_struct_struct(context,
621 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
622 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
624 let mut result = String::new();
625 let header = format!("{}{}trait {}",
626 try_opt!(format_visibility(&item.vis)),
627 format_unsafety(unsafety),
630 result.push_str(&header);
632 let body_lo = context.codemap.span_after(item.span, "{");
634 let generics_str = try_opt!(rewrite_generics(context,
637 context.config.max_width,
638 offset + result.len(),
639 mk_sp(item.span.lo, body_lo)));
640 result.push_str(&generics_str);
642 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
645 context.config.max_width));
646 // If the trait, generics, and trait bound cannot fit on the same line,
647 // put the trait bounds on an indented new line
648 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
649 context.config.ideal_width {
651 let width = context.block_indent.width() + context.config.tab_spaces;
652 let trait_indent = Indent::new(0, width);
653 result.push_str(&trait_indent.to_string(context.config));
655 result.push_str(&trait_bound_str);
657 let has_body = !trait_items.is_empty();
660 if (context.config.where_density == Density::Compressed &&
661 (!result.contains('\n') ||
662 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
663 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
664 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
665 !result.contains('\n')) {
671 let where_budget = try_opt!(context.config
673 .checked_sub(last_line_width(&result)));
674 let where_clause_str = try_opt!(rewrite_where_clause(context,
675 &generics.where_clause,
677 context.config.item_brace_style,
678 context.block_indent,
684 // If the where clause cannot fit on the same line,
685 // put the where clause on a new line
686 if !where_clause_str.contains('\n') &&
687 last_line_width(&result) + where_clause_str.len() + offset.width() >
688 context.config.ideal_width {
690 let width = context.block_indent.width() + context.config.tab_spaces - 1;
691 let where_indent = Indent::new(0, width);
692 result.push_str(&where_indent.to_string(context.config));
694 result.push_str(&where_clause_str);
696 match context.config.item_brace_style {
697 BraceStyle::AlwaysNextLine => {
699 result.push_str(&offset.to_string(context.config));
701 BraceStyle::PreferSameLine => result.push(' '),
702 BraceStyle::SameLineWhere => {
703 if !where_clause_str.is_empty() &&
704 (trait_items.len() > 0 || result.contains('\n')) {
706 result.push_str(&offset.to_string(context.config));
714 let snippet = context.snippet(item.span);
715 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
717 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
718 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
719 visitor.block_indent = context.block_indent.block_indent(context.config);
720 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
722 for item in trait_items {
723 visitor.visit_trait_item(&item);
726 visitor.format_missing(item.span.hi - BytePos(1));
728 let inner_indent_str = visitor.block_indent.to_string(context.config);
729 let outer_indent_str = context.block_indent.to_string(context.config);
732 result.push_str(&inner_indent_str);
733 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
735 result.push_str(&outer_indent_str);
736 } else if result.contains('\n') {
747 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> Option<String> {
748 let mut result = String::with_capacity(1024);
750 let header_str = try_opt!(format_header(item_name, ident, vis));
751 result.push_str(&header_str);
757 fn format_struct_struct(context: &RewriteContext,
760 vis: &ast::Visibility,
761 fields: &[ast::StructField],
762 generics: Option<&ast::Generics>,
765 one_line_width: Option<usize>)
767 let mut result = String::with_capacity(1024);
769 let header_str = try_opt!(format_header(item_name, ident, vis));
770 result.push_str(&header_str);
772 let body_lo = context.codemap.span_after(span, "{");
774 let generics_str = match generics {
776 try_opt!(format_generics(context,
780 context.config.item_brace_style,
783 offset + header_str.len(),
784 mk_sp(span.lo, body_lo)))
787 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
788 format!("\n{}{{", context.block_indent.to_string(context.config))
794 result.push_str(&generics_str);
796 // FIXME(#919): properly format empty structs and their comments.
797 if fields.is_empty() {
798 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
802 let item_indent = offset.block_indent(context.config);
804 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
806 let items = itemize_list(context.codemap,
810 // Include attributes and doc comments, if present
811 if !field.attrs.is_empty() {
812 field.attrs[0].span.lo
817 |field| field.ty.span.hi,
818 |field| field.rewrite(context, item_budget, item_indent),
819 context.codemap.span_after(span, "{"),
821 .collect::<Vec<_>>();
823 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
825 let tactic = match one_line_width {
826 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
827 None => DefinitiveListTactic::Vertical,
830 let fmt = ListFormatting {
833 trailing_separator: context.config.struct_trailing_comma,
836 ends_with_newline: true,
837 config: context.config,
839 let items_str = try_opt!(write_list(&items, &fmt));
840 if one_line_width.is_some() && !items_str.contains('\n') {
841 Some(format!("{} {} }}", result, items_str))
843 Some(format!("{}\n{}{}\n{}}}",
845 offset.block_indent(context.config).to_string(context.config),
847 offset.to_string(context.config)))
851 fn format_tuple_struct(context: &RewriteContext,
854 vis: &ast::Visibility,
855 fields: &[ast::StructField],
856 generics: Option<&ast::Generics>,
860 let mut result = String::with_capacity(1024);
862 let header_str = try_opt!(format_header(item_name, ident, vis));
863 result.push_str(&header_str);
865 // FIXME(#919): don't lose comments on empty tuple structs.
866 let body_lo = if fields.is_empty() {
872 let where_clause_str = match generics {
873 Some(ref generics) => {
874 let generics_str = try_opt!(rewrite_generics(context,
877 context.config.max_width,
878 offset + header_str.len(),
879 mk_sp(span.lo, body_lo)));
880 result.push_str(&generics_str);
882 let where_budget = try_opt!(context.config
884 .checked_sub(last_line_width(&result)));
885 try_opt!(rewrite_where_clause(context,
886 &generics.where_clause,
888 context.config.item_brace_style,
889 context.block_indent,
896 None => "".to_owned(),
900 let item_indent = context.block_indent + result.len();
902 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
904 let items = itemize_list(context.codemap,
908 // Include attributes and doc comments, if present
909 if !field.attrs.is_empty() {
910 field.attrs[0].span.lo
915 |field| field.ty.span.hi,
916 |field| field.rewrite(context, item_budget, item_indent),
917 context.codemap.span_after(span, "("),
919 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
920 result.push_str(&body);
923 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
924 (result.contains('\n') ||
925 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
926 context.config.max_width) {
927 // We need to put the where clause on a new line, but we didn'to_string
928 // know that earlier, so the where clause will not be indented properly.
930 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
931 .to_string(context.config));
933 result.push_str(&where_clause_str);
938 pub fn rewrite_type_alias(context: &RewriteContext,
942 generics: &ast::Generics,
943 vis: &ast::Visibility,
946 let mut result = String::new();
948 result.push_str(&try_opt!(format_visibility(&vis)));
949 result.push_str("type ");
950 result.push_str(&ident.to_string());
952 let generics_indent = indent + result.len();
953 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
954 let generics_width = context.config.max_width - " =".len();
955 let generics_str = try_opt!(rewrite_generics(context,
962 result.push_str(&generics_str);
964 let where_budget = try_opt!(context.config
966 .checked_sub(last_line_width(&result)));
967 let where_clause_str = try_opt!(rewrite_where_clause(context,
968 &generics.where_clause,
970 context.config.item_brace_style,
973 context.config.where_density,
977 result.push_str(&where_clause_str);
978 result.push_str(" = ");
980 let line_width = last_line_width(&result);
981 // This checked_sub may fail as the extra space after '=' is not taken into account
982 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
983 let budget = context.config
985 .checked_sub(indent.width() + line_width + ";".len())
987 let type_indent = indent + line_width;
988 // Try to fit the type on the same line
989 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
991 // The line was too short, try to put the type on the next line
993 // Remove the space after '='
995 let type_indent = indent.block_indent(context.config);
997 result.push_str(&type_indent.to_string(context.config));
998 let budget = try_opt!(context.config
1000 .checked_sub(type_indent.width() + ";".len()));
1001 ty.rewrite(context, budget, type_indent)
1003 result.push_str(&ty_str);
1004 result.push_str(";");
1008 impl Rewrite for ast::StructField {
1009 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1010 if contains_skip(&self.attrs) {
1011 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1012 return wrap_str(span, context.config.max_width, width, offset);
1015 let name = self.ident;
1016 let vis = try_opt!(format_visibility(&self.vis));
1017 let mut attr_str = try_opt!(self.attrs
1018 .rewrite(context, context.config.max_width - offset.width(), offset));
1019 if !attr_str.is_empty() {
1020 attr_str.push('\n');
1021 attr_str.push_str(&offset.to_string(context.config));
1024 let result = match name {
1025 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1026 None => format!("{}{}", attr_str, vis),
1029 let last_line_width = last_line_width(&result);
1030 let budget = try_opt!(width.checked_sub(last_line_width));
1031 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1032 Some(result + &rewrite)
1036 pub fn rewrite_static(prefix: &str,
1037 vis: &ast::Visibility,
1040 mutability: ast::Mutability,
1041 expr_opt: Option<&ptr::P<ast::Expr>>,
1042 context: &RewriteContext)
1044 let prefix = format!("{}{} {}{}: ",
1045 try_opt!(format_visibility(vis)),
1047 format_mutability(mutability),
1050 let ty_str = try_opt!(ty.rewrite(context,
1051 context.config.max_width - context.block_indent.width() -
1053 context.block_indent));
1055 if let Some(ref expr) = expr_opt {
1056 let lhs = format!("{}{} =", prefix, ty_str);
1058 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1059 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1062 let lhs = format!("{}{};", prefix, ty_str);
1067 pub fn rewrite_associated_type(ident: ast::Ident,
1068 ty_opt: Option<&ptr::P<ast::Ty>>,
1069 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1070 context: &RewriteContext,
1073 let prefix = format!("type {}", ident);
1075 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1076 let bounds: &[_] = &ty_param_bounds;
1077 let bound_str = bounds.iter()
1078 .filter_map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1079 .collect::<Vec<String>>()
1081 if bounds.len() > 0 {
1082 format!(": {}", bound_str)
1090 if let Some(ty) = ty_opt {
1091 let ty_str = try_opt!(ty.rewrite(context,
1092 context.config.max_width - context.block_indent.width() -
1095 context.block_indent));
1096 Some(format!("{} = {};", prefix, ty_str))
1098 Some(format!("{}{};", prefix, type_bounds_str))
1102 impl Rewrite for ast::FunctionRetTy {
1103 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1105 ast::FunctionRetTy::Default(_) => Some(String::new()),
1106 ast::FunctionRetTy::None(_) => {
1108 Some("-> !".to_owned())
1113 ast::FunctionRetTy::Ty(ref ty) => {
1114 let inner_width = try_opt!(width.checked_sub(3));
1115 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1121 impl Rewrite for ast::Arg {
1122 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1123 if is_named_arg(self) {
1124 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1126 if self.ty.node != ast::TyKind::Infer {
1127 result.push_str(": ");
1128 let max_width = try_opt!(width.checked_sub(result.len()));
1129 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1130 result.push_str(&ty_str);
1135 self.ty.rewrite(context, width, offset)
1140 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1142 context: &RewriteContext)
1144 match explicit_self.node {
1145 ast::SelfKind::Region(lt, m, _) => {
1146 let mut_str = format_mutability(m);
1150 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1151 Some(format!("&{} {}self", lifetime_str, mut_str))
1153 None => Some(format!("&{}self", mut_str)),
1156 ast::SelfKind::Explicit(ref ty, _) => {
1157 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1159 let mutability = explicit_self_mutability(&args[0]);
1160 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1162 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1164 ast::SelfKind::Value(_) => {
1165 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1167 let mutability = explicit_self_mutability(&args[0]);
1169 Some(format!("{}self", format_mutability(mutability)))
1175 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1176 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1177 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1178 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1185 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1186 if is_named_arg(arg) {
1193 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1195 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1196 _ => arg.ty.span.hi,
1200 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1201 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1202 ident.node != token::keywords::Invalid.ident()
1208 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1210 ast::FunctionRetTy::None(ref span) |
1211 ast::FunctionRetTy::Default(ref span) => span.clone(),
1212 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1216 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1217 // Note that ty.span is the span for ty.ident, not the whole item.
1218 let lo = ty.span.lo;
1219 if let Some(ref def) = ty.default {
1220 return mk_sp(lo, def.span.hi);
1222 if ty.bounds.is_empty() {
1225 let hi = match ty.bounds[ty.bounds.len() - 1] {
1226 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1227 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1232 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1234 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1235 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1236 ast::WherePredicate::EqPredicate(ref p) => p.span,
1240 // Return type is (result, force_new_line_for_brace)
1241 fn rewrite_fn_base(context: &RewriteContext,
1245 explicit_self: Option<&ast::ExplicitSelf>,
1246 generics: &ast::Generics,
1247 unsafety: ast::Unsafety,
1248 constness: ast::Constness,
1250 vis: &ast::Visibility,
1252 newline_brace: bool,
1254 -> Option<(String, bool)> {
1255 let mut force_new_line_for_brace = false;
1256 // FIXME we'll lose any comments in between parts of the function decl, but
1257 // anyone who comments there probably deserves what they get.
1259 let where_clause = &generics.where_clause;
1261 let mut result = String::with_capacity(1024);
1262 // Vis unsafety abi.
1263 result.push_str(try_opt!(format_visibility(vis)));
1265 if let ast::Constness::Const = constness {
1266 result.push_str("const ");
1269 result.push_str(::utils::format_unsafety(unsafety));
1271 if abi != abi::Abi::Rust {
1272 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1276 result.push_str("fn ");
1277 result.push_str(&ident.to_string());
1280 let generics_indent = indent + result.len();
1281 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1282 let generics_str = try_opt!(rewrite_generics(context,
1285 context.config.max_width,
1288 result.push_str(&generics_str);
1290 // Note that if the width and indent really matter, we'll re-layout the
1291 // return type later anyway.
1292 let ret_str = try_opt!(fd.output
1293 .rewrite(&context, context.config.max_width - indent.width(), indent));
1295 let multi_line_ret_str = ret_str.contains('\n');
1296 let ret_str_len = if multi_line_ret_str {
1303 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1304 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1306 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1307 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1308 arg_indent = indent.block_indent(context.config);
1309 multi_line_budget = context.config.max_width - arg_indent.width();
1312 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1317 // Check if vertical layout was forced by compute_budget_for_args.
1318 if one_line_budget == 0 {
1319 if context.config.fn_args_paren_newline {
1321 result.push_str(&arg_indent.to_string(context.config));
1322 arg_indent = arg_indent + 1; // extra space for `(`
1325 result.push_str("(\n");
1326 result.push_str(&arg_indent.to_string(context.config));
1332 if multi_line_ret_str {
1333 one_line_budget = 0;
1336 // A conservative estimation, to goal is to be over all parens in generics
1337 let args_start = generics.ty_params
1339 .map_or(span.lo, |tp| end_typaram(tp));
1340 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1341 span_for_return(&fd.output).lo);
1342 let arg_str = try_opt!(rewrite_args(context,
1352 let multi_line_arg_str = arg_str.contains('\n');
1354 let put_args_in_block = match context.config.fn_args_layout {
1355 FnArgLayoutStyle::Block => multi_line_arg_str,
1356 FnArgLayoutStyle::BlockAlways => true,
1358 } && fd.inputs.len() > 0;
1360 if put_args_in_block {
1361 arg_indent = indent.block_indent(context.config);
1363 result.push_str(&arg_indent.to_string(context.config));
1364 result.push_str(&arg_str);
1366 result.push_str(&indent.to_string(context.config));
1369 result.push_str(&arg_str);
1374 if !ret_str.is_empty() {
1375 let ret_should_indent = match context.config.fn_args_layout {
1376 // If our args are block layout then we surely must have space.
1377 FnArgLayoutStyle::Block if put_args_in_block => false,
1378 FnArgLayoutStyle::BlockAlways => false,
1380 // If we've already gone multi-line, or the return type would push
1381 // over the max width, then put the return type on a new line.
1382 result.contains("\n") || multi_line_ret_str ||
1383 result.len() + indent.width() + ret_str_len > context.config.max_width
1386 let ret_indent = if ret_should_indent {
1387 let indent = match context.config.fn_return_indent {
1388 ReturnIndent::WithWhereClause => indent + 4,
1389 // Aligning with non-existent args looks silly.
1390 _ if arg_str.is_empty() => {
1391 force_new_line_for_brace = true;
1394 // FIXME: we might want to check that using the arg indent
1395 // doesn't blow our budget, and if it does, then fallback to
1396 // the where clause indent.
1401 result.push_str(&indent.to_string(context.config));
1405 Indent::new(indent.width(), result.len())
1408 if multi_line_ret_str {
1409 // Now that we know the proper indent and width, we need to
1410 // re-layout the return type.
1412 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1413 let ret_str = try_opt!(fd.output
1414 .rewrite(context, budget, ret_indent));
1415 result.push_str(&ret_str);
1417 result.push_str(&ret_str);
1420 // Comment between return type and the end of the decl.
1421 let snippet_lo = fd.output.span().hi;
1422 if where_clause.predicates.is_empty() {
1423 let snippet_hi = span.hi;
1424 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1425 let snippet = snippet.trim();
1426 if !snippet.is_empty() {
1428 result.push_str(snippet);
1431 // FIXME it would be nice to catch comments between the return type
1432 // and the where clause, but we don't have a span for the where
1437 let should_compress_where = match context.config.where_density {
1438 Density::Compressed => !result.contains('\n') || put_args_in_block,
1439 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1441 } || (put_args_in_block && ret_str.is_empty());
1443 let where_density = if should_compress_where {
1450 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1451 let where_clause_str = try_opt!(rewrite_where_clause(context,
1454 context.config.fn_brace_style,
1462 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1463 !where_clause_str.contains('\n') {
1467 result.push_str(&where_clause_str);
1469 Some((result, force_new_line_for_brace))
1472 fn rewrite_args(context: &RewriteContext,
1474 explicit_self: Option<&ast::ExplicitSelf>,
1475 one_line_budget: usize,
1476 multi_line_budget: usize,
1482 let mut arg_item_strs = try_opt!(args.iter()
1483 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1484 .collect::<Option<Vec<_>>>());
1486 // Account for sugary self.
1487 // FIXME: the comment for the self argument is dropped. This is blocked
1488 // on rust issue #27522.
1490 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1491 .map_or(1, |self_str| {
1492 arg_item_strs[0] = self_str;
1496 // Comments between args.
1497 let mut arg_items = Vec::new();
1499 arg_items.push(ListItem::from_str(""));
1502 // FIXME(#21): if there are no args, there might still be a comment, but
1503 // without spans for the comment or parens, there is no chance of
1504 // getting it right. You also don't get to put a comment on self, unless
1506 if args.len() >= min_args || variadic {
1507 let comment_span_start = if min_args == 2 {
1508 let second_arg_start = if arg_has_pattern(&args[1]) {
1513 let reduced_span = mk_sp(span.lo, second_arg_start);
1515 context.codemap.span_after_last(reduced_span, ",")
1520 enum ArgumentKind<'a> {
1521 Regular(&'a ast::Arg),
1525 let variadic_arg = if variadic {
1526 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1527 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1528 Some(ArgumentKind::Variadic(variadic_start))
1533 let more_items = itemize_list(context.codemap,
1534 args[min_args - 1..]
1536 .map(ArgumentKind::Regular)
1537 .chain(variadic_arg),
1541 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1542 ArgumentKind::Variadic(start) => start,
1547 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1548 ArgumentKind::Variadic(start) => start + BytePos(3),
1553 ArgumentKind::Regular(..) => None,
1554 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1560 arg_items.extend(more_items);
1563 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1564 item.item = Some(arg);
1567 let indent = match context.config.fn_arg_indent {
1568 BlockIndentStyle::Inherit => indent,
1569 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1570 BlockIndentStyle::Visual => arg_indent,
1573 let tactic = definitive_tactic(&arg_items,
1574 context.config.fn_args_density.to_list_tactic(),
1576 let budget = match tactic {
1577 DefinitiveListTactic::Horizontal => one_line_budget,
1578 _ => multi_line_budget,
1581 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1583 let end_with_newline = match context.config.fn_args_layout {
1584 FnArgLayoutStyle::Block |
1585 FnArgLayoutStyle::BlockAlways => true,
1589 let fmt = ListFormatting {
1592 trailing_separator: SeparatorTactic::Never,
1595 ends_with_newline: end_with_newline,
1596 config: context.config,
1599 write_list(&arg_items, &fmt)
1602 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1603 if let ast::PatKind::Ident(_,
1605 node: ast::Ident { name: ast::Name(0u32), .. },
1615 fn compute_budgets_for_args(context: &RewriteContext,
1619 newline_brace: bool)
1620 -> Option<((usize, usize, Indent))> {
1621 // Try keeping everything on the same line.
1622 if !result.contains("\n") {
1623 // 3 = `() `, space is before ret_string.
1624 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1628 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1630 if one_line_budget > 0 {
1632 let multi_line_budget =
1633 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1635 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1639 // Didn't work. we must force vertical layout and put args on a newline.
1640 let new_indent = indent.block_indent(context.config);
1641 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1642 let max_space = context.config.max_width;
1643 if used_space <= max_space {
1644 Some((0, max_space - used_space, new_indent))
1646 // Whoops! bankrupt.
1651 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1652 match config.fn_brace_style {
1653 BraceStyle::AlwaysNextLine => true,
1654 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1659 fn rewrite_generics(context: &RewriteContext,
1660 generics: &ast::Generics,
1663 generics_offset: Indent,
1666 // FIXME: convert bounds to where clauses where they get too big or if
1667 // there is a where clause at all.
1668 let lifetimes: &[_] = &generics.lifetimes;
1669 let tys: &[_] = &generics.ty_params;
1670 if lifetimes.is_empty() && tys.is_empty() {
1671 return Some(String::new());
1674 let offset = match context.config.generics_indent {
1675 BlockIndentStyle::Inherit => offset,
1676 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1678 BlockIndentStyle::Visual => generics_offset + 1,
1681 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1682 // FIXME: might need to insert a newline if the generics are really long.
1684 // Strings for the generics.
1685 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1686 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1688 // Extract comments between generics.
1689 let lt_spans = lifetimes.iter().map(|l| {
1690 let hi = if l.bounds.is_empty() {
1693 l.bounds[l.bounds.len() - 1].span.hi
1695 mk_sp(l.lifetime.span.lo, hi)
1697 let ty_spans = tys.iter().map(span_for_ty_param);
1699 let items = itemize_list(context.codemap,
1700 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1704 // FIXME: don't clone
1705 |&(_, ref str)| str.clone(),
1706 context.codemap.span_after(span, "<"),
1708 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1710 Some(format!("<{}>", list_str))
1713 fn rewrite_trait_bounds(context: &RewriteContext,
1714 type_param_bounds: &ast::TyParamBounds,
1718 let bounds: &[_] = &type_param_bounds;
1720 if bounds.is_empty() {
1721 return Some(String::new());
1724 let bound_str = bounds.iter()
1725 .filter_map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1726 .collect::<Vec<String>>()
1729 let mut result = String::new();
1730 result.push_str(": ");
1731 result.push_str(&bound_str);
1735 fn rewrite_where_clause(context: &RewriteContext,
1736 where_clause: &ast::WhereClause,
1738 brace_style: BraceStyle,
1743 allow_trailing_comma: bool,
1744 span_end: Option<BytePos>)
1746 if where_clause.predicates.is_empty() {
1747 return Some(String::new());
1750 let extra_indent = match context.config.where_indent {
1751 BlockIndentStyle::Inherit => Indent::empty(),
1752 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1755 let offset = match context.config.where_pred_indent {
1756 BlockIndentStyle::Inherit => indent + extra_indent,
1757 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1758 // 6 = "where ".len()
1759 BlockIndentStyle::Visual => indent + extra_indent + 6,
1761 // FIXME: if where_pred_indent != Visual, then the budgets below might
1762 // be out by a char or two.
1764 let budget = context.config.max_width - offset.width();
1765 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1766 // If we don't have the start of the next span, then use the end of the
1767 // predicates, but that means we miss comments.
1768 let len = where_clause.predicates.len();
1769 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1770 let span_end = span_end.unwrap_or(end_of_preds);
1771 let items = itemize_list(context.codemap,
1772 where_clause.predicates.iter(),
1774 |pred| span_for_where_pred(pred).lo,
1775 |pred| span_for_where_pred(pred).hi,
1776 |pred| pred.rewrite(&context, budget, offset),
1779 let item_vec = items.collect::<Vec<_>>();
1780 // FIXME: we don't need to collect here if the where_layout isn't
1781 // HorizontalVertical.
1782 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1783 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1785 let fmt = ListFormatting {
1788 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1791 ends_with_newline: true,
1792 config: context.config,
1794 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1796 let end_length = if terminator == "{" {
1797 // If the brace is on the next line we don't need to count it otherwise it needs two
1800 BraceStyle::AlwaysNextLine => 0,
1801 BraceStyle::PreferSameLine => 2,
1802 BraceStyle::SameLineWhere => 0,
1804 } else if terminator == "=" {
1809 if density == Density::Tall || preds_str.contains('\n') ||
1810 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1811 Some(format!("\n{}where {}",
1812 (indent + extra_indent).to_string(context.config),
1815 Some(format!(" where {}", preds_str))
1819 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> Option<String> {
1820 Some(format!("{}{}{}", try_opt!(format_visibility(vis)), item_name, ident))
1823 fn format_generics(context: &RewriteContext,
1824 generics: &ast::Generics,
1827 brace_style: BraceStyle,
1828 force_same_line_brace: bool,
1830 generics_offset: Indent,
1833 let mut result = try_opt!(rewrite_generics(context,
1836 context.config.max_width,
1840 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1841 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1842 let where_clause_str = try_opt!(rewrite_where_clause(context,
1843 &generics.where_clause,
1846 context.block_indent,
1852 result.push_str(&where_clause_str);
1853 if !force_same_line_brace &&
1854 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1856 result.push_str(&context.block_indent.to_string(context.config));
1860 result.push_str(opener);
1862 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1864 result.push_str(&context.block_indent.to_string(context.config));
1868 result.push_str(opener);