1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16 last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
17 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
18 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
19 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
20 use comment::{FindUncommented, contains_comment};
21 use visitor::FmtVisitor;
22 use rewrite::{Rewrite, RewriteContext};
23 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle};
24 use itertools::Itertools;
26 use syntax::{ast, abi, ptr, codemap};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::parse::token;
29 use syntax::ast::ImplItem;
31 // Statements of the form
32 // let pat: ty = init;
33 impl Rewrite for ast::Local {
34 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
35 let mut result = "let ".to_owned();
36 let pattern_offset = offset + result.len();
38 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
40 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
41 result.push_str(&pat_str);
43 // String that is placed within the assignment pattern and expression.
45 let mut infix = String::new();
47 if let Some(ref ty) = self.ty {
50 let indent = offset + last_line_width(&result) + 2;
51 let budget = try_opt!(width.checked_sub(indent.width() + 1));
52 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
55 infix.push_str(&rewrite);
58 if self.init.is_some() {
65 result.push_str(&infix);
67 if let Some(ref ex) = self.init {
68 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
70 // 1 = trailing semicolon;
72 try_opt!(rewrite_assign_rhs(&context, result, ex, budget, context.block_indent));
80 impl<'a> FmtVisitor<'a> {
81 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
82 let abi_str = ::utils::format_abi(fm.abi, self.config.force_explicit_abi);
83 self.buffer.push_str(&abi_str);
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(),
122 ast::Unsafety::Normal,
123 ast::Constness::NotConst,
124 ast::Defaultness::Final,
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 vis = format_visibility(&item.vis);
145 let mut_str = if is_mutable { "mut " } else { "" };
146 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
147 let offset = self.block_indent + prefix.len();
149 let width = self.config.max_width - offset.width() - 1;
150 let rewrite = ty.rewrite(&self.get_context(), width, offset);
154 self.buffer.push_str(&prefix);
155 self.buffer.push_str(&result);
156 self.buffer.push_str(";");
158 None => self.format_missing(item.span.hi),
163 self.last_pos = item.span.hi;
166 pub fn rewrite_fn(&mut self,
170 generics: &ast::Generics,
171 unsafety: ast::Unsafety,
172 constness: ast::Constness,
173 defaultness: ast::Defaultness,
175 vis: &ast::Visibility,
179 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
180 let context = self.get_context();
182 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
183 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
184 !context.config.fn_empty_single_line;
186 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
200 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
201 newline_brace = false;
202 } else if force_newline_brace {
203 newline_brace = true;
206 // Prepare for the function body by possibly adding a newline and
208 // FIXME we'll miss anything between the end of the signature and the
209 // start of the body, but we need more spans from the compiler to solve
213 result.push_str(&indent.to_string(self.config));
218 self.single_line_fn(&result, block).or_else(|| Some(result))
221 pub fn rewrite_required_fn(&mut self,
224 sig: &ast::MethodSig,
227 // Drop semicolon or it will be interpreted as comment.
228 let span = mk_sp(span.lo, span.hi - BytePos(1));
229 let context = self.get_context();
231 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
238 ast::Defaultness::Final,
240 &ast::Visibility::Inherited,
245 // Re-attach semicolon
251 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
252 if fn_str.contains('\n') {
256 let codemap = self.get_context().codemap;
258 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
259 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
260 return Some(format!("{}{{}}", fn_str));
263 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
265 if let Some(ref e) = block.expr {
266 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
268 e.rewrite(&self.get_context(),
269 self.config.max_width - self.block_indent.width(),
272 .or_else(|| Some(self.snippet(e.span)))
273 } else if let Some(ref stmt) = block.stmts.first() {
274 stmt.rewrite(&self.get_context(),
275 self.config.max_width - self.block_indent.width(),
282 if let Some(res) = rewrite {
283 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
284 if !res.contains('\n') && width <= self.config.max_width {
285 return Some(format!("{}{{ {} }}", fn_str, res));
293 pub fn visit_enum(&mut self,
295 vis: &ast::Visibility,
296 enum_def: &ast::EnumDef,
297 generics: &ast::Generics,
299 self.buffer.push_str(&format_header("enum ", ident, vis));
301 let enum_snippet = self.snippet(span);
302 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
303 let generics_str = format_generics(&self.get_context(),
307 self.config.item_brace_style,
308 enum_def.variants.is_empty(),
310 self.block_indent.block_indent(self.config),
311 mk_sp(span.lo, body_start))
313 self.buffer.push_str(&generics_str);
315 self.last_pos = body_start;
317 self.block_indent = self.block_indent.block_indent(self.config);
318 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
320 Some(ref body_str) => self.buffer.push_str(&body_str),
321 None => self.format_missing(span.hi - BytePos(1)),
323 self.block_indent = self.block_indent.block_unindent(self.config);
325 if variant_list.is_some() {
326 self.buffer.push_str(&self.block_indent.to_string(self.config));
328 self.buffer.push_str("}");
329 self.last_pos = span.hi;
332 // Format the body of an enum definition
333 fn format_variant_list(&self,
334 enum_def: &ast::EnumDef,
338 if enum_def.variants.is_empty() {
341 let mut result = String::with_capacity(1024);
343 let indentation = self.block_indent.to_string(self.config);
344 result.push_str(&indentation);
346 let items = itemize_list(self.codemap,
347 enum_def.variants.iter(),
350 if !f.node.attrs.is_empty() {
351 f.node.attrs[0].span.lo
357 |f| self.format_variant(f),
361 let budget = self.config.max_width - self.block_indent.width() - 2;
362 let fmt = ListFormatting {
363 tactic: DefinitiveListTactic::Vertical,
365 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
366 indent: self.block_indent,
368 ends_with_newline: true,
372 let list = try_opt!(write_list(items, &fmt));
373 result.push_str(&list);
378 // Variant of an enum.
379 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
380 if contains_skip(&field.node.attrs) {
381 let lo = field.node.attrs[0].span.lo;
382 let span = mk_sp(lo, field.span.hi);
383 return Some(self.snippet(span));
386 let indent = self.block_indent;
387 let mut result = try_opt!(field.node
389 .rewrite(&self.get_context(),
390 self.config.max_width - indent.width(),
392 if !result.is_empty() {
394 result.push_str(&indent.to_string(self.config));
397 let context = self.get_context();
398 let variant_body = match field.node.data {
399 ast::VariantData::Tuple(..) |
400 ast::VariantData::Struct(..) => {
401 // FIXME: Should limit the width, as we have a trailing comma
402 format_struct(&context,
405 &ast::Visibility::Inherited,
410 Some(self.config.struct_variant_width))
412 ast::VariantData::Unit(..) => {
413 let tag = if let Some(ref expr) = field.node.disr_expr {
414 format!("{} = {}", field.node.name, self.snippet(expr.span))
416 field.node.name.to_string()
420 self.config.max_width,
421 self.config.max_width - indent.width(),
426 if let Some(variant_str) = variant_body {
427 result.push_str(&variant_str);
435 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
436 if let ast::ItemKind::Impl(unsafety,
441 ref items) = item.node {
442 let mut result = String::new();
443 result.push_str(&*format_visibility(&item.vis));
444 result.push_str(format_unsafety(unsafety));
445 result.push_str("impl");
447 let lo = context.codemap.span_after(item.span, "impl");
448 let hi = match *trait_ref {
449 Some(ref tr) => tr.path.span.lo,
450 None => self_ty.span.lo,
452 let generics_str = try_opt!(rewrite_generics(context,
455 context.config.max_width,
456 offset + result.len(),
458 result.push_str(&generics_str);
460 // FIXME might need to linebreak in the impl header, here would be a
463 if polarity == ast::ImplPolarity::Negative {
464 result.push_str("!");
466 if let Some(ref trait_ref) = *trait_ref {
467 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
468 let indent = offset + result.len();
469 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
470 result.push_str(" for ");
473 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
474 let indent = offset + result.len();
475 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
477 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
478 let where_clause_str = try_opt!(rewrite_where_clause(context,
479 &generics.where_clause,
481 context.config.item_brace_style,
482 context.block_indent,
484 context.config.where_density,
489 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
490 result.push_str(&where_clause_str);
491 if where_clause_str.contains('\n') {
492 let white_space = offset.to_string(context.config);
493 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
495 result.push_str(" {}");
500 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
502 let width = context.block_indent.width() + context.config.tab_spaces - 1;
503 let where_indent = Indent::new(0, width);
504 result.push_str(&where_indent.to_string(context.config));
506 result.push_str(&where_clause_str);
508 match context.config.item_brace_style {
509 BraceStyle::AlwaysNextLine => result.push('\n'),
510 BraceStyle::PreferSameLine => result.push(' '),
511 BraceStyle::SameLineWhere => {
512 if !where_clause_str.is_empty() {
514 result.push_str(&offset.to_string(context.config));
523 let snippet = context.snippet(item.span);
524 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
526 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
527 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
528 visitor.block_indent = context.block_indent.block_indent(context.config);
529 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
532 visitor.visit_impl_item(&item);
535 visitor.format_missing(item.span.hi - BytePos(1));
537 let inner_indent_str = visitor.block_indent.to_string(context.config);
538 let outer_indent_str = context.block_indent.to_string(context.config);
541 result.push_str(&inner_indent_str);
542 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
544 result.push_str(&outer_indent_str);
547 if result.chars().last().unwrap() == '{' {
558 fn is_impl_single_line(context: &RewriteContext,
559 items: &Vec<ImplItem>,
561 where_clause_str: &str,
564 let snippet = context.snippet(item.span);
565 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
567 Some(context.config.impl_empty_single_line && items.is_empty() &&
568 result.len() + where_clause_str.len() <= context.config.max_width &&
569 !contains_comment(&snippet[open_pos..]))
572 pub fn format_struct(context: &RewriteContext,
575 vis: &ast::Visibility,
576 struct_def: &ast::VariantData,
577 generics: Option<&ast::Generics>,
580 one_line_width: Option<usize>)
583 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
584 ast::VariantData::Tuple(ref fields, _) => {
585 format_tuple_struct(context,
594 ast::VariantData::Struct(ref fields, _) => {
595 format_struct_struct(context,
608 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
609 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
611 let mut result = String::new();
612 let header = format!("{}{}trait {}",
613 format_visibility(&item.vis),
614 format_unsafety(unsafety),
617 result.push_str(&header);
619 let body_lo = context.codemap.span_after(item.span, "{");
621 let generics_str = try_opt!(rewrite_generics(context,
624 context.config.max_width,
625 offset + result.len(),
626 mk_sp(item.span.lo, body_lo)));
627 result.push_str(&generics_str);
629 let trait_bound_str = try_opt!(rewrite_trait_bounds(context,
632 context.config.max_width));
633 // If the trait, generics, and trait bound cannot fit on the same line,
634 // put the trait bounds on an indented new line
635 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
636 context.config.ideal_width {
638 let width = context.block_indent.width() + context.config.tab_spaces;
639 let trait_indent = Indent::new(0, width);
640 result.push_str(&trait_indent.to_string(context.config));
642 result.push_str(&trait_bound_str);
644 let has_body = !trait_items.is_empty();
647 if (context.config.where_density == Density::Compressed &&
648 (!result.contains('\n') ||
649 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
650 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
651 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
652 !result.contains('\n')) {
658 let where_budget = try_opt!(context.config
660 .checked_sub(last_line_width(&result)));
661 let where_clause_str = try_opt!(rewrite_where_clause(context,
662 &generics.where_clause,
664 context.config.item_brace_style,
665 context.block_indent,
671 // If the where clause cannot fit on the same line,
672 // put the where clause on a new line
673 if !where_clause_str.contains('\n') &&
674 last_line_width(&result) + where_clause_str.len() + offset.width() >
675 context.config.ideal_width {
677 let width = context.block_indent.width() + context.config.tab_spaces - 1;
678 let where_indent = Indent::new(0, width);
679 result.push_str(&where_indent.to_string(context.config));
681 result.push_str(&where_clause_str);
683 match context.config.item_brace_style {
684 BraceStyle::AlwaysNextLine => {
686 result.push_str(&offset.to_string(context.config));
688 BraceStyle::PreferSameLine => result.push(' '),
689 BraceStyle::SameLineWhere => {
690 if !where_clause_str.is_empty() &&
691 (trait_items.len() > 0 || result.contains('\n')) {
693 result.push_str(&offset.to_string(context.config));
701 let snippet = context.snippet(item.span);
702 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
704 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
705 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
706 visitor.block_indent = context.block_indent.block_indent(context.config);
707 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
709 for item in trait_items {
710 visitor.visit_trait_item(&item);
713 visitor.format_missing(item.span.hi - BytePos(1));
715 let inner_indent_str = visitor.block_indent.to_string(context.config);
716 let outer_indent_str = context.block_indent.to_string(context.config);
719 result.push_str(&inner_indent_str);
720 result.push_str(&trim_newlines(&visitor.buffer.to_string().trim()));
722 result.push_str(&outer_indent_str);
723 } else if result.contains('\n') {
734 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
735 format!("{};", format_header(item_name, ident, vis))
738 fn format_struct_struct(context: &RewriteContext,
741 vis: &ast::Visibility,
742 fields: &[ast::StructField],
743 generics: Option<&ast::Generics>,
746 one_line_width: Option<usize>)
748 let mut result = String::with_capacity(1024);
750 let header_str = format_header(item_name, ident, vis);
751 result.push_str(&header_str);
753 let body_lo = context.codemap.span_after(span, "{");
755 let generics_str = match generics {
757 try_opt!(format_generics(context,
761 context.config.item_brace_style,
764 offset + header_str.len(),
765 mk_sp(span.lo, body_lo)))
768 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
769 format!("\n{}{{", context.block_indent.to_string(context.config))
775 result.push_str(&generics_str);
777 // FIXME(#919): properly format empty structs and their comments.
778 if fields.is_empty() {
779 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
783 let item_indent = offset.block_indent(context.config);
785 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
787 let items = itemize_list(context.codemap,
791 // Include attributes and doc comments, if present
792 if !field.attrs.is_empty() {
793 field.attrs[0].span.lo
798 |field| field.ty.span.hi,
799 |field| field.rewrite(context, item_budget, item_indent),
800 context.codemap.span_after(span, "{"),
802 .collect::<Vec<_>>();
804 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
806 let tactic = match one_line_width {
807 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
808 None => DefinitiveListTactic::Vertical,
811 let fmt = ListFormatting {
814 trailing_separator: context.config.struct_trailing_comma,
817 ends_with_newline: true,
818 config: context.config,
820 let items_str = try_opt!(write_list(&items, &fmt));
821 if one_line_width.is_some() && !items_str.contains('\n') {
822 Some(format!("{} {} }}", result, items_str))
824 Some(format!("{}\n{}{}\n{}}}",
826 offset.block_indent(context.config).to_string(context.config),
828 offset.to_string(context.config)))
832 fn format_tuple_struct(context: &RewriteContext,
835 vis: &ast::Visibility,
836 fields: &[ast::StructField],
837 generics: Option<&ast::Generics>,
841 let mut result = String::with_capacity(1024);
843 let header_str = format_header(item_name, ident, vis);
844 result.push_str(&header_str);
846 // FIXME(#919): don't lose comments on empty tuple structs.
847 let body_lo = if fields.is_empty() {
853 let where_clause_str = match generics {
854 Some(ref generics) => {
855 let generics_str = try_opt!(rewrite_generics(context,
858 context.config.max_width,
859 offset + header_str.len(),
860 mk_sp(span.lo, body_lo)));
861 result.push_str(&generics_str);
863 let where_budget = try_opt!(context.config
865 .checked_sub(last_line_width(&result)));
866 try_opt!(rewrite_where_clause(context,
867 &generics.where_clause,
869 context.config.item_brace_style,
870 context.block_indent,
877 None => "".to_owned(),
881 let item_indent = context.block_indent + result.len();
883 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
885 let items = itemize_list(context.codemap,
889 // Include attributes and doc comments, if present
890 if !field.attrs.is_empty() {
891 field.attrs[0].span.lo
896 |field| field.ty.span.hi,
897 |field| field.rewrite(context, item_budget, item_indent),
898 context.codemap.span_after(span, "("),
900 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
901 result.push_str(&body);
904 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
905 (result.contains('\n') ||
906 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
907 context.config.max_width) {
908 // We need to put the where clause on a new line, but we didn'to_string
909 // know that earlier, so the where clause will not be indented properly.
911 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
912 .to_string(context.config));
914 result.push_str(&where_clause_str);
919 pub fn rewrite_type_alias(context: &RewriteContext,
923 generics: &ast::Generics,
924 vis: &ast::Visibility,
927 let mut result = String::new();
929 result.push_str(&format_visibility(&vis));
930 result.push_str("type ");
931 result.push_str(&ident.to_string());
933 let generics_indent = indent + result.len();
934 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
935 let generics_width = context.config.max_width - " =".len();
936 let generics_str = try_opt!(rewrite_generics(context,
943 result.push_str(&generics_str);
945 let where_budget = try_opt!(context.config
947 .checked_sub(last_line_width(&result)));
948 let where_clause_str = try_opt!(rewrite_where_clause(context,
949 &generics.where_clause,
951 context.config.item_brace_style,
954 context.config.where_density,
958 result.push_str(&where_clause_str);
959 result.push_str(" = ");
961 let line_width = last_line_width(&result);
962 // This checked_sub may fail as the extra space after '=' is not taken into account
963 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
964 let budget = context.config
966 .checked_sub(indent.width() + line_width + ";".len())
968 let type_indent = indent + line_width;
969 // Try to fit the type on the same line
970 let ty_str = try_opt!(ty.rewrite(context, budget, type_indent)
972 // The line was too short, try to put the type on the next line
974 // Remove the space after '='
976 let type_indent = indent.block_indent(context.config);
978 result.push_str(&type_indent.to_string(context.config));
979 let budget = try_opt!(context.config
981 .checked_sub(type_indent.width() + ";".len()));
982 ty.rewrite(context, budget, type_indent)
984 result.push_str(&ty_str);
985 result.push_str(";");
989 impl Rewrite for ast::StructField {
990 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
991 if contains_skip(&self.attrs) {
992 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
993 return wrap_str(span, context.config.max_width, width, offset);
996 let name = self.ident;
997 let vis = format_visibility(&self.vis);
998 let mut attr_str = try_opt!(self.attrs
999 .rewrite(context, context.config.max_width - offset.width(), offset));
1000 if !attr_str.is_empty() {
1001 attr_str.push('\n');
1002 attr_str.push_str(&offset.to_string(context.config));
1005 let result = match name {
1006 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
1007 None => format!("{}{}", attr_str, vis),
1010 let last_line_width = last_line_width(&result);
1011 let budget = try_opt!(width.checked_sub(last_line_width));
1012 let rewrite = try_opt!(self.ty.rewrite(context, budget, offset + last_line_width));
1013 Some(result + &rewrite)
1017 pub fn rewrite_static(prefix: &str,
1018 vis: &ast::Visibility,
1021 mutability: ast::Mutability,
1022 expr_opt: Option<&ptr::P<ast::Expr>>,
1023 context: &RewriteContext)
1025 let prefix = format!("{}{} {}{}: ",
1026 format_visibility(vis),
1028 format_mutability(mutability),
1031 let ty_str = try_opt!(ty.rewrite(context,
1032 context.config.max_width - context.block_indent.width() -
1034 context.block_indent));
1036 if let Some(ref expr) = expr_opt {
1037 let lhs = format!("{}{} =", prefix, ty_str);
1039 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
1040 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent)
1043 let lhs = format!("{}{};", prefix, ty_str);
1048 pub fn rewrite_associated_type(ident: ast::Ident,
1049 ty_opt: Option<&ptr::P<ast::Ty>>,
1050 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1051 context: &RewriteContext,
1054 let prefix = format!("type {}", ident);
1056 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1057 let bounds: &[_] = &ty_param_bounds;
1058 let bound_str = try_opt!(bounds.iter()
1059 .map(|ty_bound| ty_bound.rewrite(context, context.config.max_width, indent))
1060 .intersperse(Some(" + ".to_string()))
1061 .collect::<Option<String>>());
1062 if bounds.len() > 0 {
1063 format!(": {}", bound_str)
1071 if let Some(ty) = ty_opt {
1072 let ty_str = try_opt!(ty.rewrite(context,
1073 context.config.max_width - context.block_indent.width() -
1076 context.block_indent));
1077 Some(format!("{} = {};", prefix, ty_str))
1079 Some(format!("{}{};", prefix, type_bounds_str))
1083 impl Rewrite for ast::FunctionRetTy {
1084 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1086 ast::FunctionRetTy::Default(_) => Some(String::new()),
1087 ast::FunctionRetTy::None(_) => {
1089 Some("-> !".to_owned())
1094 ast::FunctionRetTy::Ty(ref ty) => {
1095 let inner_width = try_opt!(width.checked_sub(3));
1096 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1102 impl Rewrite for ast::Arg {
1103 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1104 if is_named_arg(self) {
1105 let mut result = try_opt!(self.pat.rewrite(context, width, offset));
1107 if self.ty.node != ast::TyKind::Infer {
1108 result.push_str(": ");
1109 let max_width = try_opt!(width.checked_sub(result.len()));
1110 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1111 result.push_str(&ty_str);
1116 self.ty.rewrite(context, width, offset)
1121 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1123 context: &RewriteContext)
1125 match explicit_self.node {
1126 ast::SelfKind::Region(lt, m) => {
1127 let mut_str = format_mutability(m);
1131 try_opt!(l.rewrite(context, usize::max_value(), Indent::empty()));
1132 Some(format!("&{} {}self", lifetime_str, mut_str))
1134 None => Some(format!("&{}self", mut_str)),
1137 ast::SelfKind::Explicit(ref ty, _) => {
1138 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1140 let mutability = explicit_self_mutability(&args[0]);
1141 let type_str = try_opt!(ty.rewrite(context, usize::max_value(), Indent::empty()));
1143 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1145 ast::SelfKind::Value(_) => {
1146 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1148 let mutability = explicit_self_mutability(&args[0]);
1150 Some(format!("{}self", format_mutability(mutability)))
1155 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1156 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1157 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1158 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1165 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1166 if is_named_arg(arg) {
1173 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1175 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1176 _ => arg.ty.span.hi,
1180 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1181 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1182 ident.node != token::keywords::Invalid.ident()
1188 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1190 ast::FunctionRetTy::None(ref span) |
1191 ast::FunctionRetTy::Default(ref span) => span.clone(),
1192 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1196 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1197 // Note that ty.span is the span for ty.ident, not the whole item.
1198 let lo = ty.span.lo;
1199 if let Some(ref def) = ty.default {
1200 return mk_sp(lo, def.span.hi);
1202 if ty.bounds.is_empty() {
1205 let hi = match ty.bounds[ty.bounds.len() - 1] {
1206 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1207 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1212 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1214 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1215 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1216 ast::WherePredicate::EqPredicate(ref p) => p.span,
1220 // Return type is (result, force_new_line_for_brace)
1221 fn rewrite_fn_base(context: &RewriteContext,
1225 generics: &ast::Generics,
1226 unsafety: ast::Unsafety,
1227 constness: ast::Constness,
1228 defaultness: ast::Defaultness,
1230 vis: &ast::Visibility,
1232 newline_brace: bool,
1234 -> Option<(String, bool)> {
1235 let mut force_new_line_for_brace = false;
1236 // FIXME we'll lose any comments in between parts of the function decl, but
1237 // anyone who comments there probably deserves what they get.
1239 let where_clause = &generics.where_clause;
1241 let mut result = String::with_capacity(1024);
1242 // Vis unsafety abi.
1243 result.push_str(&*format_visibility(vis));
1245 if let ast::Defaultness::Default = defaultness {
1246 result.push_str("default ");
1249 if let ast::Constness::Const = constness {
1250 result.push_str("const ");
1253 result.push_str(::utils::format_unsafety(unsafety));
1255 if abi != abi::Abi::Rust {
1256 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1260 result.push_str("fn ");
1261 result.push_str(&ident.to_string());
1264 let generics_indent = indent + result.len();
1265 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1266 let generics_str = try_opt!(rewrite_generics(context,
1269 context.config.max_width,
1272 result.push_str(&generics_str);
1274 // Note that if the width and indent really matter, we'll re-layout the
1275 // return type later anyway.
1276 let ret_str = try_opt!(fd.output
1277 .rewrite(&context, context.config.max_width - indent.width(), indent));
1279 let multi_line_ret_str = ret_str.contains('\n');
1280 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1283 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1284 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1286 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1287 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1288 arg_indent = indent.block_indent(context.config);
1289 multi_line_budget = context.config.max_width - arg_indent.width();
1292 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1297 // Check if vertical layout was forced by compute_budget_for_args.
1298 if one_line_budget == 0 {
1299 if context.config.fn_args_paren_newline {
1301 result.push_str(&arg_indent.to_string(context.config));
1302 arg_indent = arg_indent + 1; // extra space for `(`
1305 result.push_str("(\n");
1306 result.push_str(&arg_indent.to_string(context.config));
1312 if multi_line_ret_str {
1313 one_line_budget = 0;
1316 // A conservative estimation, to goal is to be over all parens in generics
1317 let args_start = generics.ty_params
1319 .map_or(span.lo, |tp| end_typaram(tp));
1320 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1321 span_for_return(&fd.output).lo);
1322 let arg_str = try_opt!(rewrite_args(context,
1324 fd.get_self().as_ref(),
1332 let multi_line_arg_str = arg_str.contains('\n');
1334 let put_args_in_block = match context.config.fn_args_layout {
1335 FnArgLayoutStyle::Block => multi_line_arg_str,
1336 FnArgLayoutStyle::BlockAlways => true,
1338 } && fd.inputs.len() > 0;
1340 if put_args_in_block {
1341 arg_indent = indent.block_indent(context.config);
1343 result.push_str(&arg_indent.to_string(context.config));
1344 result.push_str(&arg_str);
1346 result.push_str(&indent.to_string(context.config));
1349 result.push_str(&arg_str);
1354 if !ret_str.is_empty() {
1355 let ret_should_indent = match context.config.fn_args_layout {
1356 // If our args are block layout then we surely must have space.
1357 FnArgLayoutStyle::Block if put_args_in_block => false,
1358 FnArgLayoutStyle::BlockAlways => false,
1360 // If we've already gone multi-line, or the return type would push
1361 // over the max width, then put the return type on a new line.
1362 result.contains("\n") || multi_line_ret_str ||
1363 result.len() + indent.width() + ret_str_len > context.config.max_width
1366 let ret_indent = if ret_should_indent {
1367 let indent = match context.config.fn_return_indent {
1368 ReturnIndent::WithWhereClause => indent + 4,
1369 // Aligning with non-existent args looks silly.
1370 _ if arg_str.is_empty() => {
1371 force_new_line_for_brace = true;
1374 // FIXME: we might want to check that using the arg indent
1375 // doesn't blow our budget, and if it does, then fallback to
1376 // the where clause indent.
1381 result.push_str(&indent.to_string(context.config));
1385 Indent::new(indent.width(), result.len())
1388 if multi_line_ret_str {
1389 // Now that we know the proper indent and width, we need to
1390 // re-layout the return type.
1392 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1393 let ret_str = try_opt!(fd.output
1394 .rewrite(context, budget, ret_indent));
1395 result.push_str(&ret_str);
1397 result.push_str(&ret_str);
1400 // Comment between return type and the end of the decl.
1401 let snippet_lo = fd.output.span().hi;
1402 if where_clause.predicates.is_empty() {
1403 let snippet_hi = span.hi;
1404 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1405 let snippet = snippet.trim();
1406 if !snippet.is_empty() {
1408 result.push_str(snippet);
1411 // FIXME it would be nice to catch comments between the return type
1412 // and the where clause, but we don't have a span for the where
1417 let should_compress_where = match context.config.where_density {
1418 Density::Compressed => !result.contains('\n') || put_args_in_block,
1419 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1421 } || (put_args_in_block && ret_str.is_empty());
1423 let where_density = if should_compress_where {
1430 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1431 let where_clause_str = try_opt!(rewrite_where_clause(context,
1434 context.config.fn_brace_style,
1442 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1443 !where_clause_str.contains('\n') {
1447 result.push_str(&where_clause_str);
1449 Some((result, force_new_line_for_brace))
1452 fn rewrite_args(context: &RewriteContext,
1454 explicit_self: Option<&ast::ExplicitSelf>,
1455 one_line_budget: usize,
1456 multi_line_budget: usize,
1462 let mut arg_item_strs = try_opt!(args.iter()
1463 .map(|arg| arg.rewrite(&context, multi_line_budget, arg_indent))
1464 .collect::<Option<Vec<_>>>());
1466 // Account for sugary self.
1467 // FIXME: the comment for the self argument is dropped. This is blocked
1468 // on rust issue #27522.
1470 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1471 .map_or(1, |self_str| {
1472 arg_item_strs[0] = self_str;
1476 // Comments between args.
1477 let mut arg_items = Vec::new();
1479 arg_items.push(ListItem::from_str(""));
1482 // FIXME(#21): if there are no args, there might still be a comment, but
1483 // without spans for the comment or parens, there is no chance of
1484 // getting it right. You also don't get to put a comment on self, unless
1486 if args.len() >= min_args || variadic {
1487 let comment_span_start = if min_args == 2 {
1488 let second_arg_start = if arg_has_pattern(&args[1]) {
1493 let reduced_span = mk_sp(span.lo, second_arg_start);
1495 context.codemap.span_after_last(reduced_span, ",")
1500 enum ArgumentKind<'a> {
1501 Regular(&'a ast::Arg),
1505 let variadic_arg = if variadic {
1506 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1507 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1508 Some(ArgumentKind::Variadic(variadic_start))
1513 let more_items = itemize_list(context.codemap,
1514 args[min_args - 1..]
1516 .map(ArgumentKind::Regular)
1517 .chain(variadic_arg),
1521 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1522 ArgumentKind::Variadic(start) => start,
1527 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1528 ArgumentKind::Variadic(start) => start + BytePos(3),
1533 ArgumentKind::Regular(..) => None,
1534 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1540 arg_items.extend(more_items);
1543 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1544 item.item = Some(arg);
1547 let indent = match context.config.fn_arg_indent {
1548 BlockIndentStyle::Inherit => indent,
1549 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1550 BlockIndentStyle::Visual => arg_indent,
1553 let tactic = definitive_tactic(&arg_items,
1554 context.config.fn_args_density.to_list_tactic(),
1556 let budget = match tactic {
1557 DefinitiveListTactic::Horizontal => one_line_budget,
1558 _ => multi_line_budget,
1561 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1563 let end_with_newline = match context.config.fn_args_layout {
1564 FnArgLayoutStyle::Block |
1565 FnArgLayoutStyle::BlockAlways => true,
1569 let fmt = ListFormatting {
1572 trailing_separator: SeparatorTactic::Never,
1575 ends_with_newline: end_with_newline,
1576 config: context.config,
1579 write_list(&arg_items, &fmt)
1582 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1583 if let ast::PatKind::Ident(_,
1585 node: ast::Ident { name: ast::Name(0u32), .. },
1595 fn compute_budgets_for_args(context: &RewriteContext,
1599 newline_brace: bool)
1600 -> Option<((usize, usize, Indent))> {
1601 // Try keeping everything on the same line.
1602 if !result.contains("\n") {
1603 // 3 = `() `, space is before ret_string.
1604 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1608 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1610 if one_line_budget > 0 {
1612 let multi_line_budget =
1613 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1615 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1619 // Didn't work. we must force vertical layout and put args on a newline.
1620 let new_indent = indent.block_indent(context.config);
1621 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1622 let max_space = context.config.max_width;
1623 if used_space <= max_space {
1624 Some((0, max_space - used_space, new_indent))
1626 // Whoops! bankrupt.
1631 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1632 match config.fn_brace_style {
1633 BraceStyle::AlwaysNextLine => true,
1634 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1639 fn rewrite_generics(context: &RewriteContext,
1640 generics: &ast::Generics,
1643 generics_offset: Indent,
1646 // FIXME: convert bounds to where clauses where they get too big or if
1647 // there is a where clause at all.
1648 let lifetimes: &[_] = &generics.lifetimes;
1649 let tys: &[_] = &generics.ty_params;
1650 if lifetimes.is_empty() && tys.is_empty() {
1651 return Some(String::new());
1654 let offset = match context.config.generics_indent {
1655 BlockIndentStyle::Inherit => offset,
1656 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1658 BlockIndentStyle::Visual => generics_offset + 1,
1661 let h_budget = try_opt!(width.checked_sub(generics_offset.width() + 2));
1662 // FIXME: might need to insert a newline if the generics are really long.
1664 // Strings for the generics.
1665 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1666 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1668 // Extract comments between generics.
1669 let lt_spans = lifetimes.iter().map(|l| {
1670 let hi = if l.bounds.is_empty() {
1673 l.bounds[l.bounds.len() - 1].span.hi
1675 mk_sp(l.lifetime.span.lo, hi)
1677 let ty_spans = tys.iter().map(span_for_ty_param);
1679 let items = itemize_list(context.codemap,
1680 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1684 // FIXME: don't clone
1685 |&(_, ref str)| str.clone(),
1686 context.codemap.span_after(span, "<"),
1688 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1690 Some(format!("<{}>", list_str))
1693 fn rewrite_trait_bounds(context: &RewriteContext,
1694 type_param_bounds: &ast::TyParamBounds,
1698 let bounds: &[_] = &type_param_bounds;
1700 if bounds.is_empty() {
1701 return Some(String::new());
1704 let bound_str = try_opt!(bounds.iter()
1705 .map(|ty_bound| ty_bound.rewrite(&context, width, indent))
1706 .intersperse(Some(" + ".to_string()))
1707 .collect::<Option<String>>());
1709 let mut result = String::new();
1710 result.push_str(": ");
1711 result.push_str(&bound_str);
1715 fn rewrite_where_clause(context: &RewriteContext,
1716 where_clause: &ast::WhereClause,
1718 brace_style: BraceStyle,
1723 allow_trailing_comma: bool,
1724 span_end: Option<BytePos>)
1726 if where_clause.predicates.is_empty() {
1727 return Some(String::new());
1730 let extra_indent = match context.config.where_indent {
1731 BlockIndentStyle::Inherit => Indent::empty(),
1732 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1735 let offset = match context.config.where_pred_indent {
1736 BlockIndentStyle::Inherit => indent + extra_indent,
1737 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1738 // 6 = "where ".len()
1739 BlockIndentStyle::Visual => indent + extra_indent + 6,
1741 // FIXME: if where_pred_indent != Visual, then the budgets below might
1742 // be out by a char or two.
1744 let budget = context.config.max_width - offset.width();
1745 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1746 // If we don't have the start of the next span, then use the end of the
1747 // predicates, but that means we miss comments.
1748 let len = where_clause.predicates.len();
1749 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1750 let span_end = span_end.unwrap_or(end_of_preds);
1751 let items = itemize_list(context.codemap,
1752 where_clause.predicates.iter(),
1754 |pred| span_for_where_pred(pred).lo,
1755 |pred| span_for_where_pred(pred).hi,
1756 |pred| pred.rewrite(&context, budget, offset),
1759 let item_vec = items.collect::<Vec<_>>();
1760 // FIXME: we don't need to collect here if the where_layout isn't
1761 // HorizontalVertical.
1762 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1763 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1765 let fmt = ListFormatting {
1768 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1771 ends_with_newline: true,
1772 config: context.config,
1774 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1776 let end_length = if terminator == "{" {
1777 // If the brace is on the next line we don't need to count it otherwise it needs two
1780 BraceStyle::AlwaysNextLine => 0,
1781 BraceStyle::PreferSameLine => 2,
1782 BraceStyle::SameLineWhere => 0,
1784 } else if terminator == "=" {
1789 if density == Density::Tall || preds_str.contains('\n') ||
1790 indent.width() + " where ".len() + preds_str.len() + end_length > width {
1791 Some(format!("\n{}where {}",
1792 (indent + extra_indent).to_string(context.config),
1795 Some(format!(" where {}", preds_str))
1799 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1800 format!("{}{}{}", format_visibility(vis), item_name, ident)
1803 fn format_generics(context: &RewriteContext,
1804 generics: &ast::Generics,
1807 brace_style: BraceStyle,
1808 force_same_line_brace: bool,
1810 generics_offset: Indent,
1813 let mut result = try_opt!(rewrite_generics(context,
1816 context.config.max_width,
1820 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1821 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1822 let where_clause_str = try_opt!(rewrite_where_clause(context,
1823 &generics.where_clause,
1826 context.block_indent,
1832 result.push_str(&where_clause_str);
1833 if !force_same_line_brace &&
1834 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1836 result.push_str(&context.block_indent.to_string(context.config));
1840 result.push_str(opener);
1842 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1844 result.push_str(&context.block_indent.to_string(context.config));
1848 result.push_str(opener);