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 trimmed_last_line_width};
18 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, list_helper,
19 DefinitiveListTactic, ListTactic, definitive_tactic, format_item_list};
20 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, type_annotation_separator};
21 use comment::{FindUncommented, contains_comment};
22 use visitor::FmtVisitor;
23 use rewrite::{Rewrite, RewriteContext};
24 use config::{Config, IndentStyle, Density, ReturnIndent, BraceStyle, Style, TypeDensity};
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();
41 let pat_shape = try_opt!(shape.offset_left(4));
43 let pat_shape = try_opt!(pat_shape.sub_width(1));
44 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
45 result.push_str(&pat_str);
47 // String that is placed within the assignment pattern and expression.
49 let mut infix = String::new();
51 if let Some(ref ty) = self.ty {
52 let separator = type_annotation_separator(context.config);
53 let indent = shape.indent + last_line_width(&result) + separator.len();
55 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
56 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
58 infix.push_str(separator);
59 infix.push_str(&rewrite);
62 if self.init.is_some() {
69 result.push_str(&infix);
71 if let Some(ref ex) = self.init {
72 // 1 = trailing semicolon;
73 let nested_shape = try_opt!(shape.sub_width(1));
75 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
83 // TODO convert to using rewrite style rather than visitor
84 // TODO format modules in this style
87 keyword: &'static str,
89 vis: Option<&'a ast::Visibility>,
90 body: Vec<BodyElement<'a>>,
95 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
96 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
99 format!("extern {}", fm.abi)
107 .map(|i| BodyElement::ForeignItem(i))
114 enum BodyElement<'a> {
115 // Stmt(&'a ast::Stmt),
116 // Field(&'a ast::Field),
117 // Variant(&'a ast::Variant),
118 // Item(&'a ast::Item),
119 ForeignItem(&'a ast::ForeignItem),
122 impl<'a> FmtVisitor<'a> {
123 fn format_item(&mut self, item: Item) {
124 self.buffer.push_str(&item.abi);
125 self.buffer.push_str(" ");
127 let snippet = self.snippet(item.span);
128 let brace_pos = snippet.find_uncommented("{").unwrap();
130 self.buffer.push_str("{");
131 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
132 // FIXME: this skips comments between the extern keyword and the opening
134 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
135 self.block_indent = self.block_indent.block_indent(self.config);
137 if item.body.is_empty() {
138 self.format_missing_no_indent(item.span.hi - BytePos(1));
139 self.block_indent = self.block_indent.block_unindent(self.config);
142 .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.
195 Some((new_fn, _)) => {
196 self.buffer.push_str(&new_fn);
197 self.buffer.push_str(";");
199 None => self.format_missing(item.span.hi),
202 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
203 // FIXME(#21): we're dropping potential comments in between the
204 // function keywords here.
205 let vis = format_visibility(&item.vis);
206 let mut_str = if is_mutable { "mut " } else { "" };
207 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
208 let offset = self.block_indent + prefix.len();
210 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
211 let rewrite = ty.rewrite(&self.get_context(), shape);
215 self.buffer.push_str(&prefix);
216 self.buffer.push_str(&result);
217 self.buffer.push_str(";");
219 None => self.format_missing(item.span.hi),
224 self.last_pos = item.span.hi;
227 pub fn rewrite_fn(&mut self,
231 generics: &ast::Generics,
232 unsafety: ast::Unsafety,
233 constness: ast::Constness,
234 defaultness: ast::Defaultness,
236 vis: &ast::Visibility,
240 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
241 let context = self.get_context();
243 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
244 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
245 !context.config.fn_empty_single_line();
247 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
262 if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine && !result.contains('\n') {
263 newline_brace = false;
264 } else if force_newline_brace {
265 newline_brace = true;
268 // Prepare for the function body by possibly adding a newline and
270 // FIXME we'll miss anything between the end of the signature and the
271 // start of the body, but we need more spans from the compiler to solve
275 result.push_str(&indent.to_string(self.config));
280 self.single_line_fn(&result, block).or_else(|| Some(result))
283 pub fn rewrite_required_fn(&mut self,
286 sig: &ast::MethodSig,
289 // Drop semicolon or it will be interpreted as comment.
290 let span = mk_sp(span.lo, span.hi - BytePos(1));
291 let context = self.get_context();
293 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
300 ast::Defaultness::Final,
302 &ast::Visibility::Inherited,
308 // Re-attach semicolon
314 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
315 if fn_str.contains('\n') {
319 let codemap = self.get_context().codemap;
321 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
322 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width() {
323 return Some(format!("{}{{}}", fn_str));
326 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
328 if let Some(ref stmt) = block.stmts.first() {
329 match stmt_expr(stmt) {
331 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
333 e.rewrite(&self.get_context(),
334 Shape::indented(self.block_indent, self.config))
336 .or_else(|| Some(self.snippet(e.span)))
339 stmt.rewrite(&self.get_context(),
340 Shape::indented(self.block_indent, self.config))
348 if let Some(res) = rewrite {
349 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
350 if !res.contains('\n') && width <= self.config.max_width() {
351 return Some(format!("{}{{ {} }}", fn_str, res));
359 pub fn visit_enum(&mut self,
361 vis: &ast::Visibility,
362 enum_def: &ast::EnumDef,
363 generics: &ast::Generics,
365 self.buffer.push_str(&format_header("enum ", ident, vis));
367 let enum_snippet = self.snippet(span);
368 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
369 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
370 let generics_str = format_generics(&self.get_context(),
374 self.config.item_brace_style(),
375 enum_def.variants.is_empty(),
377 mk_sp(span.lo, body_start))
379 self.buffer.push_str(&generics_str);
381 self.last_pos = body_start;
383 self.block_indent = self.block_indent.block_indent(self.config);
384 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
386 Some(ref body_str) => self.buffer.push_str(body_str),
388 if contains_comment(&enum_snippet[brace_pos..]) {
389 self.format_missing_no_indent(span.hi - BytePos(1))
391 self.format_missing(span.hi - BytePos(1))
395 self.block_indent = self.block_indent.block_unindent(self.config);
397 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
399 .push_str(&self.block_indent.to_string(self.config));
401 self.buffer.push_str("}");
402 self.last_pos = span.hi;
405 // Format the body of an enum definition
406 fn format_variant_list(&self,
407 enum_def: &ast::EnumDef,
411 if enum_def.variants.is_empty() {
414 let mut result = String::with_capacity(1024);
416 let indentation = self.block_indent.to_string(self.config);
417 result.push_str(&indentation);
419 let items = itemize_list(self.codemap,
420 enum_def.variants.iter(),
422 |f| if !f.node.attrs.is_empty() {
423 f.node.attrs[0].span.lo
428 |f| self.format_variant(f),
432 let shape = Shape::indented(self.block_indent, self.config)
435 let fmt = ListFormatting {
436 tactic: DefinitiveListTactic::Vertical,
438 trailing_separator: self.config.trailing_comma(),
440 ends_with_newline: true,
444 let list = try_opt!(write_list(items, &fmt));
445 result.push_str(&list);
450 // Variant of an enum.
451 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
452 if contains_skip(&field.node.attrs) {
453 let lo = field.node.attrs[0].span.lo;
454 let span = mk_sp(lo, field.span.hi);
455 return Some(self.snippet(span));
458 let indent = self.block_indent;
459 let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
460 Shape::indented(indent, self.config)));
461 if !result.is_empty() {
463 result.push_str(&indent.to_string(self.config));
466 let context = self.get_context();
467 let variant_body = match field.node.data {
468 ast::VariantData::Tuple(..) |
469 ast::VariantData::Struct(..) => {
470 // FIXME: Should limit the width, as we have a trailing comma
471 format_struct(&context,
474 &ast::Visibility::Inherited,
479 Some(self.config.struct_variant_width()))
481 ast::VariantData::Unit(..) => {
482 let tag = if let Some(ref expr) = field.node.disr_expr {
483 format!("{} = {}", field.node.name, self.snippet(expr.span))
485 field.node.name.to_string()
489 self.config.max_width(),
490 Shape::indented(indent, self.config))
494 if let Some(variant_str) = variant_body {
495 result.push_str(&variant_str);
503 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
504 if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
505 let mut result = String::new();
506 // First try to format the ref and type without a split at the 'for'.
507 let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
509 // If there is a line break present in the first result format it again
510 // with a split at the 'for'. Skip this if there is no trait ref and
511 // therefore no 'for'.
512 if ref_and_type.contains('\n') && trait_ref.is_some() {
513 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
515 result.push_str(&ref_and_type);
517 let where_budget = try_opt!(context
520 .checked_sub(last_line_width(&result)));
521 let where_clause_str = try_opt!(rewrite_where_clause(context,
522 &generics.where_clause,
523 context.config.item_brace_style(),
524 Shape::legacy(where_budget,
525 offset.block_only()),
526 context.config.where_density(),
529 last_line_width(&ref_and_type) == 1,
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_indent = offset + last_line_width(&result);
638 let shape = Shape::indented(generics_indent, context.config);
639 let generics_str = try_opt!(rewrite_generics(context, generics, shape, mk_sp(lo, hi)));
640 result.push_str(&generics_str);
642 if polarity == ast::ImplPolarity::Negative {
643 result.push_str(" !");
645 if let Some(ref trait_ref) = *trait_ref {
646 if polarity != ast::ImplPolarity::Negative {
647 result.push_str(" ");
649 let used_space = last_line_width(&result);
650 let budget = try_opt!(context.config.max_width().checked_sub(used_space));
651 let indent = offset + used_space;
652 result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
657 // Add indentation of one additional tab.
658 let width = offset.block_indent + context.config.tab_spaces();
659 let for_indent = Indent::new(0, width);
660 result.push_str(&for_indent.to_string(context.config));
662 result.push_str("for");
664 result.push_str(" for");
668 let mut used_space = last_line_width(&result);
669 if generics.where_clause.predicates.is_empty() {
670 // If there is no where clause adapt budget for type formatting to take space and curly
671 // brace into account.
672 match context.config.item_brace_style() {
673 BraceStyle::AlwaysNextLine => {}
674 BraceStyle::PreferSameLine => used_space += 2,
675 BraceStyle::SameLineWhere => used_space += 2,
679 // 1 = space before the type.
680 let budget = try_opt!(context.config.max_width().checked_sub(used_space + 1));
681 let indent = offset + result.len() + 1;
682 let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
683 if let Some(self_ty_str) = self_ty_str {
684 result.push_str(" ");
685 result.push_str(&self_ty_str);
689 // Can't fit the self type on what's left of the line, so start a new one.
690 let indent = offset.block_indent(context.config);
691 result.push_str(&format!("\n{}", indent.to_string(context.config)));
692 result.push_str(&*try_opt!(self_ty.rewrite(context,
693 Shape::indented(indent, context.config))));
700 pub fn format_struct(context: &RewriteContext,
703 vis: &ast::Visibility,
704 struct_def: &ast::VariantData,
705 generics: Option<&ast::Generics>,
708 one_line_width: Option<usize>)
711 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
712 ast::VariantData::Tuple(ref fields, _) => {
713 format_tuple_struct(context,
722 ast::VariantData::Struct(ref fields, _) => {
723 format_struct_struct(context,
736 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
737 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
739 let mut result = String::new();
740 let header = format!("{}{}trait {}",
741 format_visibility(&item.vis),
742 format_unsafety(unsafety),
745 result.push_str(&header);
747 let body_lo = context.codemap.span_after(item.span, "{");
749 let generics_indent = offset + last_line_width(&result);
750 let shape = Shape::indented(generics_indent, context.config);
752 try_opt!(rewrite_generics(context, generics, shape, mk_sp(item.span.lo, body_lo)));
753 result.push_str(&generics_str);
755 let trait_bound_str =
756 try_opt!(rewrite_trait_bounds(context,
758 Shape::legacy(context.config.max_width(), offset)));
759 // If the trait, generics, and trait bound cannot fit on the same line,
760 // put the trait bounds on an indented new line
761 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
762 context.config.comment_width() {
764 let trait_indent = offset.block_only().block_indent(context.config);
765 result.push_str(&trait_indent.to_string(context.config));
767 result.push_str(&trait_bound_str);
769 let has_body = !trait_items.is_empty();
772 if (context.config.where_density() == Density::Compressed &&
773 (!result.contains('\n') ||
774 context.config.fn_args_layout() == IndentStyle::Block)) ||
775 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
776 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
777 !result.contains('\n')) {
783 let where_budget = try_opt!(context
786 .checked_sub(last_line_width(&result)));
787 let where_clause_str = try_opt!(rewrite_where_clause(context,
788 &generics.where_clause,
789 context.config.item_brace_style(),
790 Shape::legacy(where_budget,
791 offset.block_only()),
795 trait_bound_str.is_empty() &&
796 last_line_width(&generics_str) == 1,
798 // If the where clause cannot fit on the same line,
799 // put the where clause on a new line
800 if !where_clause_str.contains('\n') &&
801 last_line_width(&result) + where_clause_str.len() + offset.width() >
802 context.config.comment_width() {
804 let width = offset.block_indent + context.config.tab_spaces() - 1;
805 let where_indent = Indent::new(0, width);
806 result.push_str(&where_indent.to_string(context.config));
808 result.push_str(&where_clause_str);
810 match context.config.item_brace_style() {
811 BraceStyle::AlwaysNextLine => {
813 result.push_str(&offset.to_string(context.config));
815 BraceStyle::PreferSameLine => result.push(' '),
816 BraceStyle::SameLineWhere => {
817 if !where_clause_str.is_empty() &&
818 (!trait_items.is_empty() || result.contains('\n')) {
820 result.push_str(&offset.to_string(context.config));
828 let snippet = context.snippet(item.span);
829 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
831 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
832 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
833 visitor.block_indent = offset.block_only().block_indent(context.config);
834 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
836 for item in trait_items {
837 visitor.visit_trait_item(item);
840 visitor.format_missing(item.span.hi - BytePos(1));
842 let inner_indent_str = visitor.block_indent.to_string(context.config);
843 let outer_indent_str = offset.block_only().to_string(context.config);
846 result.push_str(&inner_indent_str);
847 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
849 result.push_str(&outer_indent_str);
850 } else if result.contains('\n') {
861 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
862 format!("{};", format_header(item_name, ident, vis))
865 fn format_struct_struct(context: &RewriteContext,
868 vis: &ast::Visibility,
869 fields: &[ast::StructField],
870 generics: Option<&ast::Generics>,
873 one_line_width: Option<usize>)
875 let mut result = String::with_capacity(1024);
877 let header_str = format_header(item_name, ident, vis);
878 result.push_str(&header_str);
880 let body_lo = context.codemap.span_after(span, "{");
882 let generics_str = match generics {
884 try_opt!(format_generics(context,
888 context.config.item_brace_style(),
891 mk_sp(span.lo, body_lo)))
894 if context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
896 format!("\n{}{{", offset.block_only().to_string(context.config))
902 result.push_str(&generics_str);
904 if fields.is_empty() {
905 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
906 if snippet.trim().is_empty() {
908 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
910 result.push_str(&snippet.trim_right());
912 result.push_str(&offset.to_string(context.config));
914 result.push_str(&snippet);
920 let item_indent = offset.block_indent(context.config);
922 let item_budget = try_opt!(context
925 .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.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{}}}",
967 .block_indent(context.config)
968 .to_string(context.config),
970 offset.to_string(context.config)))
974 fn format_tuple_struct(context: &RewriteContext,
977 vis: &ast::Visibility,
978 fields: &[ast::StructField],
979 generics: Option<&ast::Generics>,
983 let mut result = String::with_capacity(1024);
985 let header_str = format_header(item_name, ident, vis);
986 result.push_str(&header_str);
988 let body_lo = if fields.is_empty() {
989 context.codemap.span_after(span, "(")
994 let where_clause_str = match generics {
996 let generics_indent = offset + last_line_width(&header_str);
997 let shape = Shape::indented(generics_indent, context.config);
999 try_opt!(rewrite_generics(context, generics, shape, mk_sp(span.lo, body_lo)));
1000 result.push_str(&generics_str);
1002 let where_budget = try_opt!(context
1005 .checked_sub(last_line_width(&result)));
1006 try_opt!(rewrite_where_clause(context,
1007 &generics.where_clause,
1008 context.config.item_brace_style(),
1009 Shape::legacy(where_budget, offset.block_only()),
1010 Density::Compressed,
1016 None => "".to_owned(),
1019 if fields.is_empty() {
1021 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1022 if snippet.is_empty() {
1024 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1025 result.push_str(&snippet.trim_right());
1027 result.push_str(&offset.to_string(context.config));
1029 result.push_str(&snippet);
1033 let (tactic, item_indent) = match context.config.fn_args_layout() {
1034 IndentStyle::Visual => {
1036 (ListTactic::HorizontalVertical, offset.block_only() + result.len() + 1)
1038 IndentStyle::Block => {
1039 (ListTactic::HorizontalVertical, offset.block_only().block_indent(&context.config))
1043 let item_budget = try_opt!(context
1046 .checked_sub(item_indent.width() + 3));
1049 itemize_list(context.codemap,
1053 // Include attributes and doc comments, if present
1054 if !field.attrs.is_empty() {
1055 field.attrs[0].span.lo
1060 |field| field.ty.span.hi,
1061 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1062 context.codemap.span_after(span, "("),
1068 .checked_sub(offset.block_only().width() + result.len() + 3));
1069 let body = try_opt!(list_helper(items,
1070 // TODO budget is wrong in block case
1071 Shape::legacy(body_budget, item_indent),
1075 if context.config.fn_args_layout() == IndentStyle::Visual || !body.contains('\n') {
1077 if context.config.spaces_within_parens() && body.len() > 0 {
1081 result.push_str(&body);
1083 if context.config.spaces_within_parens() && body.len() > 0 {
1088 result.push_str("(\n");
1089 result.push_str(&item_indent.to_string(&context.config));
1090 result.push_str(&body);
1092 result.push_str(&offset.block_only().to_string(&context.config));
1097 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1098 (result.contains('\n') ||
1099 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1100 context.config.max_width()) {
1101 // We need to put the where clause on a new line, but we didn't
1102 // know that earlier, so the where clause will not be indented properly.
1104 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1105 .to_string(context.config));
1107 result.push_str(&where_clause_str);
1112 pub fn rewrite_type_alias(context: &RewriteContext,
1116 generics: &ast::Generics,
1117 vis: &ast::Visibility,
1120 let mut result = String::new();
1122 result.push_str(&format_visibility(vis));
1123 result.push_str("type ");
1124 result.push_str(&ident.to_string());
1126 let generics_indent = indent + result.len();
1127 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1128 let shape = try_opt!(Shape::indented(generics_indent, context.config).sub_width(" =".len()));
1129 let generics_str = try_opt!(rewrite_generics(context, generics, shape, generics_span));
1131 result.push_str(&generics_str);
1133 let where_budget = try_opt!(context
1136 .checked_sub(last_line_width(&result)));
1137 let where_clause_str = try_opt!(rewrite_where_clause(context,
1138 &generics.where_clause,
1139 context.config.item_brace_style(),
1140 Shape::legacy(where_budget, indent),
1141 context.config.where_density(),
1146 result.push_str(&where_clause_str);
1147 result.push_str(" = ");
1149 let line_width = last_line_width(&result);
1150 // This checked_sub may fail as the extra space after '=' is not taken into account
1151 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1152 let budget = context
1155 .checked_sub(indent.width() + line_width + ";".len())
1157 let type_indent = indent + line_width;
1158 // Try to fit the type on the same line
1159 let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
1161 // The line was too short, try to put the type on the next line
1163 // Remove the space after '='
1165 let type_indent = indent.block_indent(context.config);
1167 result.push_str(&type_indent.to_string(context.config));
1168 let budget = try_opt!(context
1171 .checked_sub(type_indent.width() + ";".len()));
1172 ty.rewrite(context, Shape::legacy(budget, type_indent))
1174 result.push_str(&ty_str);
1175 result.push_str(";");
1179 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1180 (if config.space_before_type_annotation() {
1185 if config.space_after_type_annotation_colon() {
1192 impl Rewrite for ast::StructField {
1193 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1194 if contains_skip(&self.attrs) {
1195 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1196 return wrap_str(span, context.config.max_width(), shape);
1199 let name = self.ident;
1200 let vis = format_visibility(&self.vis);
1201 let mut attr_str = try_opt!(self.attrs.rewrite(context,
1202 Shape::indented(shape.indent,
1204 if !attr_str.is_empty() {
1205 attr_str.push('\n');
1206 attr_str.push_str(&shape.indent.to_string(context.config));
1209 let type_annotation_spacing = type_annotation_spacing(context.config);
1210 let mut result = match name {
1211 Some(name) => format!("{}{}{}{}:", attr_str, vis, name, type_annotation_spacing.0),
1212 None => format!("{}{}", attr_str, vis),
1215 let type_offset = shape.indent.block_indent(context.config);
1216 let rewrite_type_in_next_line = || {
1218 .rewrite(context, Shape::indented(type_offset, context.config))
1221 let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len();
1222 let budget = try_opt!(shape.width.checked_sub(last_line_width));
1224 self.ty.rewrite(context,
1225 Shape::legacy(budget, shape.indent + last_line_width));
1226 match ty_rewritten {
1227 Some(ref ty) if ty.contains('\n') => {
1228 let new_ty = rewrite_type_in_next_line();
1230 Some(ref new_ty) if !new_ty.contains('\n') &&
1231 new_ty.len() + type_offset.width() <=
1232 context.config.max_width() => {
1233 Some(format!("{}\n{}{}",
1235 type_offset.to_string(&context.config),
1240 result.push_str(type_annotation_spacing.1);
1248 result.push_str(type_annotation_spacing.1);
1253 let ty = try_opt!(rewrite_type_in_next_line());
1254 Some(format!("{}\n{}{}",
1256 type_offset.to_string(&context.config),
1263 pub fn rewrite_static(prefix: &str,
1264 vis: &ast::Visibility,
1267 mutability: ast::Mutability,
1268 expr_opt: Option<&ptr::P<ast::Expr>>,
1270 context: &RewriteContext)
1272 let type_annotation_spacing = type_annotation_spacing(context.config);
1273 let prefix = format!("{}{} {}{}{}:{}",
1274 format_visibility(vis),
1276 format_mutability(mutability),
1278 type_annotation_spacing.0,
1279 type_annotation_spacing.1);
1281 let ty_str = try_opt!(ty.rewrite(context,
1282 Shape::legacy(context.config.max_width() -
1283 offset.block_indent -
1286 offset.block_only())));
1288 if let Some(expr) = expr_opt {
1289 let lhs = format!("{}{} =", prefix, ty_str);
1291 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1292 rewrite_assign_rhs(context,
1295 Shape::legacy(remaining_width, offset.block_only()))
1298 let lhs = format!("{}{};", prefix, ty_str);
1303 pub fn rewrite_associated_type(ident: ast::Ident,
1304 ty_opt: Option<&ptr::P<ast::Ty>>,
1305 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1306 context: &RewriteContext,
1309 let prefix = format!("type {}", ident);
1311 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1312 let joiner = match context.config.type_punctuation_density() {
1313 TypeDensity::Compressed => "+",
1314 TypeDensity::Wide => " + ",
1316 let bounds: &[_] = ty_param_bounds;
1321 ty_bound.rewrite(context,
1322 Shape::legacy(context.config.max_width(),
1325 .collect::<Option<Vec<_>>>())
1327 if bounds.len() > 0 {
1328 format!(": {}", bound_str)
1336 if let Some(ty) = ty_opt {
1337 let ty_str = try_opt!(ty.rewrite(context,
1338 Shape::legacy(context.config.max_width() -
1339 indent.block_indent -
1342 indent.block_only())));
1343 Some(format!("{} = {};", prefix, ty_str))
1345 Some(format!("{}{};", prefix, type_bounds_str))
1349 pub fn rewrite_associated_impl_type(ident: ast::Ident,
1350 defaultness: ast::Defaultness,
1351 ty_opt: Option<&ptr::P<ast::Ty>>,
1352 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1353 context: &RewriteContext,
1357 try_opt!(rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent));
1360 ast::Defaultness::Default => Some(format!("default {}", result)),
1365 impl Rewrite for ast::FunctionRetTy {
1366 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1368 ast::FunctionRetTy::Default(_) => Some(String::new()),
1369 ast::FunctionRetTy::Ty(ref ty) => {
1370 let inner_width = try_opt!(shape.width.checked_sub(3));
1371 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1372 .map(|r| format!("-> {}", r))
1378 impl Rewrite for ast::Arg {
1379 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1380 if is_named_arg(self) {
1381 let mut result = try_opt!(self.pat.rewrite(context,
1382 Shape::legacy(shape.width, shape.indent)));
1384 if self.ty.node != ast::TyKind::Infer {
1385 if context.config.space_before_type_annotation() {
1386 result.push_str(" ");
1388 result.push_str(":");
1389 if context.config.space_after_type_annotation_colon() {
1390 result.push_str(" ");
1392 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1393 let ty_str = try_opt!(self.ty.rewrite(context,
1394 Shape::legacy(max_width,
1395 shape.indent + result.len())));
1396 result.push_str(&ty_str);
1401 self.ty.rewrite(context, shape)
1406 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1408 context: &RewriteContext)
1410 match explicit_self.node {
1411 ast::SelfKind::Region(lt, m) => {
1412 let mut_str = format_mutability(m);
1415 let lifetime_str = try_opt!(l.rewrite(context,
1416 Shape::legacy(usize::max_value(),
1418 Some(format!("&{} {}self", lifetime_str, mut_str))
1420 None => Some(format!("&{}self", mut_str)),
1423 ast::SelfKind::Explicit(ref ty, _) => {
1424 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1426 let mutability = explicit_self_mutability(&args[0]);
1427 let type_str = try_opt!(ty.rewrite(context,
1428 Shape::legacy(usize::max_value(), Indent::empty())));
1430 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1432 ast::SelfKind::Value(_) => {
1433 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1435 let mutability = explicit_self_mutability(&args[0]);
1437 Some(format!("{}self", format_mutability(mutability)))
1442 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1443 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1444 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1445 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1452 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1453 if is_named_arg(arg) {
1460 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1462 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1463 _ => arg.ty.span.hi,
1467 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1468 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1469 ident.node != symbol::keywords::Invalid.ident()
1475 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1477 ast::FunctionRetTy::Default(ref span) => span.clone(),
1478 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1482 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1483 // Note that ty.span is the span for ty.ident, not the whole item.
1484 let lo = ty.span.lo;
1485 if let Some(ref def) = ty.default {
1486 return mk_sp(lo, def.span.hi);
1488 if ty.bounds.is_empty() {
1491 let hi = match ty.bounds[ty.bounds.len() - 1] {
1492 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1493 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1498 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1500 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1501 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1502 ast::WherePredicate::EqPredicate(ref p) => p.span,
1506 // Return type is (result, force_new_line_for_brace)
1507 fn rewrite_fn_base(context: &RewriteContext,
1511 generics: &ast::Generics,
1512 unsafety: ast::Unsafety,
1513 constness: ast::Constness,
1514 defaultness: ast::Defaultness,
1516 vis: &ast::Visibility,
1518 newline_brace: bool,
1521 -> Option<(String, bool)> {
1522 let mut force_new_line_for_brace = false;
1524 let where_clause = &generics.where_clause;
1526 let mut result = String::with_capacity(1024);
1527 // Vis unsafety abi.
1528 result.push_str(&*format_visibility(vis));
1530 if let ast::Defaultness::Default = defaultness {
1531 result.push_str("default ");
1534 if let ast::Constness::Const = constness {
1535 result.push_str("const ");
1538 result.push_str(::utils::format_unsafety(unsafety));
1540 if abi != abi::Abi::Rust {
1541 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi()));
1545 result.push_str("fn ");
1546 result.push_str(&ident.to_string());
1549 let generics_indent = indent + last_line_width(&result);
1550 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1551 let shape = Shape::indented(generics_indent, context.config);
1552 let generics_str = try_opt!(rewrite_generics(context, generics, shape, generics_span));
1553 result.push_str(&generics_str);
1555 let snuggle_angle_bracket = last_line_width(&generics_str) == 1;
1557 // Note that the width and indent don't really matter, we'll re-layout the
1558 // return type later anyway.
1559 let ret_str = try_opt!(fd.output
1560 .rewrite(&context, Shape::indented(indent, context.config)));
1562 let multi_line_ret_str = ret_str.contains('\n');
1563 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1566 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1567 try_opt!(compute_budgets_for_args(context,
1574 if context.config.fn_args_layout() == IndentStyle::Block {
1575 arg_indent = indent.block_indent(context.config);
1576 multi_line_budget = context.config.max_width() - arg_indent.width();
1579 debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1584 // Check if vertical layout was forced.
1585 if one_line_budget == 0 {
1586 if snuggle_angle_bracket {
1587 result.push_str("(");
1588 } else if context.config.fn_args_paren_newline() {
1590 result.push_str(&arg_indent.to_string(context.config));
1591 arg_indent = arg_indent + 1; // extra space for `(`
1593 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1597 result.push_str("(\n");
1598 result.push_str(&arg_indent.to_string(context.config));
1602 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1607 if multi_line_ret_str {
1608 one_line_budget = 0;
1611 // A conservative estimation, to goal is to be over all parens in generics
1612 let args_start = generics
1615 .map_or(span.lo, |tp| end_typaram(tp));
1616 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1617 span_for_return(&fd.output).lo);
1618 let arg_str = try_opt!(rewrite_args(context,
1620 fd.get_self().as_ref(),
1627 generics_str.contains('\n')));
1629 let multi_line_arg_str = arg_str.contains('\n') ||
1630 arg_str.chars().last().map_or(false, |c| c == ',');
1632 let put_args_in_block = match context.config.fn_args_layout() {
1633 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1635 } && !fd.inputs.is_empty();
1637 if put_args_in_block {
1638 arg_indent = indent.block_indent(context.config);
1640 result.push_str(&arg_indent.to_string(context.config));
1641 result.push_str(&arg_str);
1643 result.push_str(&indent.to_string(context.config));
1646 result.push_str(&arg_str);
1647 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1654 if !ret_str.is_empty() {
1655 let ret_should_indent = match context.config.fn_args_layout() {
1656 // If our args are block layout then we surely must have space.
1657 IndentStyle::Block if put_args_in_block => false,
1659 // If we've already gone multi-line, or the return type would push over the max
1660 // width, then put the return type on a new line. With the +1 for the signature
1661 // length an additional space between the closing parenthesis of the argument and
1662 // the arrow '->' is considered.
1663 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1665 // If there is no where clause, take into account the space after the return type
1667 if where_clause.predicates.is_empty() {
1671 let overlong_sig = sig_length > context.config.max_width();
1673 result.contains('\n') || multi_line_ret_str || overlong_sig
1676 let ret_indent = if ret_should_indent {
1677 let indent = match context.config.fn_return_indent() {
1678 ReturnIndent::WithWhereClause => indent + 4,
1679 // Aligning with non-existent args looks silly.
1680 _ if arg_str.is_empty() => {
1681 force_new_line_for_brace = true;
1684 // FIXME: we might want to check that using the arg indent
1685 // doesn't blow our budget, and if it does, then fallback to
1686 // the where clause indent.
1691 result.push_str(&indent.to_string(context.config));
1695 Indent::new(indent.width(), result.len())
1698 if multi_line_ret_str || ret_should_indent {
1699 // Now that we know the proper indent and width, we need to
1700 // re-layout the return type.
1701 let ret_str = try_opt!(fd.output.rewrite(context,
1702 Shape::indented(ret_indent, context.config)));
1703 result.push_str(&ret_str);
1705 result.push_str(&ret_str);
1708 // Comment between return type and the end of the decl.
1709 let snippet_lo = fd.output.span().hi;
1710 if where_clause.predicates.is_empty() {
1711 let snippet_hi = span.hi;
1712 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1713 let snippet = snippet.trim();
1714 if !snippet.is_empty() {
1716 result.push_str(snippet);
1719 // FIXME it would be nice to catch comments between the return type
1720 // and the where clause, but we don't have a span for the where
1725 let should_compress_where = match context.config.where_density() {
1726 Density::Compressed => !result.contains('\n') || put_args_in_block,
1727 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1729 } || (put_args_in_block && ret_str.is_empty());
1731 if where_clause.predicates.len() == 1 && should_compress_where {
1732 let budget = try_opt!(context
1735 .checked_sub(last_line_width(&result)));
1736 if let Some(where_clause_str) =
1737 rewrite_where_clause(context,
1739 context.config.fn_brace_style(),
1740 Shape::legacy(budget, indent),
1741 Density::Compressed,
1744 put_args_in_block && ret_str.is_empty(),
1746 if !where_clause_str.contains('\n') {
1747 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
1751 result.push_str(&where_clause_str);
1753 return Some((result, force_new_line_for_brace));
1758 let where_clause_str = try_opt!(rewrite_where_clause(context,
1760 context.config.fn_brace_style(),
1761 Shape::indented(indent, context.config),
1765 put_args_in_block && ret_str.is_empty(),
1768 result.push_str(&where_clause_str);
1770 Some((result, force_new_line_for_brace))
1773 fn rewrite_args(context: &RewriteContext,
1775 explicit_self: Option<&ast::ExplicitSelf>,
1776 one_line_budget: usize,
1777 multi_line_budget: usize,
1782 generics_str_contains_newline: bool)
1784 let mut arg_item_strs =
1785 try_opt!(args.iter()
1786 .map(|arg| arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent)))
1787 .collect::<Option<Vec<_>>>());
1789 // Account for sugary self.
1790 // FIXME: the comment for the self argument is dropped. This is blocked
1791 // on rust issue #27522.
1792 let min_args = explicit_self
1793 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1794 .map_or(1, |self_str| {
1795 arg_item_strs[0] = self_str;
1799 // Comments between args.
1800 let mut arg_items = Vec::new();
1802 arg_items.push(ListItem::from_str(""));
1805 // FIXME(#21): if there are no args, there might still be a comment, but
1806 // without spans for the comment or parens, there is no chance of
1807 // getting it right. You also don't get to put a comment on self, unless
1809 if args.len() >= min_args || variadic {
1810 let comment_span_start = if min_args == 2 {
1811 let second_arg_start = if arg_has_pattern(&args[1]) {
1816 let reduced_span = mk_sp(span.lo, second_arg_start);
1818 context.codemap.span_after_last(reduced_span, ",")
1823 enum ArgumentKind<'a> {
1824 Regular(&'a ast::Arg),
1828 let variadic_arg = if variadic {
1829 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1830 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1831 Some(ArgumentKind::Variadic(variadic_start))
1836 let more_items = itemize_list(context.codemap,
1837 args[min_args - 1..]
1839 .map(ArgumentKind::Regular)
1840 .chain(variadic_arg),
1843 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1844 ArgumentKind::Variadic(start) => start,
1847 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1848 ArgumentKind::Variadic(start) => start + BytePos(3),
1851 ArgumentKind::Regular(..) => None,
1852 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1857 arg_items.extend(more_items);
1860 let fits_in_one_line = !generics_str_contains_newline &&
1861 (arg_items.len() == 0 ||
1862 arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
1864 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1865 item.item = Some(arg);
1868 let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout() {
1869 IndentStyle::Block if fits_in_one_line => {
1870 (indent.block_indent(context.config), SeparatorTactic::Never, true)
1872 IndentStyle::Block => {
1873 (indent.block_indent(context.config), SeparatorTactic::Vertical, true)
1875 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never, false),
1878 let tactic = definitive_tactic(&arg_items,
1879 context.config.fn_args_density().to_list_tactic(),
1881 let budget = match tactic {
1882 DefinitiveListTactic::Horizontal => one_line_budget,
1883 _ => multi_line_budget,
1886 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1888 let fmt = ListFormatting {
1891 trailing_separator: trailing_comma,
1892 shape: Shape::legacy(budget, indent),
1893 ends_with_newline: end_with_newline,
1894 config: context.config,
1897 write_list(&arg_items, &fmt)
1900 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1901 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1902 ident.node != symbol::keywords::Invalid.ident()
1908 fn compute_budgets_for_args(context: &RewriteContext,
1912 newline_brace: bool,
1914 -> Option<((usize, usize, Indent))> {
1915 debug!("compute_budgets_for_args {} {:?}, {}, {}",
1920 // Try keeping everything on the same line.
1921 if !result.contains('\n') {
1922 // 2 = `()`, 3 = `() `, space is before ret_string.
1923 let overhead = if ret_str_len == 0 { 2 } else { 3 };
1924 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
1934 let one_line_budget = context
1937 .checked_sub(used_space)
1940 if one_line_budget > 0 {
1942 let multi_line_budget = try_opt!(context
1945 .checked_sub(indent.width() + result.len() + 4));
1947 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1951 // Didn't work. we must force vertical layout and put args on a newline.
1952 let new_indent = indent.block_indent(context.config);
1953 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1954 let max_space = context.config.max_width();
1955 if used_space <= max_space {
1956 Some((0, max_space - used_space, new_indent))
1958 // Whoops! bankrupt.
1963 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1964 match config.fn_brace_style() {
1965 BraceStyle::AlwaysNextLine => true,
1966 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1971 fn rewrite_generics(context: &RewriteContext,
1972 generics: &ast::Generics,
1976 // FIXME: convert bounds to where clauses where they get too big or if
1977 // there is a where clause at all.
1978 let lifetimes: &[_] = &generics.lifetimes;
1979 let tys: &[_] = &generics.ty_params;
1980 if lifetimes.is_empty() && tys.is_empty() {
1981 return Some(String::new());
1984 let offset = match context.config.generics_indent() {
1985 IndentStyle::Block => shape.indent.block_only().block_indent(context.config),
1987 IndentStyle::Visual => shape.indent + 1,
1990 let h_budget = try_opt!(shape.width.checked_sub(2));
1991 // FIXME: might need to insert a newline if the generics are really long.
1993 // Strings for the generics.
1994 let lt_strs = lifetimes
1996 .map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1997 let ty_strs = tys.iter()
1998 .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
2000 // Extract comments between generics.
2001 let lt_spans = lifetimes.iter().map(|l| {
2002 let hi = if l.bounds.is_empty() {
2005 l.bounds[l.bounds.len() - 1].span.hi
2007 mk_sp(l.lifetime.span.lo, hi)
2009 let ty_spans = tys.iter().map(span_for_ty_param);
2011 let items = itemize_list(context.codemap,
2012 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2016 // FIXME: don't clone
2017 |&(_, ref str)| str.clone(),
2018 context.codemap.span_after(span, "<"),
2021 try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
2023 let result = if context.config.generics_indent() != IndentStyle::Visual &&
2024 list_str.contains('\n') {
2025 format!("<\n{}{}\n{}>",
2026 offset.to_string(context.config),
2028 shape.indent.block_only().to_string(context.config))
2029 } else if context.config.spaces_within_angle_brackets() {
2030 format!("< {} >", list_str)
2032 format!("<{}>", list_str)
2037 fn rewrite_trait_bounds(context: &RewriteContext,
2038 type_param_bounds: &ast::TyParamBounds,
2041 let bounds: &[_] = type_param_bounds;
2043 if bounds.is_empty() {
2044 return Some(String::new());
2046 let joiner = match context.config.type_punctuation_density() {
2047 TypeDensity::Compressed => "+",
2048 TypeDensity::Wide => " + ",
2050 let bound_str = try_opt!(bounds
2052 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2053 .collect::<Option<Vec<_>>>())
2056 let mut result = String::new();
2057 result.push_str(": ");
2058 result.push_str(&bound_str);
2062 fn rewrite_where_clause_rfc_style(context: &RewriteContext,
2063 where_clause: &ast::WhereClause,
2066 suppress_comma: bool,
2067 // where clause can be kept on the current line.
2069 span_end: Option<BytePos>)
2071 let block_shape = shape.block();
2073 let starting_newline = if snuggle {
2076 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2079 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2080 // each clause on one line, trailing comma (except if suppress_comma)
2081 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2082 // If we don't have the start of the next span, then use the end of the
2083 // predicates, but that means we miss comments.
2084 let len = where_clause.predicates.len();
2085 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2086 let span_end = span_end.unwrap_or(end_of_preds);
2087 let items = itemize_list(context.codemap,
2088 where_clause.predicates.iter(),
2090 |pred| span_for_where_pred(pred).lo,
2091 |pred| span_for_where_pred(pred).hi,
2092 |pred| pred.rewrite(context, clause_shape),
2095 let comma_tactic = if suppress_comma {
2096 SeparatorTactic::Never
2098 SeparatorTactic::Always
2101 let fmt = ListFormatting {
2102 tactic: DefinitiveListTactic::Vertical,
2104 trailing_separator: comma_tactic,
2105 shape: clause_shape,
2106 ends_with_newline: true,
2107 config: context.config,
2109 let preds_str = try_opt!(write_list(items, &fmt));
2111 Some(format!("{}where\n{}{}",
2113 clause_shape.indent.to_string(context.config),
2117 fn rewrite_where_clause(context: &RewriteContext,
2118 where_clause: &ast::WhereClause,
2119 brace_style: BraceStyle,
2123 suppress_comma: bool,
2125 span_end: Option<BytePos>)
2127 if where_clause.predicates.is_empty() {
2128 return Some(String::new());
2131 if context.config.where_style() == Style::Rfc {
2132 return rewrite_where_clause_rfc_style(context,
2141 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2143 let offset = match context.config.where_pred_indent() {
2144 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2145 // 6 = "where ".len()
2146 IndentStyle::Visual => shape.indent + extra_indent + 6,
2148 // FIXME: if where_pred_indent != Visual, then the budgets below might
2149 // be out by a char or two.
2151 let budget = context.config.max_width() - offset.width();
2152 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2153 // If we don't have the start of the next span, then use the end of the
2154 // predicates, but that means we miss comments.
2155 let len = where_clause.predicates.len();
2156 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2157 let span_end = span_end.unwrap_or(end_of_preds);
2158 let items = itemize_list(context.codemap,
2159 where_clause.predicates.iter(),
2161 |pred| span_for_where_pred(pred).lo,
2162 |pred| span_for_where_pred(pred).hi,
2163 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2166 let item_vec = items.collect::<Vec<_>>();
2167 // FIXME: we don't need to collect here if the where_layout isn't
2168 // HorizontalVertical.
2169 let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget);
2171 let mut comma_tactic = context.config.trailing_comma();
2172 // Kind of a hack because we don't usually have trailing commas in where clauses.
2173 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2174 comma_tactic = SeparatorTactic::Never;
2177 let fmt = ListFormatting {
2180 trailing_separator: comma_tactic,
2181 shape: Shape::legacy(budget, offset),
2182 ends_with_newline: true,
2183 config: context.config,
2185 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2187 let end_length = if terminator == "{" {
2188 // If the brace is on the next line we don't need to count it otherwise it needs two
2191 BraceStyle::AlwaysNextLine |
2192 BraceStyle::SameLineWhere => 0,
2193 BraceStyle::PreferSameLine => 2,
2195 } else if terminator == "=" {
2200 if density == Density::Tall || preds_str.contains('\n') ||
2201 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
2202 Some(format!("\n{}where {}",
2203 (shape.indent + extra_indent).to_string(context.config),
2206 Some(format!(" where {}", preds_str))
2210 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2211 format!("{}{}{}", format_visibility(vis), item_name, ident)
2214 fn format_generics(context: &RewriteContext,
2215 generics: &ast::Generics,
2218 brace_style: BraceStyle,
2219 force_same_line_brace: bool,
2223 let shape = Shape::indented(offset, context.config);
2224 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2226 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2227 let budget = try_opt!(context
2230 .checked_sub(last_line_width(&result)));
2231 let where_clause_str =
2232 try_opt!(rewrite_where_clause(context,
2233 &generics.where_clause,
2235 Shape::legacy(budget, offset.block_only()),
2239 trimmed_last_line_width(&result) == 1,
2241 result.push_str(&where_clause_str);
2242 let same_line_brace = force_same_line_brace ||
2243 (generics.where_clause.predicates.is_empty() &&
2244 trimmed_last_line_width(&result) == 1);
2245 if !same_line_brace &&
2246 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2248 result.push_str(&offset.block_only().to_string(context.config));
2252 result.push_str(opener);
2254 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2255 brace_style != BraceStyle::AlwaysNextLine {
2259 result.push_str(&offset.block_only().to_string(context.config));
2261 result.push_str(opener);