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, BlockIndentStyle, Density, ReturnIndent, BraceStyle, FnArgLayoutStyle, Style};
25 use itertools::Itertools;
27 use syntax::{ast, abi, codemap, ptr, symbol};
28 use syntax::codemap::{Span, BytePos, mk_sp};
29 use syntax::ast::ImplItem;
31 // Statements of the form
32 // let pat: ty = init;
33 impl Rewrite for ast::Local {
34 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
35 debug!("Local::rewrite {:?} {} {:?}",
39 let mut result = "let ".to_owned();
40 let pattern_offset = shape.indent + result.len();
42 let pattern_width = try_opt!(shape.width.checked_sub(pattern_offset.width() + 1));
44 let pat_str = try_opt!(self.pat.rewrite(&context,
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)
111 .map(|i| BodyElement::ForeignItem(i))
118 enum BodyElement<'a> {
119 // Stmt(&'a ast::Stmt),
120 // Field(&'a ast::Field),
121 // Variant(&'a ast::Variant),
122 // Item(&'a ast::Item),
123 ForeignItem(&'a ast::ForeignItem),
126 impl<'a> FmtVisitor<'a> {
127 fn format_item(&mut self, item: Item) {
128 self.buffer.push_str(&item.abi);
129 self.buffer.push_str(" ");
131 let snippet = self.snippet(item.span);
132 let brace_pos = snippet.find_uncommented("{").unwrap();
134 self.buffer.push_str("{");
135 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
136 // FIXME: this skips comments between the extern keyword and the opening
138 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
139 self.block_indent = self.block_indent.block_indent(self.config);
141 if item.body.is_empty() {
142 self.format_missing_no_indent(item.span.hi - BytePos(1));
143 self.block_indent = self.block_indent.block_unindent(self.config);
145 self.buffer.push_str(&self.block_indent.to_string(self.config));
147 for item in &item.body {
148 self.format_body_element(item);
151 self.block_indent = self.block_indent.block_unindent(self.config);
152 self.format_missing_with_indent(item.span.hi - BytePos(1));
156 self.buffer.push_str("}");
157 self.last_pos = item.span.hi;
160 fn format_body_element(&mut self, element: &BodyElement) {
162 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
166 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
167 let item = Item::from_foreign_mod(fm, span, self.config);
168 self.format_item(item);
171 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
172 self.format_missing_with_indent(item.span.lo);
173 // Drop semicolon or it will be interpreted as comment.
174 // FIXME: this may be a faulty span from libsyntax.
175 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
178 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
179 let indent = self.block_indent;
180 let rewrite = rewrite_fn_base(&self.get_context(),
185 ast::Unsafety::Normal,
186 ast::Constness::NotConst,
187 ast::Defaultness::Final,
188 // These are not actually rust functions,
189 // but we format them as such.
198 Some((new_fn, _)) => {
199 self.buffer.push_str(&new_fn);
200 self.buffer.push_str(";");
202 None => self.format_missing(item.span.hi),
205 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
206 // FIXME(#21): we're dropping potential comments in between the
207 // function keywords here.
208 let vis = format_visibility(&item.vis);
209 let mut_str = if is_mutable { "mut " } else { "" };
210 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
211 let offset = self.block_indent + prefix.len();
213 let width = self.config.max_width - offset.width() - 1;
214 let rewrite = ty.rewrite(&self.get_context(), Shape::legacy(width, offset));
218 self.buffer.push_str(&prefix);
219 self.buffer.push_str(&result);
220 self.buffer.push_str(";");
222 None => self.format_missing(item.span.hi),
227 self.last_pos = item.span.hi;
230 pub fn rewrite_fn(&mut self,
234 generics: &ast::Generics,
235 unsafety: ast::Unsafety,
236 constness: ast::Constness,
237 defaultness: ast::Defaultness,
239 vis: &ast::Visibility,
243 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
244 let context = self.get_context();
246 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
247 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
248 !context.config.fn_empty_single_line;
250 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
265 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
266 newline_brace = false;
267 } else if force_newline_brace {
268 newline_brace = true;
271 // Prepare for the function body by possibly adding a newline and
273 // FIXME we'll miss anything between the end of the signature and the
274 // start of the body, but we need more spans from the compiler to solve
278 result.push_str(&indent.to_string(self.config));
283 self.single_line_fn(&result, block).or_else(|| Some(result))
286 pub fn rewrite_required_fn(&mut self,
289 sig: &ast::MethodSig,
292 // Drop semicolon or it will be interpreted as comment.
293 let span = mk_sp(span.lo, span.hi - BytePos(1));
294 let context = self.get_context();
296 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
303 ast::Defaultness::Final,
305 &ast::Visibility::Inherited,
311 // Re-attach semicolon
317 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
318 if fn_str.contains('\n') {
322 let codemap = self.get_context().codemap;
324 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
325 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
326 return Some(format!("{}{{}}", fn_str));
329 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
331 if let Some(ref stmt) = block.stmts.first() {
332 match stmt_expr(stmt) {
334 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
336 e.rewrite(&self.get_context(),
337 Shape::legacy(self.config.max_width -
338 self.block_indent.width(),
341 .or_else(|| Some(self.snippet(e.span)))
344 stmt.rewrite(&self.get_context(),
345 Shape::legacy(self.config.max_width -
346 self.block_indent.width(),
355 if let Some(res) = rewrite {
356 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
357 if !res.contains('\n') && width <= self.config.max_width {
358 return Some(format!("{}{{ {} }}", fn_str, res));
366 pub fn visit_enum(&mut self,
368 vis: &ast::Visibility,
369 enum_def: &ast::EnumDef,
370 generics: &ast::Generics,
372 self.buffer.push_str(&format_header("enum ", ident, vis));
374 let enum_snippet = self.snippet(span);
375 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
376 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
377 let generics_str = format_generics(&self.get_context(),
381 self.config.item_brace_style,
382 enum_def.variants.is_empty(),
384 self.block_indent.block_indent(self.config),
385 mk_sp(span.lo, body_start))
387 self.buffer.push_str(&generics_str);
389 self.last_pos = body_start;
391 self.block_indent = self.block_indent.block_indent(self.config);
392 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
394 Some(ref body_str) => self.buffer.push_str(body_str),
396 if contains_comment(&enum_snippet[brace_pos..]) {
397 self.format_missing_no_indent(span.hi - BytePos(1))
399 self.format_missing(span.hi - BytePos(1))
403 self.block_indent = self.block_indent.block_unindent(self.config);
405 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
406 self.buffer.push_str(&self.block_indent.to_string(self.config));
408 self.buffer.push_str("}");
409 self.last_pos = span.hi;
412 // Format the body of an enum definition
413 fn format_variant_list(&self,
414 enum_def: &ast::EnumDef,
418 if enum_def.variants.is_empty() {
421 let mut result = String::with_capacity(1024);
423 let indentation = self.block_indent.to_string(self.config);
424 result.push_str(&indentation);
426 let items = itemize_list(self.codemap,
427 enum_def.variants.iter(),
429 |f| if !f.node.attrs.is_empty() {
430 f.node.attrs[0].span.lo
435 |f| self.format_variant(f),
439 let budget = self.config.max_width - self.block_indent.width() - 2;
440 let fmt = ListFormatting {
441 tactic: DefinitiveListTactic::Vertical,
443 trailing_separator: self.config.trailing_comma,
444 shape: Shape::legacy(budget, self.block_indent),
445 ends_with_newline: true,
449 let list = try_opt!(write_list(items, &fmt));
450 result.push_str(&list);
455 // Variant of an enum.
456 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
457 if contains_skip(&field.node.attrs) {
458 let lo = field.node.attrs[0].span.lo;
459 let span = mk_sp(lo, field.span.hi);
460 return Some(self.snippet(span));
463 let indent = self.block_indent;
464 let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
465 Shape::legacy(self.config.max_width -
468 if !result.is_empty() {
470 result.push_str(&indent.to_string(self.config));
473 let context = self.get_context();
474 let variant_body = match field.node.data {
475 ast::VariantData::Tuple(..) |
476 ast::VariantData::Struct(..) => {
477 // FIXME: Should limit the width, as we have a trailing comma
478 format_struct(&context,
481 &ast::Visibility::Inherited,
486 Some(self.config.struct_variant_width))
488 ast::VariantData::Unit(..) => {
489 let tag = if let Some(ref expr) = field.node.disr_expr {
490 format!("{} = {}", field.node.name, self.snippet(expr.span))
492 field.node.name.to_string()
496 self.config.max_width,
497 Shape::legacy(self.config.max_width - indent.width(), indent))
501 if let Some(variant_str) = variant_body {
502 result.push_str(&variant_str);
510 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
511 if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
512 let mut result = String::new();
513 // First try to format the ref and type without a split at the 'for'.
514 let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
516 // If there is a line break present in the first result format it again
517 // with a split at the 'for'. Skip this if there is no trait ref and
518 // therefore no 'for'.
519 if ref_and_type.contains('\n') && trait_ref.is_some() {
520 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
522 result.push_str(&ref_and_type);
524 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
525 let where_clause_str = try_opt!(rewrite_where_clause(context,
526 &generics.where_clause,
527 context.config.item_brace_style,
528 Shape::legacy(where_budget,
529 offset.block_only()),
530 context.config.where_density,
533 last_line_width(&ref_and_type) == 1,
536 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
537 result.push_str(&where_clause_str);
538 if where_clause_str.contains('\n') {
539 let white_space = offset.to_string(context.config);
540 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
542 result.push_str(" {}");
547 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
549 let width = offset.block_indent + context.config.tab_spaces - 1;
550 let where_indent = Indent::new(0, width);
551 result.push_str(&where_indent.to_string(context.config));
553 result.push_str(&where_clause_str);
555 match context.config.item_brace_style {
556 BraceStyle::AlwaysNextLine => {
558 result.push_str(&offset.to_string(context.config));
560 BraceStyle::PreferSameLine => result.push(' '),
561 BraceStyle::SameLineWhere => {
562 if !where_clause_str.is_empty() {
564 result.push_str(&offset.to_string(context.config));
573 let snippet = context.snippet(item.span);
574 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
576 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
577 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
578 visitor.block_indent = offset.block_only().block_indent(context.config);
579 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
582 visitor.visit_impl_item(item);
585 visitor.format_missing(item.span.hi - BytePos(1));
587 let inner_indent_str = visitor.block_indent.to_string(context.config);
588 let outer_indent_str = offset.block_only().to_string(context.config);
591 result.push_str(&inner_indent_str);
592 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
594 result.push_str(&outer_indent_str);
597 if result.chars().last().unwrap() == '{' {
599 result.push_str(&offset.to_string(context.config));
609 fn is_impl_single_line(context: &RewriteContext,
612 where_clause_str: &str,
615 let snippet = context.snippet(item.span);
616 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
618 Some(context.config.impl_empty_single_line && items.is_empty() &&
619 result.len() + where_clause_str.len() <= context.config.max_width &&
620 !contains_comment(&snippet[open_pos..]))
623 fn format_impl_ref_and_type(context: &RewriteContext,
628 if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
630 let mut result = String::new();
632 result.push_str(&format_visibility(&item.vis));
633 result.push_str(format_unsafety(unsafety));
634 result.push_str("impl");
636 let lo = context.codemap.span_after(item.span, "impl");
637 let hi = match *trait_ref {
638 Some(ref tr) => tr.path.span.lo,
639 None => self_ty.span.lo,
641 let generics_str = try_opt!(rewrite_generics(context,
643 Shape::legacy(context.config.max_width,
645 offset + result.len(),
647 result.push_str(&generics_str);
649 if polarity == ast::ImplPolarity::Negative {
650 result.push_str(" !");
652 if let Some(ref trait_ref) = *trait_ref {
653 if polarity != ast::ImplPolarity::Negative {
654 result.push_str(" ");
656 let used_space = last_line_width(&result);
657 let budget = try_opt!(context.config.max_width.checked_sub(used_space));
658 let indent = offset + used_space;
659 result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
664 // Add indentation of one additional tab.
665 let width = offset.block_indent + context.config.tab_spaces;
666 let for_indent = Indent::new(0, width);
667 result.push_str(&for_indent.to_string(context.config));
669 result.push_str("for");
671 result.push_str(" for");
675 let mut used_space = last_line_width(&result);
676 if generics.where_clause.predicates.is_empty() {
677 // If there is no where clause adapt budget for type formatting to take space and curly
678 // brace into account.
679 match context.config.item_brace_style {
680 BraceStyle::AlwaysNextLine => {}
681 BraceStyle::PreferSameLine => used_space += 2,
682 BraceStyle::SameLineWhere => used_space += 2,
686 // 1 = space before the type.
687 let budget = try_opt!(context.config.max_width.checked_sub(used_space + 1));
688 let indent = offset + result.len() + 1;
689 let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
690 if let Some(self_ty_str) = self_ty_str {
691 result.push_str(" ");
692 result.push_str(&self_ty_str);
696 // Can't fit the self type on what's left of the line, so start a new one.
697 let indent = offset.block_indent(context.config);
698 result.push_str(&format!("\n{}", indent.to_string(context.config)));
699 let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
700 result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
707 pub fn format_struct(context: &RewriteContext,
710 vis: &ast::Visibility,
711 struct_def: &ast::VariantData,
712 generics: Option<&ast::Generics>,
715 one_line_width: Option<usize>)
718 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
719 ast::VariantData::Tuple(ref fields, _) => {
720 format_tuple_struct(context,
729 ast::VariantData::Struct(ref fields, _) => {
730 format_struct_struct(context,
743 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
744 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
746 let mut result = String::new();
747 let header = format!("{}{}trait {}",
748 format_visibility(&item.vis),
749 format_unsafety(unsafety),
752 result.push_str(&header);
754 let body_lo = context.codemap.span_after(item.span, "{");
756 let generics_str = try_opt!(rewrite_generics(context,
758 Shape::legacy(context.config.max_width,
760 offset + result.len(),
761 mk_sp(item.span.lo, body_lo)));
762 result.push_str(&generics_str);
764 let trait_bound_str =
765 try_opt!(rewrite_trait_bounds(context,
767 Shape::legacy(context.config.max_width, offset)));
768 // If the trait, generics, and trait bound cannot fit on the same line,
769 // put the trait bounds on an indented new line
770 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
771 context.config.ideal_width {
773 let trait_indent = offset.block_only().block_indent(context.config);
774 result.push_str(&trait_indent.to_string(context.config));
776 result.push_str(&trait_bound_str);
778 let has_body = !trait_items.is_empty();
781 if (context.config.where_density == Density::Compressed &&
782 (!result.contains('\n') ||
783 context.config.fn_args_layout == FnArgLayoutStyle::Block)) ||
784 (context.config.fn_args_layout == FnArgLayoutStyle::Block && result.is_empty()) ||
785 (context.config.where_density == Density::CompressedIfEmpty && !has_body &&
786 !result.contains('\n')) {
792 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
793 let where_clause_str = try_opt!(rewrite_where_clause(context,
794 &generics.where_clause,
795 context.config.item_brace_style,
796 Shape::legacy(where_budget,
797 offset.block_only()),
801 trait_bound_str.is_empty() &&
802 last_line_width(&generics_str) == 1,
804 // If the where clause cannot fit on the same line,
805 // put the where clause on a new line
806 if !where_clause_str.contains('\n') &&
807 last_line_width(&result) + where_clause_str.len() + offset.width() >
808 context.config.ideal_width {
810 let width = offset.block_indent + context.config.tab_spaces - 1;
811 let where_indent = Indent::new(0, width);
812 result.push_str(&where_indent.to_string(context.config));
814 result.push_str(&where_clause_str);
816 match context.config.item_brace_style {
817 BraceStyle::AlwaysNextLine => {
819 result.push_str(&offset.to_string(context.config));
821 BraceStyle::PreferSameLine => result.push(' '),
822 BraceStyle::SameLineWhere => {
823 if !where_clause_str.is_empty() &&
824 (!trait_items.is_empty() || result.contains('\n')) {
826 result.push_str(&offset.to_string(context.config));
834 let snippet = context.snippet(item.span);
835 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
837 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
838 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
839 visitor.block_indent = offset.block_only().block_indent(context.config);
840 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
842 for item in trait_items {
843 visitor.visit_trait_item(item);
846 visitor.format_missing(item.span.hi - BytePos(1));
848 let inner_indent_str = visitor.block_indent.to_string(context.config);
849 let outer_indent_str = offset.block_only().to_string(context.config);
852 result.push_str(&inner_indent_str);
853 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
855 result.push_str(&outer_indent_str);
856 } else if result.contains('\n') {
867 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
868 format!("{};", format_header(item_name, ident, vis))
871 fn format_struct_struct(context: &RewriteContext,
874 vis: &ast::Visibility,
875 fields: &[ast::StructField],
876 generics: Option<&ast::Generics>,
879 one_line_width: Option<usize>)
881 let mut result = String::with_capacity(1024);
883 let header_str = format_header(item_name, ident, vis);
884 result.push_str(&header_str);
886 let body_lo = context.codemap.span_after(span, "{");
888 let generics_str = match generics {
890 try_opt!(format_generics(context,
894 context.config.item_brace_style,
897 offset + header_str.len(),
898 mk_sp(span.lo, body_lo)))
901 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
902 format!("\n{}{{", offset.block_only().to_string(context.config))
908 result.push_str(&generics_str);
910 // FIXME(#919): properly format empty structs and their comments.
911 if fields.is_empty() {
912 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
913 if snippet.trim().is_empty() {
915 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
917 result.push_str(&snippet.trim_right());
919 result.push_str(&offset.to_string(context.config));
921 result.push_str(&snippet);
927 let item_indent = offset.block_indent(context.config);
929 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
932 itemize_list(context.codemap,
936 // Include attributes and doc comments, if present
937 if !field.attrs.is_empty() {
938 field.attrs[0].span.lo
943 |field| field.ty.span.hi,
944 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
945 context.codemap.span_after(span, "{"),
947 .collect::<Vec<_>>();
949 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
951 let tactic = match one_line_width {
952 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
953 None => DefinitiveListTactic::Vertical,
956 let fmt = ListFormatting {
959 trailing_separator: context.config.trailing_comma,
960 shape: Shape::legacy(budget, item_indent),
961 ends_with_newline: true,
962 config: context.config,
964 let items_str = try_opt!(write_list(&items, &fmt));
965 if one_line_width.is_some() && !items_str.contains('\n') {
966 Some(format!("{} {} }}", result, items_str))
968 Some(format!("{}\n{}{}\n{}}}",
970 offset.block_indent(context.config).to_string(context.config),
972 offset.to_string(context.config)))
976 fn format_tuple_struct(context: &RewriteContext,
979 vis: &ast::Visibility,
980 fields: &[ast::StructField],
981 generics: Option<&ast::Generics>,
985 let mut result = String::with_capacity(1024);
987 let header_str = format_header(item_name, ident, vis);
988 result.push_str(&header_str);
990 // FIXME(#919): don't lose comments on empty tuple structs.
991 let body_lo = if fields.is_empty() {
997 let where_clause_str = match generics {
999 let generics_str = try_opt!(rewrite_generics(context,
1001 Shape::legacy(context.config.max_width,
1003 offset + header_str.len(),
1004 mk_sp(span.lo, body_lo)));
1005 result.push_str(&generics_str);
1008 try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1009 try_opt!(rewrite_where_clause(context,
1010 &generics.where_clause,
1011 context.config.item_brace_style,
1012 Shape::legacy(where_budget, offset.block_only()),
1013 Density::Compressed,
1019 None => "".to_owned(),
1022 let (tactic, item_indent) = match context.config.fn_args_layout {
1023 FnArgLayoutStyle::Visual => {
1025 (ListTactic::HorizontalVertical, offset.block_only() + result.len() + 1)
1027 FnArgLayoutStyle::Block |
1028 FnArgLayoutStyle::BlockAlways => {
1029 (ListTactic::HorizontalVertical, offset.block_only().block_indent(&context.config))
1033 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 3));
1036 itemize_list(context.codemap,
1040 // Include attributes and doc comments, if present
1041 if !field.attrs.is_empty() {
1042 field.attrs[0].span.lo
1047 |field| field.ty.span.hi,
1048 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1049 context.codemap.span_after(span, "("),
1051 let body_budget = try_opt!(context.config.max_width.checked_sub(offset.block_only().width() +
1054 let body = try_opt!(list_helper(items,
1055 // TODO budget is wrong in block case
1056 Shape::legacy(body_budget, item_indent),
1060 if context.config.fn_args_layout == FnArgLayoutStyle::Visual || !body.contains('\n') {
1062 if context.config.spaces_within_parens && body.len() > 0 {
1066 result.push_str(&body);
1068 if context.config.spaces_within_parens && body.len() > 0 {
1073 result.push_str("(\n");
1074 result.push_str(&item_indent.to_string(&context.config));
1075 result.push_str(&body);
1077 result.push_str(&offset.block_only().to_string(&context.config));
1081 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1082 (result.contains('\n') ||
1083 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1084 context.config.max_width) {
1085 // We need to put the where clause on a new line, but we didn't
1086 // know that earlier, so the where clause will not be indented properly.
1088 result.push_str(&(offset.block_only() + (context.config.tab_spaces - 1))
1089 .to_string(context.config));
1091 result.push_str(&where_clause_str);
1096 pub fn rewrite_type_alias(context: &RewriteContext,
1100 generics: &ast::Generics,
1101 vis: &ast::Visibility,
1104 let mut result = String::new();
1106 result.push_str(&format_visibility(vis));
1107 result.push_str("type ");
1108 result.push_str(&ident.to_string());
1110 let generics_indent = indent + result.len();
1111 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1112 let generics_width = context.config.max_width - " =".len();
1113 let generics_str = try_opt!(rewrite_generics(context,
1115 Shape::legacy(generics_width, indent),
1119 result.push_str(&generics_str);
1121 let where_budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1122 let where_clause_str = try_opt!(rewrite_where_clause(context,
1123 &generics.where_clause,
1124 context.config.item_brace_style,
1125 Shape::legacy(where_budget, indent),
1126 context.config.where_density,
1131 result.push_str(&where_clause_str);
1132 result.push_str(" = ");
1134 let line_width = last_line_width(&result);
1135 // This checked_sub may fail as the extra space after '=' is not taken into account
1136 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1137 let budget = context.config
1139 .checked_sub(indent.width() + line_width + ";".len())
1141 let type_indent = indent + line_width;
1142 // Try to fit the type on the same line
1143 let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent)).or_else(|| {
1144 // The line was too short, try to put the type on the next line
1146 // Remove the space after '='
1148 let type_indent = indent.block_indent(context.config);
1150 result.push_str(&type_indent.to_string(context.config));
1151 let budget = try_opt!(context.config.max_width.checked_sub(type_indent.width() +
1153 ty.rewrite(context, Shape::legacy(budget, type_indent))
1155 result.push_str(&ty_str);
1156 result.push_str(";");
1160 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1161 (if config.space_before_type_annotation {
1166 if config.space_after_type_annotation_colon {
1173 impl Rewrite for ast::StructField {
1174 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1175 if contains_skip(&self.attrs) {
1176 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1177 return wrap_str(span, context.config.max_width, shape);
1180 let name = self.ident;
1181 let vis = format_visibility(&self.vis);
1182 let mut attr_str = try_opt!(self.attrs.rewrite(context,
1183 Shape::legacy(context.config.max_width -
1184 shape.indent.width(),
1186 if !attr_str.is_empty() {
1187 attr_str.push('\n');
1188 attr_str.push_str(&shape.indent.to_string(context.config));
1191 let type_annotation_spacing = type_annotation_spacing(context.config);
1192 let result = match name {
1194 format!("{}{}{}{}:{}",
1198 type_annotation_spacing.0,
1199 type_annotation_spacing.1)
1201 None => format!("{}{}", attr_str, vis),
1204 let last_line_width = last_line_width(&result);
1205 let budget = try_opt!(shape.width.checked_sub(last_line_width));
1206 let rewrite = try_opt!(self.ty.rewrite(context,
1207 Shape::legacy(budget,
1208 shape.indent + last_line_width)));
1209 Some(result + &rewrite)
1213 pub fn rewrite_static(prefix: &str,
1214 vis: &ast::Visibility,
1217 mutability: ast::Mutability,
1218 expr_opt: Option<&ptr::P<ast::Expr>>,
1220 context: &RewriteContext)
1222 let type_annotation_spacing = type_annotation_spacing(context.config);
1223 let prefix = format!("{}{} {}{}{}:{}",
1224 format_visibility(vis),
1226 format_mutability(mutability),
1228 type_annotation_spacing.0,
1229 type_annotation_spacing.1);
1231 let ty_str = try_opt!(ty.rewrite(context,
1232 Shape::legacy(context.config.max_width - offset.block_indent -
1235 offset.block_only())));
1237 if let Some(expr) = expr_opt {
1238 let lhs = format!("{}{} =", prefix, ty_str);
1240 let remaining_width = context.config.max_width - offset.block_indent - 1;
1241 rewrite_assign_rhs(context,
1244 Shape::legacy(remaining_width, offset.block_only()))
1247 let lhs = format!("{}{};", prefix, ty_str);
1252 pub fn rewrite_associated_type(ident: ast::Ident,
1253 ty_opt: Option<&ptr::P<ast::Ty>>,
1254 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1255 context: &RewriteContext,
1258 let prefix = format!("type {}", ident);
1260 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1261 let bounds: &[_] = ty_param_bounds;
1262 let bound_str = try_opt!(bounds.iter()
1264 ty_bound.rewrite(context, Shape::legacy(context.config.max_width, indent))
1266 .intersperse(Some(" + ".to_string()))
1267 .collect::<Option<String>>());
1268 if bounds.len() > 0 {
1269 format!(": {}", bound_str)
1277 if let Some(ty) = ty_opt {
1278 let ty_str = try_opt!(ty.rewrite(context,
1279 Shape::legacy(context.config.max_width -
1280 indent.block_indent -
1283 indent.block_only())));
1284 Some(format!("{} = {};", prefix, ty_str))
1286 Some(format!("{}{};", prefix, type_bounds_str))
1290 pub fn rewrite_associated_impl_type(ident: ast::Ident,
1291 defaultness: ast::Defaultness,
1292 ty_opt: Option<&ptr::P<ast::Ty>>,
1293 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1294 context: &RewriteContext,
1298 try_opt!(rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent));
1301 ast::Defaultness::Default => Some(format!("default {}", result)),
1306 impl Rewrite for ast::FunctionRetTy {
1307 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1309 ast::FunctionRetTy::Default(_) => Some(String::new()),
1310 ast::FunctionRetTy::Ty(ref ty) => {
1311 let inner_width = try_opt!(shape.width.checked_sub(3));
1312 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3)).map(|r| {
1320 impl Rewrite for ast::Arg {
1321 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1322 if is_named_arg(self) {
1323 let mut result = try_opt!(self.pat.rewrite(context,
1324 Shape::legacy(shape.width, shape.indent)));
1326 if self.ty.node != ast::TyKind::Infer {
1327 if context.config.space_before_type_annotation {
1328 result.push_str(" ");
1330 result.push_str(":");
1331 if context.config.space_after_type_annotation_colon {
1332 result.push_str(" ");
1334 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1335 let ty_str = try_opt!(self.ty.rewrite(context,
1336 Shape::legacy(max_width,
1337 shape.indent + result.len())));
1338 result.push_str(&ty_str);
1343 self.ty.rewrite(context, shape)
1348 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf,
1350 context: &RewriteContext)
1352 match explicit_self.node {
1353 ast::SelfKind::Region(lt, m) => {
1354 let mut_str = format_mutability(m);
1357 let lifetime_str = try_opt!(l.rewrite(context,
1358 Shape::legacy(usize::max_value(),
1360 Some(format!("&{} {}self", lifetime_str, mut_str))
1362 None => Some(format!("&{}self", mut_str)),
1365 ast::SelfKind::Explicit(ref ty, _) => {
1366 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1368 let mutability = explicit_self_mutability(&args[0]);
1369 let type_str = try_opt!(ty.rewrite(context,
1370 Shape::legacy(usize::max_value(), Indent::empty())));
1372 Some(format!("{}self: {}", format_mutability(mutability), type_str))
1374 ast::SelfKind::Value(_) => {
1375 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1377 let mutability = explicit_self_mutability(&args[0]);
1379 Some(format!("{}self", format_mutability(mutability)))
1384 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1385 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1386 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1387 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1394 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1395 if is_named_arg(arg) {
1402 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1404 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1405 _ => arg.ty.span.hi,
1409 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1410 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1411 ident.node != symbol::keywords::Invalid.ident()
1417 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1419 ast::FunctionRetTy::Default(ref span) => span.clone(),
1420 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1424 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1425 // Note that ty.span is the span for ty.ident, not the whole item.
1426 let lo = ty.span.lo;
1427 if let Some(ref def) = ty.default {
1428 return mk_sp(lo, def.span.hi);
1430 if ty.bounds.is_empty() {
1433 let hi = match ty.bounds[ty.bounds.len() - 1] {
1434 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1435 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1440 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1442 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1443 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1444 ast::WherePredicate::EqPredicate(ref p) => p.span,
1448 // Return type is (result, force_new_line_for_brace)
1449 fn rewrite_fn_base(context: &RewriteContext,
1453 generics: &ast::Generics,
1454 unsafety: ast::Unsafety,
1455 constness: ast::Constness,
1456 defaultness: ast::Defaultness,
1458 vis: &ast::Visibility,
1460 newline_brace: bool,
1463 -> Option<(String, bool)> {
1464 let mut force_new_line_for_brace = false;
1466 let where_clause = &generics.where_clause;
1468 let mut result = String::with_capacity(1024);
1469 // Vis unsafety abi.
1470 result.push_str(&*format_visibility(vis));
1472 if let ast::Defaultness::Default = defaultness {
1473 result.push_str("default ");
1476 if let ast::Constness::Const = constness {
1477 result.push_str("const ");
1480 result.push_str(::utils::format_unsafety(unsafety));
1482 if abi != abi::Abi::Rust {
1483 result.push_str(&::utils::format_abi(abi, context.config.force_explicit_abi));
1487 result.push_str("fn ");
1488 result.push_str(&ident.to_string());
1491 let generics_indent = indent + result.len();
1492 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1493 let generics_str = try_opt!(rewrite_generics(context,
1495 Shape::legacy(context.config.max_width, indent),
1498 result.push_str(&generics_str);
1500 let snuggle_angle_bracket = last_line_width(&generics_str) == 1;
1502 // Note that the width and indent don't really matter, we'll re-layout the
1503 // return type later anyway.
1504 let ret_str = try_opt!(fd.output.rewrite(&context,
1505 Shape::legacy(context.config.max_width -
1509 let multi_line_ret_str = ret_str.contains('\n');
1510 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1513 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1514 try_opt!(compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace));
1516 if context.config.fn_args_layout == FnArgLayoutStyle::Block ||
1517 context.config.fn_args_layout == FnArgLayoutStyle::BlockAlways {
1518 arg_indent = indent.block_indent(context.config);
1519 multi_line_budget = context.config.max_width - arg_indent.width();
1522 debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1527 // Check if vertical layout was forced.
1528 if one_line_budget == 0 {
1529 if snuggle_angle_bracket {
1530 result.push_str("(");
1531 } else if context.config.fn_args_paren_newline {
1533 result.push_str(&arg_indent.to_string(context.config));
1534 arg_indent = arg_indent + 1; // extra space for `(`
1536 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1540 result.push_str("(\n");
1541 result.push_str(&arg_indent.to_string(context.config));
1545 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1550 if multi_line_ret_str {
1551 one_line_budget = 0;
1554 // A conservative estimation, to goal is to be over all parens in generics
1555 let args_start = generics.ty_params.last().map_or(span.lo, |tp| end_typaram(tp));
1556 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1557 span_for_return(&fd.output).lo);
1558 let arg_str = try_opt!(rewrite_args(context,
1560 fd.get_self().as_ref(),
1568 let multi_line_arg_str = arg_str.contains('\n');
1570 let put_args_in_block = match context.config.fn_args_layout {
1571 FnArgLayoutStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1572 FnArgLayoutStyle::BlockAlways => true,
1574 } && !fd.inputs.is_empty();
1576 if put_args_in_block {
1577 arg_indent = indent.block_indent(context.config);
1579 result.push_str(&arg_indent.to_string(context.config));
1580 result.push_str(&arg_str);
1582 result.push_str(&indent.to_string(context.config));
1585 result.push_str(&arg_str);
1586 if context.config.spaces_within_parens && fd.inputs.len() > 0 {
1593 if !ret_str.is_empty() {
1594 let ret_should_indent = match context.config.fn_args_layout {
1595 // If our args are block layout then we surely must have space.
1596 FnArgLayoutStyle::Block if put_args_in_block => false,
1597 FnArgLayoutStyle::BlockAlways => false,
1599 // If we've already gone multi-line, or the return type would push over the max
1600 // width, then put the return type on a new line. With the +1 for the signature
1601 // length an additional space between the closing parenthesis of the argument and
1602 // the arrow '->' is considered.
1603 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1605 // If there is no where clause, take into account the space after the return type
1607 if where_clause.predicates.is_empty() {
1611 let overlong_sig = sig_length > context.config.max_width;
1613 result.contains('\n') || multi_line_ret_str || overlong_sig
1616 let ret_indent = if ret_should_indent {
1617 let indent = match context.config.fn_return_indent {
1618 ReturnIndent::WithWhereClause => indent + 4,
1619 // Aligning with non-existent args looks silly.
1620 _ if arg_str.is_empty() => {
1621 force_new_line_for_brace = true;
1624 // FIXME: we might want to check that using the arg indent
1625 // doesn't blow our budget, and if it does, then fallback to
1626 // the where clause indent.
1631 result.push_str(&indent.to_string(context.config));
1635 Indent::new(indent.width(), result.len())
1638 if multi_line_ret_str || ret_should_indent {
1639 // Now that we know the proper indent and width, we need to
1640 // re-layout the return type.
1641 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1642 let ret_str = try_opt!(fd.output.rewrite(context, Shape::legacy(budget, ret_indent)));
1643 result.push_str(&ret_str);
1645 result.push_str(&ret_str);
1648 // Comment between return type and the end of the decl.
1649 let snippet_lo = fd.output.span().hi;
1650 if where_clause.predicates.is_empty() {
1651 let snippet_hi = span.hi;
1652 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1653 let snippet = snippet.trim();
1654 if !snippet.is_empty() {
1656 result.push_str(snippet);
1659 // FIXME it would be nice to catch comments between the return type
1660 // and the where clause, but we don't have a span for the where
1665 let should_compress_where = match context.config.where_density {
1666 Density::Compressed => !result.contains('\n') || put_args_in_block,
1667 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1669 } || (put_args_in_block && ret_str.is_empty());
1671 if where_clause.predicates.len() == 1 && should_compress_where {
1672 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
1673 if let Some(where_clause_str) =
1674 rewrite_where_clause(context,
1676 context.config.fn_brace_style,
1677 Shape::legacy(budget, indent),
1678 Density::Compressed,
1681 put_args_in_block && ret_str.is_empty(),
1683 if !where_clause_str.contains('\n') {
1684 if last_line_width(&result) + where_clause_str.len() > context.config.max_width {
1688 result.push_str(&where_clause_str);
1690 return Some((result, force_new_line_for_brace));
1695 let budget = try_opt!(context.config.max_width.checked_sub(indent.block_indent));
1696 let where_clause_str = try_opt!(rewrite_where_clause(context,
1698 context.config.fn_brace_style,
1699 Shape::legacy(budget, indent),
1703 put_args_in_block && ret_str.is_empty(),
1706 result.push_str(&where_clause_str);
1708 Some((result, force_new_line_for_brace))
1711 fn rewrite_args(context: &RewriteContext,
1713 explicit_self: Option<&ast::ExplicitSelf>,
1714 one_line_budget: usize,
1715 multi_line_budget: usize,
1721 let mut arg_item_strs =
1722 try_opt!(args.iter()
1724 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
1726 .collect::<Option<Vec<_>>>());
1728 // Account for sugary self.
1729 // FIXME: the comment for the self argument is dropped. This is blocked
1730 // on rust issue #27522.
1732 explicit_self.and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1733 .map_or(1, |self_str| {
1734 arg_item_strs[0] = self_str;
1738 // Comments between args.
1739 let mut arg_items = Vec::new();
1741 arg_items.push(ListItem::from_str(""));
1744 // FIXME(#21): if there are no args, there might still be a comment, but
1745 // without spans for the comment or parens, there is no chance of
1746 // getting it right. You also don't get to put a comment on self, unless
1748 if args.len() >= min_args || variadic {
1749 let comment_span_start = if min_args == 2 {
1750 let second_arg_start = if arg_has_pattern(&args[1]) {
1755 let reduced_span = mk_sp(span.lo, second_arg_start);
1757 context.codemap.span_after_last(reduced_span, ",")
1762 enum ArgumentKind<'a> {
1763 Regular(&'a ast::Arg),
1767 let variadic_arg = if variadic {
1768 let variadic_span = mk_sp(args.last()
1774 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1775 Some(ArgumentKind::Variadic(variadic_start))
1780 let more_items = itemize_list(context.codemap,
1781 args[min_args - 1..]
1783 .map(ArgumentKind::Regular)
1784 .chain(variadic_arg),
1787 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1788 ArgumentKind::Variadic(start) => start,
1791 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1792 ArgumentKind::Variadic(start) => start + BytePos(3),
1795 ArgumentKind::Regular(..) => None,
1796 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1801 arg_items.extend(more_items);
1804 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1805 item.item = Some(arg);
1808 let indent = match context.config.fn_arg_indent {
1809 BlockIndentStyle::Inherit => indent,
1810 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1811 BlockIndentStyle::Visual => arg_indent,
1814 let tactic = definitive_tactic(&arg_items,
1815 context.config.fn_args_density.to_list_tactic(),
1817 let budget = match tactic {
1818 DefinitiveListTactic::Horizontal => one_line_budget,
1819 _ => multi_line_budget,
1822 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1824 let (trailing_comma, end_with_newline) = match context.config.fn_args_layout {
1825 FnArgLayoutStyle::Block => (SeparatorTactic::Vertical, true),
1826 FnArgLayoutStyle::BlockAlways => (SeparatorTactic::Always, true),
1827 _ => (SeparatorTactic::Never, false),
1830 let fmt = ListFormatting {
1833 trailing_separator: trailing_comma,
1834 shape: Shape::legacy(budget, indent),
1835 ends_with_newline: end_with_newline,
1836 config: context.config,
1839 write_list(&arg_items, &fmt)
1842 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1843 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1844 ident.node != symbol::keywords::Invalid.ident()
1850 fn compute_budgets_for_args(context: &RewriteContext,
1854 newline_brace: bool)
1855 -> Option<((usize, usize, Indent))> {
1856 debug!("compute_budgets_for_args {} {:?}, {}, {}",
1861 // Try keeping everything on the same line.
1862 if !result.contains('\n') {
1863 // 3 = `() `, space is before ret_string.
1864 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1868 let one_line_budget = context.config
1870 .checked_sub(used_space)
1873 if one_line_budget > 0 {
1875 let multi_line_budget =
1876 try_opt!(context.config.max_width.checked_sub(indent.width() + result.len() + 4));
1878 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1882 // Didn't work. we must force vertical layout and put args on a newline.
1883 let new_indent = indent.block_indent(context.config);
1884 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1885 let max_space = context.config.max_width;
1886 if used_space <= max_space {
1887 Some((0, max_space - used_space, new_indent))
1889 // Whoops! bankrupt.
1894 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1895 match config.fn_brace_style {
1896 BraceStyle::AlwaysNextLine => true,
1897 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1902 fn rewrite_generics(context: &RewriteContext,
1903 generics: &ast::Generics,
1905 // TODO shouldn't need this
1906 generics_offset: Indent,
1909 // FIXME: convert bounds to where clauses where they get too big or if
1910 // there is a where clause at all.
1911 let lifetimes: &[_] = &generics.lifetimes;
1912 let tys: &[_] = &generics.ty_params;
1913 if lifetimes.is_empty() && tys.is_empty() {
1914 return Some(String::new());
1917 let offset = match context.config.generics_indent {
1918 BlockIndentStyle::Inherit => shape.indent,
1919 BlockIndentStyle::Tabbed => shape.indent.block_indent(context.config),
1921 BlockIndentStyle::Visual => generics_offset + 1,
1924 let h_budget = try_opt!(shape.width.checked_sub(generics_offset.width() + 2));
1925 // FIXME: might need to insert a newline if the generics are really long.
1927 // Strings for the generics.
1928 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1930 tys.iter().map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
1932 // Extract comments between generics.
1933 let lt_spans = lifetimes.iter().map(|l| {
1934 let hi = if l.bounds.is_empty() {
1937 l.bounds[l.bounds.len() - 1].span.hi
1939 mk_sp(l.lifetime.span.lo, hi)
1941 let ty_spans = tys.iter().map(span_for_ty_param);
1943 let items = itemize_list(context.codemap,
1944 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1948 // FIXME: don't clone
1949 |&(_, ref str)| str.clone(),
1950 context.codemap.span_after(span, "<"),
1953 try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
1955 let result = if context.config.generics_indent != BlockIndentStyle::Visual &&
1956 list_str.contains('\n') {
1957 format!("<\n{}{}\n{}>",
1958 offset.to_string(context.config),
1960 shape.indent.to_string(context.config))
1961 } else if context.config.spaces_within_angle_brackets {
1962 format!("< {} >", list_str)
1964 format!("<{}>", list_str)
1969 fn rewrite_trait_bounds(context: &RewriteContext,
1970 type_param_bounds: &ast::TyParamBounds,
1973 let bounds: &[_] = type_param_bounds;
1975 if bounds.is_empty() {
1976 return Some(String::new());
1979 let bound_str = try_opt!(bounds.iter()
1980 .map(|ty_bound| ty_bound.rewrite(&context, shape))
1981 .intersperse(Some(" + ".to_string()))
1982 .collect::<Option<String>>());
1984 let mut result = String::new();
1985 result.push_str(": ");
1986 result.push_str(&bound_str);
1990 // fn reflow_list_node_with_rule(
1992 // node: &CompoundNode,
1996 // ) -> Result<String, ()>
2002 fn rewrite_where_clause_rfc_style(context: &RewriteContext,
2003 where_clause: &ast::WhereClause,
2006 suppress_comma: bool,
2007 // where clause can be kept on the current line.
2009 span_end: Option<BytePos>)
2011 let block_shape = shape.block();
2013 let starting_newline = if snuggle {
2016 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2019 let clause_shape = block_shape.block_indent(context.config.tab_spaces);
2020 // each clause on one line, trailing comma (except if suppress_comma)
2021 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2022 // If we don't have the start of the next span, then use the end of the
2023 // predicates, but that means we miss comments.
2024 let len = where_clause.predicates.len();
2025 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2026 let span_end = span_end.unwrap_or(end_of_preds);
2027 let items = itemize_list(context.codemap,
2028 where_clause.predicates.iter(),
2030 |pred| span_for_where_pred(pred).lo,
2031 |pred| span_for_where_pred(pred).hi,
2032 |pred| pred.rewrite(context, clause_shape),
2035 let comma_tactic = if suppress_comma {
2036 SeparatorTactic::Never
2038 SeparatorTactic::Always
2041 let fmt = ListFormatting {
2042 tactic: DefinitiveListTactic::Vertical,
2044 trailing_separator: comma_tactic,
2045 shape: clause_shape,
2046 ends_with_newline: true,
2047 config: context.config,
2049 let preds_str = try_opt!(write_list(items, &fmt));
2051 Some(format!("{}where\n{}{}",
2053 clause_shape.indent.to_string(context.config),
2057 fn rewrite_where_clause(context: &RewriteContext,
2058 where_clause: &ast::WhereClause,
2059 brace_style: BraceStyle,
2063 suppress_comma: bool,
2065 span_end: Option<BytePos>)
2067 if where_clause.predicates.is_empty() {
2068 return Some(String::new());
2071 if context.config.where_style == Style::Rfc {
2072 return rewrite_where_clause_rfc_style(context,
2081 let extra_indent = match context.config.where_indent {
2082 BlockIndentStyle::Inherit => Indent::empty(),
2083 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => {
2084 Indent::new(context.config.tab_spaces, 0)
2088 let offset = match context.config.where_pred_indent {
2089 BlockIndentStyle::Inherit => shape.indent + extra_indent,
2090 BlockIndentStyle::Tabbed => shape.indent + extra_indent.block_indent(context.config),
2091 // 6 = "where ".len()
2092 BlockIndentStyle::Visual => shape.indent + extra_indent + 6,
2094 // FIXME: if where_pred_indent != Visual, then the budgets below might
2095 // be out by a char or two.
2097 let budget = context.config.max_width - offset.width();
2098 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2099 // If we don't have the start of the next span, then use the end of the
2100 // predicates, but that means we miss comments.
2101 let len = where_clause.predicates.len();
2102 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2103 let span_end = span_end.unwrap_or(end_of_preds);
2104 let items = itemize_list(context.codemap,
2105 where_clause.predicates.iter(),
2107 |pred| span_for_where_pred(pred).lo,
2108 |pred| span_for_where_pred(pred).hi,
2109 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2112 let item_vec = items.collect::<Vec<_>>();
2113 // FIXME: we don't need to collect here if the where_layout isn't
2114 // HorizontalVertical.
2115 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
2117 let mut comma_tactic = context.config.trailing_comma;
2118 // Kind of a hack because we don't usually have trailing commas in where clauses.
2119 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2120 comma_tactic = SeparatorTactic::Never;
2123 let fmt = ListFormatting {
2126 trailing_separator: comma_tactic,
2127 shape: Shape::legacy(budget, offset),
2128 ends_with_newline: true,
2129 config: context.config,
2131 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2133 let end_length = if terminator == "{" {
2134 // If the brace is on the next line we don't need to count it otherwise it needs two
2137 BraceStyle::AlwaysNextLine |
2138 BraceStyle::SameLineWhere => 0,
2139 BraceStyle::PreferSameLine => 2,
2141 } else if terminator == "=" {
2146 if density == Density::Tall || preds_str.contains('\n') ||
2147 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
2148 Some(format!("\n{}where {}",
2149 (shape.indent + extra_indent).to_string(context.config),
2152 Some(format!(" where {}", preds_str))
2156 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2157 format!("{}{}{}", format_visibility(vis), item_name, ident)
2160 fn format_generics(context: &RewriteContext,
2161 generics: &ast::Generics,
2164 brace_style: BraceStyle,
2165 force_same_line_brace: bool,
2167 generics_offset: Indent,
2170 let mut result = try_opt!(rewrite_generics(context,
2172 Shape::legacy(context.config.max_width, offset),
2176 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2177 let budget = try_opt!(context.config.max_width.checked_sub(last_line_width(&result)));
2178 let where_clause_str =
2179 try_opt!(rewrite_where_clause(context,
2180 &generics.where_clause,
2182 Shape::legacy(budget, offset.block_only()),
2186 trimmed_last_line_width(&result) == 1,
2188 result.push_str(&where_clause_str);
2189 let same_line_brace = force_same_line_brace ||
2190 (generics.where_clause.predicates.is_empty() &&
2191 trimmed_last_line_width(&result) == 1);
2192 if !same_line_brace &&
2193 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2195 result.push_str(&offset.block_only().to_string(context.config));
2199 result.push_str(opener);
2201 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2202 brace_style != BraceStyle::AlwaysNextLine {
2206 result.push_str(&offset.block_only().to_string(context.config));
2208 result.push_str(opener);