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, format_unsafety, trim_newlines, stmt_expr, semicolon_for_expr};
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, type_annotation_separator};
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, codemap, ptr, symbol};
27 use syntax::codemap::{Span, BytePos, mk_sp};
28 use syntax::ast::ImplItem;
30 // Statements of the form
31 // let pat: ty = init;
32 impl Rewrite for ast::Local {
33 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
34 debug!("Local::rewrite {:?} {} {:?}",
38 let mut result = "let ".to_owned();
39 let pattern_offset = shape.indent + result.len();
41 let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
43 let pat_str = try_opt!(self.pat
45 Shape::legacy(pattern_width, pattern_offset)));
46 result.push_str(&pat_str);
48 // String that is placed within the assignment pattern and expression.
50 let mut infix = String::new();
52 if let Some(ref ty) = self.ty {
53 let separator = type_annotation_separator(context.config);
54 let indent = shape.indent + last_line_width(&result) + separator.len();
56 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
57 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
59 infix.push_str(separator);
60 infix.push_str(&rewrite);
63 if self.init.is_some() {
70 result.push_str(&infix);
72 if let Some(ref ex) = self.init {
73 // 1 = trailing semicolon;
74 let budget = try_opt!(shape.width.checked_sub(shape.indent.block_only().width() + 1));
76 result = try_opt!(rewrite_assign_rhs(&context,
79 Shape::legacy(budget, shape.indent.block_only())));
87 // TODO convert to using rewrite style rather than visitor
88 // TODO format modules in this style
91 keyword: &'static str,
93 vis: Option<&'a ast::Visibility>,
94 body: Vec<BodyElement<'a>>,
99 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
100 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi {
103 format!("extern {}", fm.abi)
109 body: fm.items.iter().map(|i| BodyElement::ForeignItem(i)).collect(),
115 enum BodyElement<'a> {
116 // Stmt(&'a ast::Stmt),
117 // Field(&'a ast::Field),
118 // Variant(&'a ast::Variant),
119 // Item(&'a ast::Item),
120 ForeignItem(&'a ast::ForeignItem),
123 impl<'a> FmtVisitor<'a> {
124 fn format_item(&mut self, item: Item) {
125 self.buffer.push_str(&item.abi);
126 self.buffer.push_str(" ");
128 let snippet = self.snippet(item.span);
129 let brace_pos = snippet.find_uncommented("{").unwrap();
131 self.buffer.push_str("{");
132 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
133 // FIXME: this skips comments between the extern keyword and the opening
135 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
136 self.block_indent = self.block_indent.block_indent(self.config);
138 if item.body.is_empty() {
139 self.format_missing_no_indent(item.span.hi - BytePos(1));
140 self.block_indent = self.block_indent.block_unindent(self.config);
142 self.buffer.push_str(&self.block_indent.to_string(self.config));
144 for item in &item.body {
145 self.format_body_element(item);
148 self.block_indent = self.block_indent.block_unindent(self.config);
149 self.format_missing_with_indent(item.span.hi - BytePos(1));
153 self.buffer.push_str("}");
154 self.last_pos = item.span.hi;
157 fn format_body_element(&mut self, element: &BodyElement) {
159 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
163 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
164 let item = Item::from_foreign_mod(fm, span, self.config);
165 self.format_item(item);
168 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
169 self.format_missing_with_indent(item.span.lo);
170 // Drop semicolon or it will be interpreted as comment.
171 // FIXME: this may be a faulty span from libsyntax.
172 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
175 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
176 let indent = self.block_indent;
177 let rewrite = rewrite_fn_base(&self.get_context(),
182 ast::Unsafety::Normal,
183 ast::Constness::NotConst,
184 ast::Defaultness::Final,
185 // These are not actually rust functions,
186 // but we format them as such.
194 Some((new_fn, _)) => {
195 self.buffer.push_str(&new_fn);
196 self.buffer.push_str(";");
198 None => self.format_missing(item.span.hi),
201 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
202 // FIXME(#21): we're dropping potential comments in between the
203 // function keywords here.
204 let vis = format_visibility(&item.vis);
205 let mut_str = if is_mutable { "mut " } else { "" };
206 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
207 let offset = self.block_indent + prefix.len();
209 let width = self.config.max_width - offset.width() - 1;
210 let rewrite = ty.rewrite(&self.get_context(), Shape::legacy(width, offset));
214 self.buffer.push_str(&prefix);
215 self.buffer.push_str(&result);
216 self.buffer.push_str(";");
218 None => self.format_missing(item.span.hi),
223 self.last_pos = item.span.hi;
226 pub fn rewrite_fn(&mut self,
230 generics: &ast::Generics,
231 unsafety: ast::Unsafety,
232 constness: ast::Constness,
233 defaultness: ast::Defaultness,
235 vis: &ast::Visibility,
239 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
240 let context = self.get_context();
242 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
243 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
244 !context.config.fn_empty_single_line;
246 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
260 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
261 newline_brace = false;
262 } else if force_newline_brace {
263 newline_brace = true;
266 // Prepare for the function body by possibly adding a newline and
268 // FIXME we'll miss anything between the end of the signature and the
269 // start of the body, but we need more spans from the compiler to solve
273 result.push_str(&indent.to_string(self.config));
278 self.single_line_fn(&result, block).or_else(|| Some(result))
281 pub fn rewrite_required_fn(&mut self,
284 sig: &ast::MethodSig,
287 // Drop semicolon or it will be interpreted as comment.
288 let span = mk_sp(span.lo, span.hi - BytePos(1));
289 let context = self.get_context();
291 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
298 ast::Defaultness::Final,
300 &ast::Visibility::Inherited,
305 // Re-attach semicolon
311 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
312 if fn_str.contains('\n') {
316 let codemap = self.get_context().codemap;
318 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
319 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
320 return Some(format!("{}{{}}", fn_str));
323 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
325 if let Some(ref stmt) = block.stmts.first() {
326 match stmt_expr(stmt) {
328 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
330 e.rewrite(&self.get_context(),
331 Shape::legacy(self.config.max_width -
332 self.block_indent.width(),
335 .or_else(|| Some(self.snippet(e.span)))
338 stmt.rewrite(&self.get_context(),
339 Shape::legacy(self.config.max_width -
340 self.block_indent.width(),
349 if let Some(res) = rewrite {
350 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
351 if !res.contains('\n') && width <= self.config.max_width {
352 return Some(format!("{}{{ {} }}", fn_str, res));
360 pub fn visit_enum(&mut self,
362 vis: &ast::Visibility,
363 enum_def: &ast::EnumDef,
364 generics: &ast::Generics,
366 self.buffer.push_str(&format_header("enum ", ident, vis));
368 let enum_snippet = self.snippet(span);
369 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
370 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
371 let generics_str = format_generics(&self.get_context(),
375 self.config.item_brace_style,
376 enum_def.variants.is_empty(),
378 self.block_indent.block_indent(self.config),
379 mk_sp(span.lo, body_start))
381 self.buffer.push_str(&generics_str);
383 self.last_pos = body_start;
385 self.block_indent = self.block_indent.block_indent(self.config);
386 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
388 Some(ref body_str) => self.buffer.push_str(body_str),
390 if contains_comment(&enum_snippet[brace_pos..]) {
391 self.format_missing_no_indent(span.hi - BytePos(1))
393 self.format_missing(span.hi - BytePos(1))
397 self.block_indent = self.block_indent.block_unindent(self.config);
399 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
400 self.buffer.push_str(&self.block_indent.to_string(self.config));
402 self.buffer.push_str("}");
403 self.last_pos = span.hi;
406 // Format the body of an enum definition
407 fn format_variant_list(&self,
408 enum_def: &ast::EnumDef,
412 if enum_def.variants.is_empty() {
415 let mut result = String::with_capacity(1024);
417 let indentation = self.block_indent.to_string(self.config);
418 result.push_str(&indentation);
420 let items = itemize_list(self.codemap,
421 enum_def.variants.iter(),
423 |f| if !f.node.attrs.is_empty() {
424 f.node.attrs[0].span.lo
429 |f| self.format_variant(f),
433 let budget = self.config.max_width - self.block_indent.width() - 2;
434 let fmt = ListFormatting {
435 tactic: DefinitiveListTactic::Vertical,
437 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
438 shape: Shape::legacy(budget, self.block_indent),
439 ends_with_newline: true,
443 let list = try_opt!(write_list(items, &fmt));
444 result.push_str(&list);
449 // Variant of an enum.
450 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
451 if contains_skip(&field.node.attrs) {
452 let lo = field.node.attrs[0].span.lo;
453 let span = mk_sp(lo, field.span.hi);
454 return Some(self.snippet(span));
457 let indent = self.block_indent;
458 let mut result = try_opt!(field.node
460 .rewrite(&self.get_context(),
461 Shape::legacy(self.config.max_width -
464 if !result.is_empty() {
466 result.push_str(&indent.to_string(self.config));
469 let context = self.get_context();
470 let variant_body = match field.node.data {
471 ast::VariantData::Tuple(..) |
472 ast::VariantData::Struct(..) => {
473 // FIXME: Should limit the width, as we have a trailing comma
474 format_struct(&context,
477 &ast::Visibility::Inherited,
482 Some(self.config.struct_variant_width))
484 ast::VariantData::Unit(..) => {
485 let tag = if let Some(ref expr) = field.node.disr_expr {
486 format!("{} = {}", field.node.name, self.snippet(expr.span))
488 field.node.name.to_string()
492 self.config.max_width,
493 Shape::legacy(self.config.max_width - indent.width(), indent))
497 if let Some(variant_str) = variant_body {
498 result.push_str(&variant_str);
506 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
507 if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
508 let mut result = String::new();
509 // First try to format the ref and type without a split at the 'for'.
510 let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
512 // If there is a line break present in the first result format it again
513 // with a split at the 'for'. Skip this if there is no trait ref and
514 // therefore no 'for'.
515 if ref_and_type.contains('\n') && trait_ref.is_some() {
516 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
518 result.push_str(&ref_and_type);
520 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
521 let where_clause_str = try_opt!(rewrite_where_clause(context,
522 &generics.where_clause,
524 context.config.item_brace_style,
525 Shape::legacy(where_budget,
526 offset.block_only()),
527 context.config.where_density,
532 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
533 result.push_str(&where_clause_str);
534 if where_clause_str.contains('\n') {
535 let white_space = offset.to_string(context.config);
536 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
538 result.push_str(" {}");
543 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
545 let width = offset.block_indent + context.config.tab_spaces - 1;
546 let where_indent = Indent::new(0, width);
547 result.push_str(&where_indent.to_string(context.config));
549 result.push_str(&where_clause_str);
551 match context.config.item_brace_style {
552 BraceStyle::AlwaysNextLine => {
554 result.push_str(&offset.to_string(context.config));
556 BraceStyle::PreferSameLine => result.push(' '),
557 BraceStyle::SameLineWhere => {
558 if !where_clause_str.is_empty() {
560 result.push_str(&offset.to_string(context.config));
569 let snippet = context.snippet(item.span);
570 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
572 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
573 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
574 visitor.block_indent = offset.block_only().block_indent(context.config);
575 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
578 visitor.visit_impl_item(item);
581 visitor.format_missing(item.span.hi - BytePos(1));
583 let inner_indent_str = visitor.block_indent.to_string(context.config);
584 let outer_indent_str = offset.block_only().to_string(context.config);
587 result.push_str(&inner_indent_str);
588 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
590 result.push_str(&outer_indent_str);
593 if result.chars().last().unwrap() == '{' {
595 result.push_str(&offset.to_string(context.config));
605 fn is_impl_single_line(context: &RewriteContext,
608 where_clause_str: &str,
611 let snippet = context.snippet(item.span);
612 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
614 Some(context.config.impl_empty_single_line && items.is_empty() &&
615 result.len() + where_clause_str.len() <= context.config.max_width &&
616 !contains_comment(&snippet[open_pos..]))
619 fn format_impl_ref_and_type(context: &RewriteContext,
624 if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
626 let mut result = String::new();
628 result.push_str(&*format_visibility(&item.vis));
629 result.push_str(format_unsafety(unsafety));
630 result.push_str("impl");
632 let lo = context.codemap.span_after(item.span, "impl");
633 let hi = match *trait_ref {
634 Some(ref tr) => tr.path.span.lo,
635 None => self_ty.span.lo,
637 let generics_str = try_opt!(rewrite_generics(context,
639 Shape::legacy(context.config.max_width,
641 offset + result.len(),
643 result.push_str(&generics_str);
645 if polarity == ast::ImplPolarity::Negative {
646 result.push_str(" !");
648 if let Some(ref trait_ref) = *trait_ref {
649 if polarity != ast::ImplPolarity::Negative {
650 result.push_str(" ");
652 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
653 let indent = offset + result.len();
654 result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
659 // Add indentation of one additional tab.
660 let width = offset.block_indent + context.config.tab_spaces;
661 let for_indent = Indent::new(0, width);
662 result.push_str(&for_indent.to_string(context.config));
664 result.push_str("for");
666 result.push_str(" for");
670 let mut used_space = last_line_width(&result);
671 if generics.where_clause.predicates.is_empty() {
672 // If there is no where clause adapt budget for type formatting to take space and curly
673 // brace into account.
674 match context.config.item_brace_style {
675 BraceStyle::AlwaysNextLine => {}
676 BraceStyle::PreferSameLine => used_space += 2,
677 BraceStyle::SameLineWhere => used_space += 2,
681 // 1 = space before the type.
682 let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1));
683 let indent = offset + result.len() + 1;
684 let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
685 if let Some(self_ty_str) = self_ty_str {
686 result.push_str(" ");
687 result.push_str(&self_ty_str);
691 // Can't fit the self type on what's left of the line, so start a new one.
692 let indent = offset.block_indent(context.config);
693 result.push_str(&format!("\n{}", indent.to_string(context.config)));
694 let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
695 result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
702 pub fn format_struct(context: &RewriteContext,
705 vis: &ast::Visibility,
706 struct_def: &ast::VariantData,
707 generics: Option<&ast::Generics>,
710 one_line_width: Option<usize>)
713 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
714 ast::VariantData::Tuple(ref fields, _) => {
715 format_tuple_struct(context,
724 ast::VariantData::Struct(ref fields, _) => {
725 format_struct_struct(context,
738 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
739 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
741 let mut result = String::new();
742 let header = format!("{}{}trait {}",
743 format_visibility(&item.vis),
744 format_unsafety(unsafety),
747 result.push_str(&header);
749 let body_lo = context.codemap.span_after(item.span, "{");
751 let generics_str = try_opt!(rewrite_generics(context,
753 Shape::legacy(context.config.max_width,
755 offset + result.len(),
756 mk_sp(item.span.lo, body_lo)));
757 result.push_str(&generics_str);
759 let trait_bound_str =
760 try_opt!(rewrite_trait_bounds(context,
762 Shape::legacy(context.config.max_width, offset)));
763 // If the trait, generics, and trait bound cannot fit on the same line,
764 // put the trait bounds on an indented new line
765 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
766 context.config.ideal_width {
768 let trait_indent = offset.block_only().block_indent(context.config);
769 result.push_str(&trait_indent.to_string(context.config));
771 result.push_str(&trait_bound_str);
773 let has_body = !trait_items.is_empty();
776 if (context.config.where_density == Density::Compressed &&
777 (!result.contains('\n') ||
778 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
779 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
780 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
781 !result.contains('\n')) {
787 let where_budget = try_opt!(context.config
789 .checked_sub(last_line_width(&result)));
790 let where_clause_str = try_opt!(rewrite_where_clause(context,
791 &generics.where_clause,
793 context.config.item_brace_style,
794 Shape::legacy(where_budget,
795 offset.block_only()),
800 // If the where clause cannot fit on the same line,
801 // put the where clause on a new line
802 if !where_clause_str.contains('\n') &&
803 last_line_width(&result) + where_clause_str.len() + offset.width() >
804 context.config.ideal_width {
806 let width = offset.block_indent + context.config.tab_spaces - 1;
807 let where_indent = Indent::new(0, width);
808 result.push_str(&where_indent.to_string(context.config));
810 result.push_str(&where_clause_str);
812 match context.config.item_brace_style {
813 BraceStyle::AlwaysNextLine => {
815 result.push_str(&offset.to_string(context.config));
817 BraceStyle::PreferSameLine => result.push(' '),
818 BraceStyle::SameLineWhere => {
819 if !where_clause_str.is_empty() &&
820 (!trait_items.is_empty() || result.contains('\n')) {
822 result.push_str(&offset.to_string(context.config));
830 let snippet = context.snippet(item.span);
831 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
833 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
834 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
835 visitor.block_indent = offset.block_only().block_indent(context.config);
836 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
838 for item in trait_items {
839 visitor.visit_trait_item(item);
842 visitor.format_missing(item.span.hi - BytePos(1));
844 let inner_indent_str = visitor.block_indent.to_string(context.config);
845 let outer_indent_str = offset.block_only().to_string(context.config);
848 result.push_str(&inner_indent_str);
849 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
851 result.push_str(&outer_indent_str);
852 } else if result.contains('\n') {
863 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
864 format!("{};", format_header(item_name, ident, vis))
867 fn format_struct_struct(context: &RewriteContext,
870 vis: &ast::Visibility,
871 fields: &[ast::StructField],
872 generics: Option<&ast::Generics>,
875 one_line_width: Option<usize>)
877 let mut result = String::with_capacity(1024);
879 let header_str = format_header(item_name, ident, vis);
880 result.push_str(&header_str);
882 let body_lo = context.codemap.span_after(span, "{");
884 let generics_str = match generics {
886 try_opt!(format_generics(context,
890 context.config.item_brace_style,
893 offset + header_str.len(),
894 mk_sp(span.lo, body_lo)))
897 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
898 format!("\n{}{{", offset.block_only().to_string(context.config))
904 result.push_str(&generics_str);
906 // FIXME(#919): properly format empty structs and their comments.
907 if fields.is_empty() {
908 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
909 if snippet.trim().is_empty() {
911 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
913 result.push_str(&snippet.trim_right());
915 result.push_str(&offset.to_string(context.config));
917 result.push_str(&snippet);
923 let item_indent = offset.block_indent(context.config);
925 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
928 itemize_list(context.codemap,
932 // Include attributes and doc comments, if present
933 if !field.attrs.is_empty() {
934 field.attrs[0].span.lo
939 |field| field.ty.span.hi,
940 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
941 context.codemap.span_after(span, "{"),
943 .collect::<Vec<_>>();
945 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
947 let tactic = match one_line_width {
948 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
949 None => DefinitiveListTactic::Vertical,
952 let fmt = ListFormatting {
955 trailing_separator: context.config.struct_trailing_comma,
956 shape: Shape::legacy(budget, item_indent),
957 ends_with_newline: true,
958 config: context.config,
960 let items_str = try_opt!(write_list(&items, &fmt));
961 if one_line_width.is_some() && !items_str.contains('\n') {
962 Some(format!("{} {} }}", result, items_str))
964 Some(format!("{}\n{}{}\n{}}}",
966 offset.block_indent(context.config).to_string(context.config),
968 offset.to_string(context.config)))
972 fn format_tuple_struct(context: &RewriteContext,
975 vis: &ast::Visibility,
976 fields: &[ast::StructField],
977 generics: Option<&ast::Generics>,
981 let mut result = String::with_capacity(1024);
983 let header_str = format_header(item_name, ident, vis);
984 result.push_str(&header_str);
986 // FIXME(#919): don't lose comments on empty tuple structs.
987 let body_lo = if fields.is_empty() {
993 let where_clause_str = match generics {
995 let generics_str = try_opt!(rewrite_generics(context,
997 Shape::legacy(context.config.max_width,
999 offset + header_str.len(),
1000 mk_sp(span.lo, body_lo)));
1001 result.push_str(&generics_str);
1003 let where_budget = try_opt!(context.config
1005 .checked_sub(last_line_width(&result)));
1006 try_opt!(rewrite_where_clause(context,
1007 &generics.where_clause,
1009 context.config.item_brace_style,
1010 Shape::legacy(where_budget, offset.block_only()),
1011 Density::Compressed,
1016 None => "".to_owned(),
1020 let item_indent = offset.block_only() + result.len();
1022 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
1025 itemize_list(context.codemap,
1029 // Include attributes and doc comments, if present
1030 if !field.attrs.is_empty() {
1031 field.attrs[0].span.lo
1036 |field| field.ty.span.hi,
1037 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1038 context.codemap.span_after(span, "("),
1040 let body = try_opt!(format_item_list(items,
1041 Shape::legacy(item_budget, item_indent),
1044 if context.config.spaces_within_parens && body.len() > 0 {
1048 result.push_str(&body);
1050 if context.config.spaces_within_parens && body.len() > 0 {
1056 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1057 (result.contains('\n') ||
1058 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1059 context.config.max_width) {
1060 // We need to put the where clause on a new line, but we didn'to_string
1061 // know that earlier, so the where clause will not be indented properly.
1063 result.push_str(&(offset.block_only() + (context.config.tab_spaces - 1))
1064 .to_string(context.config));
1066 result.push_str(&where_clause_str);
1071 pub fn rewrite_type_alias(context: &RewriteContext,
1075 generics: &ast::Generics,
1076 vis: &ast::Visibility,
1079 let mut result = String::new();
1081 result.push_str(&format_visibility(vis));
1082 result.push_str("type ");
1083 result.push_str(&ident.to_string());
1085 let generics_indent = indent + result.len();
1086 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1087 let generics_width = context.config.max_width - " =".len();
1088 let generics_str = try_opt!(rewrite_generics(context,
1090 Shape::legacy(generics_width, indent),
1094 result.push_str(&generics_str);
1096 let where_budget = try_opt!(context.config
1098 .checked_sub(last_line_width(&result)));
1099 let where_clause_str = try_opt!(rewrite_where_clause(context,
1100 &generics.where_clause,
1102 context.config.item_brace_style,
1103 Shape::legacy(where_budget, indent),
1104 context.config.where_density,
1108 result.push_str(&where_clause_str);
1109 result.push_str(" = ");
1111 let line_width = last_line_width(&result);
1112 // This checked_sub may fail as the extra space after '=' is not taken into account
1113 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1114 let budget = context.config
1116 .checked_sub(indent.width() + line_width + ";".len())
1118 let type_indent = indent + line_width;
1119 // Try to fit the type on the same line
1120 let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
1122 // The line was too short, try to put the type on the next line
1124 // Remove the space after '='
1126 let type_indent = indent.block_indent(context.config);
1128 result.push_str(&type_indent.to_string(context.config));
1129 let budget = try_opt!(context.config
1131 .checked_sub(type_indent.width() + ";".len()));
1132 ty.rewrite(context, Shape::legacy(budget, type_indent))
1134 result.push_str(&ty_str);
1135 result.push_str(";");
1139 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1140 (if config.space_before_type_annotation {
1145 if config.space_after_type_annotation_colon {
1152 impl Rewrite for ast::StructField {
1153 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1154 if contains_skip(&self.attrs) {
1155 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1156 return wrap_str(span, context.config.max_width, shape);
1159 let name = self.ident;
1160 let vis = format_visibility(&self.vis);
1161 let mut attr_str = try_opt!(self.attrs
1163 Shape::legacy(context.config.max_width -
1164 shape.indent.width(),
1166 if !attr_str.is_empty() {
1167 attr_str.push('\n');
1168 attr_str.push_str(&shape.indent.to_string(context.config));
1171 let type_annotation_spacing = type_annotation_spacing(context.config);
1172 let result = match name {
1174 format!("{}{}{}{}:{}",
1178 type_annotation_spacing.0,
1179 type_annotation_spacing.1)
1181 None => format!("{}{}", attr_str, vis),
1184 let last_line_width = last_line_width(&result);
1185 let budget = try_opt!(shape.width.checked_sub(last_line_width));
1186 let rewrite = try_opt!(self.ty.rewrite(context,
1187 Shape::legacy(budget,
1188 shape.indent + last_line_width)));
1189 Some(result + &rewrite)
1193 pub fn rewrite_static(prefix: &str,
1194 vis: &ast::Visibility,
1197 mutability: ast::Mutability,
1198 expr_opt: Option<&ptr::P<ast::Expr>>,
1200 context: &RewriteContext)
1202 let type_annotation_spacing = type_annotation_spacing(context.config);
1203 let prefix = format!("{}{} {}{}{}:{}",
1204 format_visibility(vis),
1206 format_mutability(mutability),
1208 type_annotation_spacing.0,
1209 type_annotation_spacing.1);
1211 let ty_str = try_opt!(ty.rewrite(context,
1212 Shape::legacy(context.config.max_width - offset.block_indent -
1215 offset.block_only())));
1217 if let Some(expr) = expr_opt {
1218 let lhs = format!("{}{} =", prefix, ty_str);
1220 let remaining_width = context.config.max_width - offset.block_indent - 1;
1221 rewrite_assign_rhs(context,
1224 Shape::legacy(remaining_width, offset.block_only()))
1227 let lhs = format!("{}{};", prefix, ty_str);
1232 pub fn rewrite_associated_type(ident: ast::Ident,
1233 ty_opt: Option<&ptr::P<ast::Ty>>,
1234 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1235 context: &RewriteContext,
1238 let prefix = format!("type {}", ident);
1240 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1241 let bounds: &[_] = ty_param_bounds;
1242 let bound_str = try_opt!(bounds.iter()
1244 ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent))
1246 .intersperse(Some(" + ".to_string()))
1247 .collect::<Option<String>>());
1248 if bounds.len() > 0 {
1249 format!(": {}", bound_str)
1257 if let Some(ty) = ty_opt {
1258 let ty_str = try_opt!(ty.rewrite(context,
1259 Shape::legacy(context.config.max_width -
1260 indent.block_indent -
1263 indent.block_only())));
1264 Some(format!("{} = {};", prefix, ty_str))
1266 Some(format!("{}{};", prefix, type_bounds_str))
1270 impl Rewrite for ast::FunctionRetTy {
1271 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1273 ast::FunctionRetTy::Default(_) => Some(String::new()),
1274 ast::FunctionRetTy::Ty(ref ty) => {
1275 let inner_width = try_opt!(shape.width.checked_sub(3));
1276 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1277 .map(|r| format!("-> {}", r))
1283 impl Rewrite for ast::Arg {
1284 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1285 if is_named_arg(self) {
1286 let mut result = try_opt!(self.pat
1288 Shape::legacy(shape.width, shape.indent)));
1290 if self.ty.node != ast::TyKind::Infer {
1291 if context.config.space_before_type_annotation {
1292 result.push_str(" ");
1294 result.push_str(":");
1295 if context.config.space_after_type_annotation_colon {
1296 result.push_str(" ");
1298 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1299 let ty_str = try_opt!(self.ty.rewrite(context,
1300 Shape::legacy(max_width,
1301 shape.indent + result.len())));
1302 result.push_str(&ty_str);
1307 self.ty.rewrite(context, shape)
1312 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1314 context: &RewriteContext)
1316 match explicit_self.node {
1317 ast::SelfKind::Region(lt, m) => {
1318 let mut_str = format_mutability(m);
1321 let lifetime_str = try_opt!(l.rewrite(context,
1322 Shape::legacy(usize::max_value(),
1324 Some(format!("&{} {}self", lifetime_str, mut_str))
1326 None => Some(format!("&{}self", mut_str)),
1329 ast::SelfKind::Explicit(ref ty, _) => {
1330 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1332 let mutability = explicit_self_mutability(&args[0]);
1333 let type_str = try_opt!(ty.rewrite(context,
1334 Shape::legacy(usize::max_value(), Indent::empty())));
1336 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1338 ast::SelfKind::Value(_) => {
1339 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1341 let mutability = explicit_self_mutability(&args[0]);
1343 Some(format!("{}self", format_mutability(mutability)))
1348 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1349 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1350 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1351 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1358 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1359 if is_named_arg(arg) {
1366 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1368 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1369 _ => arg.ty.span.hi,
1373 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1374 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1375 ident.node != symbol::keywords::Invalid.ident()
1381 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1383 ast::FunctionRetTy::Default(ref span) => span.clone(),
1384 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1388 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1389 // Note that ty.span is the span for ty.ident, not the whole item.
1390 let lo = ty.span.lo;
1391 if let Some(ref def) = ty.default {
1392 return mk_sp(lo, def.span.hi);
1394 if ty.bounds.is_empty() {
1397 let hi = match ty.bounds[ty.bounds.len() - 1] {
1398 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1399 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1404 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1406 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1407 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1408 ast::WherePredicate::EqPredicate(ref p) => p.span,
1412 // Return type is (result, force_new_line_for_brace)
1413 fn rewrite_fn_base(context: &RewriteContext,
1417 generics: &ast::Generics,
1418 unsafety: ast::Unsafety,
1419 constness: ast::Constness,
1420 defaultness: ast::Defaultness,
1422 vis: &ast::Visibility,
1424 newline_brace: bool,
1426 -> Option<(String, bool)> {
1427 let mut force_new_line_for_brace = false;
1429 let where_clause = &generics.where_clause;
1431 let mut result = String::with_capacity(1024);
1432 // Vis unsafety abi.
1433 result.push_str(&*format_visibility(vis));
1435 if let ast::Defaultness::Default = defaultness {
1436 result.push_str("default ");
1439 if let ast::Constness::Const = constness {
1440 result.push_str("const ");
1443 result.push_str(::utils::format_unsafety(unsafety));
1445 if abi != abi::Abi::Rust {
1446 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1450 result.push_str("fn ");
1451 result.push_str(&ident.to_string());
1454 let generics_indent = indent + result.len();
1455 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1456 let generics_str = try_opt!(rewrite_generics(context,
1458 Shape::legacy(context.config.max_width, indent),
1461 result.push_str(&generics_str);
1463 // Note that if the width and indent really matter, we'll re-layout the
1464 // return type later anyway.
1465 let ret_str = try_opt!(fd.output
1467 Shape::legacy(context.config.max_width -
1471 let multi_line_ret_str = ret_str.contains('\n');
1472 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1475 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1476 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1478 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1479 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1480 arg_indent = indent.block_indent(context.config);
1481 multi_line_budget = context.config.max_width - arg_indent.width();
1484 debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1489 // Check if vertical layout was forced.
1490 if one_line_budget == 0 {
1491 if context.config.fn_args_paren_newline {
1493 result.push_str(&arg_indent.to_string(context.config));
1494 arg_indent = arg_indent + 1; // extra space for `(`
1496 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1500 result.push_str("(\n");
1501 result.push_str(&arg_indent.to_string(context.config));
1505 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1510 if multi_line_ret_str {
1511 one_line_budget = 0;
1514 // A conservative estimation, to goal is to be over all parens in generics
1515 let args_start = generics.ty_params
1517 .map_or(span.lo, |tp| end_typaram(tp));
1518 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1519 span_for_return(&fd.output).lo);
1520 let arg_str = try_opt!(rewrite_args(context,
1522 fd.get_self().as_ref(),
1530 let multi_line_arg_str = arg_str.contains('\n');
1532 let put_args_in_block = match context.config.fn_args_layout {
1533 FnArgLayoutStyle::Block => multi_line_arg_str,
1534 FnArgLayoutStyle::BlockAlways => true,
1536 } && !fd.inputs.is_empty();
1538 if put_args_in_block {
1539 arg_indent = indent.block_indent(context.config);
1541 result.push_str(&arg_indent.to_string(context.config));
1542 result.push_str(&arg_str);
1544 result.push_str(&indent.to_string(context.config));
1547 result.push_str(&arg_str);
1548 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1555 if !ret_str.is_empty() {
1556 let ret_should_indent = match context.config.fn_args_layout {
1557 // If our args are block layout then we surely must have space.
1558 FnArgLayoutStyle::Block if put_args_in_block => false,
1559 FnArgLayoutStyle::BlockAlways => false,
1561 // If we've already gone multi-line, or the return type would push over the max
1562 // width, then put the return type on a new line. With the +1 for the signature
1563 // length an additional space between the closing parenthesis of the argument and
1564 // the arrow '->' is considered.
1565 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1567 // If there is no where clause, take into account the space after the return type
1569 if where_clause.predicates.is_empty() {
1573 let overlong_sig = sig_length > context.config.max_width;
1575 result.contains('\n') || multi_line_ret_str || overlong_sig
1578 let ret_indent = if ret_should_indent {
1579 let indent = match context.config.fn_return_indent {
1580 ReturnIndent::WithWhereClause => indent + 4,
1581 // Aligning with non-existent args looks silly.
1582 _ if arg_str.is_empty() => {
1583 force_new_line_for_brace = true;
1586 // FIXME: we might want to check that using the arg indent
1587 // doesn't blow our budget, and if it does, then fallback to
1588 // the where clause indent.
1593 result.push_str(&indent.to_string(context.config));
1597 Indent::new(indent.width(), result.len())
1600 if multi_line_ret_str {
1601 // Now that we know the proper indent and width, we need to
1602 // re-layout the return type.
1603 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1604 let ret_str = try_opt!(fd.output.rewrite(context, Shape::legacy(budget, ret_indent)));
1605 result.push_str(&ret_str);
1607 result.push_str(&ret_str);
1610 // Comment between return type and the end of the decl.
1611 let snippet_lo = fd.output.span().hi;
1612 if where_clause.predicates.is_empty() {
1613 let snippet_hi = span.hi;
1614 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1615 let snippet = snippet.trim();
1616 if !snippet.is_empty() {
1618 result.push_str(snippet);
1621 // FIXME it would be nice to catch comments between the return type
1622 // and the where clause, but we don't have a span for the where
1627 let should_compress_where = match context.config.where_density {
1628 Density::Compressed => !result.contains('\n') || put_args_in_block,
1629 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1631 } || (put_args_in_block && ret_str.is_empty());
1633 let where_density = if should_compress_where {
1640 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1641 let where_clause_str = try_opt!(rewrite_where_clause(context,
1644 context.config.fn_brace_style,
1645 Shape::legacy(where_budget, indent),
1651 if last_line_width(&result) + where_clause_str.len() > context.config.max_width &&
1652 !where_clause_str.contains('\n') {
1656 result.push_str(&where_clause_str);
1658 Some((result, force_new_line_for_brace))
1661 fn rewrite_args(context: &RewriteContext,
1663 explicit_self: Option<&ast::ExplicitSelf>,
1664 one_line_budget: usize,
1665 multi_line_budget: usize,
1671 let mut arg_item_strs =
1672 try_opt!(args.iter()
1674 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
1676 .collect::<Option<Vec<_>>>());
1678 // Account for sugary self.
1679 // FIXME: the comment for the self argument is dropped. This is blocked
1680 // on rust issue #27522.
1682 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1683 .map_or(1, |self_str| {
1684 arg_item_strs[0] = self_str;
1688 // Comments between args.
1689 let mut arg_items = Vec::new();
1691 arg_items.push(ListItem::from_str(""));
1694 // FIXME(#21): if there are no args, there might still be a comment, but
1695 // without spans for the comment or parens, there is no chance of
1696 // getting it right. You also don't get to put a comment on self, unless
1698 if args.len() >= min_args || variadic {
1699 let comment_span_start = if min_args == 2 {
1700 let second_arg_start = if arg_has_pattern(&args[1]) {
1705 let reduced_span = mk_sp(span.lo, second_arg_start);
1707 context.codemap.span_after_last(reduced_span, ",")
1712 enum ArgumentKind<'a> {
1713 Regular(&'a ast::Arg),
1717 let variadic_arg = if variadic {
1718 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1719 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1720 Some(ArgumentKind::Variadic(variadic_start))
1725 let more_items = itemize_list(context.codemap,
1726 args[min_args - 1..]
1728 .map(ArgumentKind::Regular)
1729 .chain(variadic_arg),
1732 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1733 ArgumentKind::Variadic(start) => start,
1736 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1737 ArgumentKind::Variadic(start) => start + BytePos(3),
1740 ArgumentKind::Regular(..) => None,
1741 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1746 arg_items.extend(more_items);
1749 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1750 item.item = Some(arg);
1753 let indent = match context.config.fn_arg_indent {
1754 BlockIndentStyle::Inherit => indent,
1755 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1756 BlockIndentStyle::Visual => arg_indent,
1759 let tactic = definitive_tactic(&arg_items,
1760 context.config.fn_args_density.to_list_tactic(),
1762 let budget = match tactic {
1763 DefinitiveListTactic::Horizontal => one_line_budget,
1764 _ => multi_line_budget,
1767 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1769 let end_with_newline = match context.config.fn_args_layout {
1770 FnArgLayoutStyle::Block |
1771 FnArgLayoutStyle::BlockAlways => true,
1775 let fmt = ListFormatting {
1778 trailing_separator: SeparatorTactic::Never,
1779 shape: Shape::legacy(budget, indent),
1780 ends_with_newline: end_with_newline,
1781 config: context.config,
1784 write_list(&arg_items, &fmt)
1787 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1788 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1789 ident.node != symbol::keywords::Invalid.ident()
1795 fn compute_budgets_for_args(context: &RewriteContext,
1799 newline_brace: bool)
1800 -> Option<((usize, usize, Indent))> {
1801 debug!("compute_budgets_for_args {} {:?}, {}, {}",
1806 // Try keeping everything on the same line.
1807 if !result.contains('\n') {
1808 // 3 = `() `, space is before ret_string.
1809 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1813 let one_line_budget = context.config.max_width.checked_sub(used_space).unwrap_or(0);
1815 if one_line_budget > 0 {
1817 let multi_line_budget =
1818 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1820 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1824 // Didn't work. we must force vertical layout and put args on a newline.
1825 let new_indent = indent.block_indent(context.config);
1826 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1827 let max_space = context.config.max_width;
1828 if used_space <= max_space {
1829 Some((0, max_space - used_space, new_indent))
1831 // Whoops! bankrupt.
1836 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1837 match config.fn_brace_style {
1838 BraceStyle::AlwaysNextLine => true,
1839 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1844 fn rewrite_generics(context: &RewriteContext,
1845 generics: &ast::Generics,
1847 // TODO shouldn't need this
1848 generics_offset: Indent,
1851 // FIXME: convert bounds to where clauses where they get too big or if
1852 // there is a where clause at all.
1853 let lifetimes: &[_] = &generics.lifetimes;
1854 let tys: &[_] = &generics.ty_params;
1855 if lifetimes.is_empty() && tys.is_empty() {
1856 return Some(String::new());
1859 let offset = match context.config.generics_indent {
1860 BlockIndentStyle::Inherit => shape.indent,
1861 BlockIndentStyle::Tabbed => shape.indent.block_indent(context.config),
1863 BlockIndentStyle::Visual => generics_offset + 1,
1866 let h_budget = try_opt!(shape.width.checked_sub(generics_offset.width() + 2));
1867 // FIXME: might need to insert a newline if the generics are really long.
1869 // Strings for the generics.
1870 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1871 let ty_strs = tys.iter()
1872 .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
1874 // Extract comments between generics.
1875 let lt_spans = lifetimes.iter().map(|l| {
1876 let hi = if l.bounds.is_empty() {
1879 l.bounds[l.bounds.len() - 1].span.hi
1881 mk_sp(l.lifetime.span.lo, hi)
1883 let ty_spans = tys.iter().map(span_for_ty_param);
1885 let items = itemize_list(context.codemap,
1886 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1890 // FIXME: don't clone
1891 |&(_, ref str)| str.clone(),
1892 context.codemap.span_after(span, "<"),
1895 try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
1897 Some(if context.config.spaces_within_angle_brackets {
1898 format!("< {} >", list_str)
1900 format!("<{}>", list_str)
1904 fn rewrite_trait_bounds(context: &RewriteContext,
1905 type_param_bounds: &ast::TyParamBounds,
1908 let bounds: &[_] = type_param_bounds;
1910 if bounds.is_empty() {
1911 return Some(String::new());
1914 let bound_str = try_opt!(bounds.iter()
1915 .map(|ty_bound| ty_bound.rewrite(&context, shape))
1916 .intersperse(Some(" + ".to_string()))
1917 .collect::<Option<String>>());
1919 let mut result = String::new();
1920 result.push_str(": ");
1921 result.push_str(&bound_str);
1925 fn rewrite_where_clause(context: &RewriteContext,
1926 where_clause: &ast::WhereClause,
1928 brace_style: BraceStyle,
1932 allow_trailing_comma: bool,
1933 span_end: Option<BytePos>)
1935 if where_clause.predicates.is_empty() {
1936 return Some(String::new());
1939 let extra_indent = match context.config.where_indent {
1940 BlockIndentStyle::Inherit => Indent::empty(),
1941 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1944 let offset = match context.config.where_pred_indent {
1945 BlockIndentStyle::Inherit => shape.indent + extra_indent,
1946 BlockIndentStyle::Tabbed => shape.indent + extra_indent.block_indent(config),
1947 // 6 = "where ".len()
1948 BlockIndentStyle::Visual => shape.indent + extra_indent + 6,
1950 // FIXME: if where_pred_indent != Visual, then the budgets below might
1951 // be out by a char or two.
1953 let budget = context.config.max_width - offset.width();
1954 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1955 // If we don't have the start of the next span, then use the end of the
1956 // predicates, but that means we miss comments.
1957 let len = where_clause.predicates.len();
1958 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1959 let span_end = span_end.unwrap_or(end_of_preds);
1960 let items = itemize_list(context.codemap,
1961 where_clause.predicates.iter(),
1963 |pred| span_for_where_pred(pred).lo,
1964 |pred| span_for_where_pred(pred).hi,
1965 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
1968 let item_vec = items.collect::<Vec<_>>();
1969 // FIXME: we don't need to collect here if the where_layout isn't
1970 // HorizontalVertical.
1971 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1972 let use_trailing_comma = allow_trailing_comma && context.config.where_trailing_comma;
1974 let fmt = ListFormatting {
1977 trailing_separator: SeparatorTactic::from_bool(use_trailing_comma),
1978 shape: Shape::legacy(budget, offset),
1979 ends_with_newline: true,
1980 config: context.config,
1982 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1984 let end_length = if terminator == "{" {
1985 // If the brace is on the next line we don't need to count it otherwise it needs two
1988 BraceStyle::AlwaysNextLine |
1989 BraceStyle::SameLineWhere => 0,
1990 BraceStyle::PreferSameLine => 2,
1992 } else if terminator == "=" {
1997 if density == Density::Tall || preds_str.contains('\n') ||
1998 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
1999 Some(format!("\n{}where {}",
2000 (shape.indent + extra_indent).to_string(context.config),
2003 Some(format!(" where {}", preds_str))
2007 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2008 format!("{}{}{}", format_visibility(vis), item_name, ident)
2011 fn format_generics(context: &RewriteContext,
2012 generics: &ast::Generics,
2015 brace_style: BraceStyle,
2016 force_same_line_brace: bool,
2018 generics_offset: Indent,
2021 let mut result = try_opt!(rewrite_generics(context,
2023 Shape::legacy(context.config.max_width, offset),
2027 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2028 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
2029 let where_clause_str = try_opt!(rewrite_where_clause(context,
2030 &generics.where_clause,
2033 Shape::legacy(budget,
2034 offset.block_only()),
2039 result.push_str(&where_clause_str);
2040 if !force_same_line_brace &&
2041 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2043 result.push_str(&offset.block_only().to_string(context.config));
2047 result.push_str(opener);
2049 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
2051 result.push_str(&offset.block_only().to_string(context.config));
2055 result.push_str(opener);