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};
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();
42 let pat_shape = try_opt!(shape.offset_left(4));
44 let pat_shape = try_opt!(pat_shape.sub_width(1));
45 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
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 nested_shape = try_opt!(shape.sub_width(1));
76 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
84 // TODO convert to using rewrite style rather than visitor
85 // TODO format modules in this style
88 keyword: &'static str,
90 vis: Option<&'a ast::Visibility>,
91 body: Vec<BodyElement<'a>>,
96 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
97 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
100 format!("extern {}", fm.abi)
108 .map(|i| BodyElement::ForeignItem(i))
115 enum BodyElement<'a> {
116 // Stmt(&'a ast::Stmt),
117 // Field(&'a ast::Field),
118 // Variant(&'a ast::Variant),
119 // Item(&'a ast::Item),
120 ForeignItem(&'a ast::ForeignItem),
123 impl<'a> FmtVisitor<'a> {
124 fn format_item(&mut self, item: Item) {
125 self.buffer.push_str(&item.abi);
126 self.buffer.push_str(" ");
128 let snippet = self.snippet(item.span);
129 let brace_pos = snippet.find_uncommented("{").unwrap();
131 self.buffer.push_str("{");
132 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
133 // FIXME: this skips comments between the extern keyword and the opening
135 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
136 self.block_indent = self.block_indent.block_indent(self.config);
138 if item.body.is_empty() {
139 self.format_missing_no_indent(item.span.hi - BytePos(1));
140 self.block_indent = self.block_indent.block_unindent(self.config);
143 .push_str(&self.block_indent.to_string(self.config));
145 for item in &item.body {
146 self.format_body_element(item);
149 self.block_indent = self.block_indent.block_unindent(self.config);
150 self.format_missing_with_indent(item.span.hi - BytePos(1));
154 self.buffer.push_str("}");
155 self.last_pos = item.span.hi;
158 fn format_body_element(&mut self, element: &BodyElement) {
160 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
164 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
165 let item = Item::from_foreign_mod(fm, span, self.config);
166 self.format_item(item);
169 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
170 self.format_missing_with_indent(item.span.lo);
171 // Drop semicolon or it will be interpreted as comment.
172 // FIXME: this may be a faulty span from libsyntax.
173 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
176 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
177 let indent = self.block_indent;
178 let rewrite = rewrite_fn_base(&self.get_context(),
183 ast::Unsafety::Normal,
184 ast::Constness::NotConst,
185 ast::Defaultness::Final,
186 // These are not actually rust functions,
187 // but we format them as such.
196 Some((new_fn, _)) => {
197 self.buffer.push_str(&new_fn);
198 self.buffer.push_str(";");
200 None => self.format_missing(item.span.hi),
203 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
204 // FIXME(#21): we're dropping potential comments in between the
205 // function keywords here.
206 let vis = format_visibility(&item.vis);
207 let mut_str = if is_mutable { "mut " } else { "" };
208 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
209 let offset = self.block_indent + prefix.len();
211 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
212 let rewrite = ty.rewrite(&self.get_context(), shape);
216 self.buffer.push_str(&prefix);
217 self.buffer.push_str(&result);
218 self.buffer.push_str(";");
220 None => self.format_missing(item.span.hi),
225 self.last_pos = item.span.hi;
228 pub fn rewrite_fn(&mut self,
232 generics: &ast::Generics,
233 unsafety: ast::Unsafety,
234 constness: ast::Constness,
235 defaultness: ast::Defaultness,
237 vis: &ast::Visibility,
241 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
242 let context = self.get_context();
244 let block_snippet = self.snippet(codemap::mk_sp(block.span.lo, block.span.hi));
245 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
246 !context.config.fn_empty_single_line();
248 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
263 if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine && !result.contains('\n') {
264 newline_brace = false;
265 } else if force_newline_brace {
266 newline_brace = true;
269 // Prepare for the function body by possibly adding a newline and
271 // FIXME we'll miss anything between the end of the signature and the
272 // start of the body, but we need more spans from the compiler to solve
276 result.push_str(&indent.to_string(self.config));
281 self.single_line_fn(&result, block).or_else(|| Some(result))
284 pub fn rewrite_required_fn(&mut self,
287 sig: &ast::MethodSig,
290 // Drop semicolon or it will be interpreted as comment.
291 let span = mk_sp(span.lo, span.hi - BytePos(1));
292 let context = self.get_context();
294 let (mut result, _) = try_opt!(rewrite_fn_base(&context,
301 ast::Defaultness::Final,
303 &ast::Visibility::Inherited,
309 // Re-attach semicolon
315 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
316 if fn_str.contains('\n') {
320 let codemap = self.get_context().codemap;
322 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
323 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width() {
324 return Some(format!("{}{{}}", fn_str));
327 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
329 if let Some(ref stmt) = block.stmts.first() {
330 match stmt_expr(stmt) {
332 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
334 e.rewrite(&self.get_context(),
335 Shape::indented(self.block_indent, self.config))
337 .or_else(|| Some(self.snippet(e.span)))
340 stmt.rewrite(&self.get_context(),
341 Shape::indented(self.block_indent, self.config))
349 if let Some(res) = rewrite {
350 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
351 if !res.contains('\n') && width <= self.config.max_width() {
352 return Some(format!("{}{{ {} }}", fn_str, res));
360 pub fn visit_enum(&mut self,
362 vis: &ast::Visibility,
363 enum_def: &ast::EnumDef,
364 generics: &ast::Generics,
366 self.buffer.push_str(&format_header("enum ", ident, vis));
368 let enum_snippet = self.snippet(span);
369 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
370 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
371 let generics_str = format_generics(&self.get_context(),
375 self.config.item_brace_style(),
376 enum_def.variants.is_empty(),
378 mk_sp(span.lo, body_start))
380 self.buffer.push_str(&generics_str);
382 self.last_pos = body_start;
384 self.block_indent = self.block_indent.block_indent(self.config);
385 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
387 Some(ref body_str) => self.buffer.push_str(body_str),
389 if contains_comment(&enum_snippet[brace_pos..]) {
390 self.format_missing_no_indent(span.hi - BytePos(1))
392 self.format_missing(span.hi - BytePos(1))
396 self.block_indent = self.block_indent.block_unindent(self.config);
398 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
400 .push_str(&self.block_indent.to_string(self.config));
402 self.buffer.push_str("}");
403 self.last_pos = span.hi;
406 // Format the body of an enum definition
407 fn format_variant_list(&self,
408 enum_def: &ast::EnumDef,
412 if enum_def.variants.is_empty() {
415 let mut result = String::with_capacity(1024);
417 let indentation = self.block_indent.to_string(self.config);
418 result.push_str(&indentation);
420 let items = itemize_list(self.codemap,
421 enum_def.variants.iter(),
423 |f| if !f.node.attrs.is_empty() {
424 f.node.attrs[0].span.lo
429 |f| self.format_variant(f),
433 let shape = Shape::indented(self.block_indent, self.config)
436 let fmt = ListFormatting {
437 tactic: DefinitiveListTactic::Vertical,
439 trailing_separator: self.config.trailing_comma(),
441 ends_with_newline: true,
445 let list = try_opt!(write_list(items, &fmt));
446 result.push_str(&list);
451 // Variant of an enum.
452 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
453 if contains_skip(&field.node.attrs) {
454 let lo = field.node.attrs[0].span.lo;
455 let span = mk_sp(lo, field.span.hi);
456 return Some(self.snippet(span));
459 let indent = self.block_indent;
460 let mut result = try_opt!(field.node.attrs.rewrite(&self.get_context(),
461 Shape::indented(indent, self.config)));
462 if !result.is_empty() {
464 result.push_str(&indent.to_string(self.config));
467 let context = self.get_context();
468 let variant_body = match field.node.data {
469 ast::VariantData::Tuple(..) |
470 ast::VariantData::Struct(..) => {
471 // FIXME: Should limit the width, as we have a trailing comma
472 format_struct(&context,
475 &ast::Visibility::Inherited,
480 Some(self.config.struct_variant_width()))
482 ast::VariantData::Unit(..) => {
483 let tag = if let Some(ref expr) = field.node.disr_expr {
484 format!("{} = {}", field.node.name, self.snippet(expr.span))
486 field.node.name.to_string()
490 self.config.max_width(),
491 Shape::indented(indent, self.config))
495 if let Some(variant_str) = variant_body {
496 result.push_str(&variant_str);
504 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
505 if let ast::ItemKind::Impl(_, _, ref generics, ref trait_ref, _, ref items) = item.node {
506 let mut result = String::new();
507 // First try to format the ref and type without a split at the 'for'.
508 let mut ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, false));
510 // If there is a line break present in the first result format it again
511 // with a split at the 'for'. Skip this if there is no trait ref and
512 // therefore no 'for'.
513 if ref_and_type.contains('\n') && trait_ref.is_some() {
514 ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset, true));
516 result.push_str(&ref_and_type);
518 let where_budget = try_opt!(context
521 .checked_sub(last_line_width(&result)));
522 let where_clause_str = try_opt!(rewrite_where_clause(context,
523 &generics.where_clause,
524 context.config.item_brace_style(),
525 Shape::legacy(where_budget,
526 offset.block_only()),
527 context.config.where_density(),
530 last_line_width(&ref_and_type) == 1,
533 if try_opt!(is_impl_single_line(context, &items, &result, &where_clause_str, &item)) {
534 result.push_str(&where_clause_str);
535 if where_clause_str.contains('\n') {
536 let white_space = offset.to_string(context.config);
537 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
539 result.push_str(" {}");
544 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
546 let width = offset.block_indent + context.config.tab_spaces() - 1;
547 let where_indent = Indent::new(0, width);
548 result.push_str(&where_indent.to_string(context.config));
550 result.push_str(&where_clause_str);
552 match context.config.item_brace_style() {
553 BraceStyle::AlwaysNextLine => {
555 result.push_str(&offset.to_string(context.config));
557 BraceStyle::PreferSameLine => result.push(' '),
558 BraceStyle::SameLineWhere => {
559 if !where_clause_str.is_empty() {
561 result.push_str(&offset.to_string(context.config));
570 let snippet = context.snippet(item.span);
571 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
573 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
574 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
575 visitor.block_indent = offset.block_only().block_indent(context.config);
576 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
579 visitor.visit_impl_item(item);
582 visitor.format_missing(item.span.hi - BytePos(1));
584 let inner_indent_str = visitor.block_indent.to_string(context.config);
585 let outer_indent_str = offset.block_only().to_string(context.config);
588 result.push_str(&inner_indent_str);
589 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
591 result.push_str(&outer_indent_str);
594 if result.chars().last().unwrap() == '{' {
596 result.push_str(&offset.to_string(context.config));
606 fn is_impl_single_line(context: &RewriteContext,
609 where_clause_str: &str,
612 let snippet = context.snippet(item.span);
613 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
615 Some(context.config.impl_empty_single_line() && items.is_empty() &&
616 result.len() + where_clause_str.len() <= context.config.max_width() &&
617 !contains_comment(&snippet[open_pos..]))
620 fn format_impl_ref_and_type(context: &RewriteContext,
625 if let ast::ItemKind::Impl(unsafety, polarity, ref generics, ref trait_ref, ref self_ty, _) =
627 let mut result = String::new();
629 result.push_str(&format_visibility(&item.vis));
630 result.push_str(format_unsafety(unsafety));
631 result.push_str("impl");
633 let lo = context.codemap.span_after(item.span, "impl");
634 let hi = match *trait_ref {
635 Some(ref tr) => tr.path.span.lo,
636 None => self_ty.span.lo,
638 let generics_indent = offset + last_line_width(&result);
639 let shape = Shape::indented(generics_indent, context.config);
640 let generics_str = try_opt!(rewrite_generics(context, generics, shape, mk_sp(lo, hi)));
641 result.push_str(&generics_str);
643 if polarity == ast::ImplPolarity::Negative {
644 result.push_str(" !");
646 if let Some(ref trait_ref) = *trait_ref {
647 if polarity != ast::ImplPolarity::Negative {
648 result.push_str(" ");
650 let used_space = last_line_width(&result);
651 let budget = try_opt!(context.config.max_width().checked_sub(used_space));
652 let indent = offset + used_space;
653 result.push_str(&*try_opt!(trait_ref.rewrite(context, Shape::legacy(budget, indent))));
658 // Add indentation of one additional tab.
659 let width = offset.block_indent + context.config.tab_spaces();
660 let for_indent = Indent::new(0, width);
661 result.push_str(&for_indent.to_string(context.config));
663 result.push_str("for");
665 result.push_str(" for");
669 let mut used_space = last_line_width(&result);
670 if generics.where_clause.predicates.is_empty() {
671 // If there is no where clause adapt budget for type formatting to take space and curly
672 // brace into account.
673 match context.config.item_brace_style() {
674 BraceStyle::AlwaysNextLine => {}
675 BraceStyle::PreferSameLine => used_space += 2,
676 BraceStyle::SameLineWhere => used_space += 2,
680 // 1 = space before the type.
681 let budget = try_opt!(context.config.max_width().checked_sub(used_space + 1));
682 let indent = offset + result.len() + 1;
683 let self_ty_str = self_ty.rewrite(context, Shape::legacy(budget, indent));
684 if let Some(self_ty_str) = self_ty_str {
685 result.push_str(" ");
686 result.push_str(&self_ty_str);
690 // Can't fit the self type on what's left of the line, so start a new one.
691 let indent = offset.block_indent(context.config);
692 result.push_str(&format!("\n{}", indent.to_string(context.config)));
693 result.push_str(&*try_opt!(self_ty.rewrite(context,
694 Shape::indented(indent, context.config))));
701 pub fn format_struct(context: &RewriteContext,
704 vis: &ast::Visibility,
705 struct_def: &ast::VariantData,
706 generics: Option<&ast::Generics>,
709 one_line_width: Option<usize>)
712 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
713 ast::VariantData::Tuple(ref fields, _) => {
714 format_tuple_struct(context,
723 ast::VariantData::Struct(ref fields, _) => {
724 format_struct_struct(context,
737 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
738 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
740 let mut result = String::new();
741 let header = format!("{}{}trait {}",
742 format_visibility(&item.vis),
743 format_unsafety(unsafety),
746 result.push_str(&header);
748 let body_lo = context.codemap.span_after(item.span, "{");
750 let generics_indent = offset + last_line_width(&result);
751 let shape = Shape::indented(generics_indent, context.config);
753 try_opt!(rewrite_generics(context, generics, shape, mk_sp(item.span.lo, body_lo)));
754 result.push_str(&generics_str);
756 let trait_bound_str =
757 try_opt!(rewrite_trait_bounds(context,
759 Shape::legacy(context.config.max_width(), offset)));
760 // If the trait, generics, and trait bound cannot fit on the same line,
761 // put the trait bounds on an indented new line
762 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
763 context.config.comment_width() {
765 let trait_indent = offset.block_only().block_indent(context.config);
766 result.push_str(&trait_indent.to_string(context.config));
768 result.push_str(&trait_bound_str);
770 let has_body = !trait_items.is_empty();
773 if (context.config.where_density() == Density::Compressed &&
774 (!result.contains('\n') ||
775 context.config.fn_args_layout() == IndentStyle::Block)) ||
776 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
777 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
778 !result.contains('\n')) {
784 let where_budget = try_opt!(context
787 .checked_sub(last_line_width(&result)));
788 let where_clause_str = try_opt!(rewrite_where_clause(context,
789 &generics.where_clause,
790 context.config.item_brace_style(),
791 Shape::legacy(where_budget,
792 offset.block_only()),
796 trait_bound_str.is_empty() &&
797 last_line_width(&generics_str) == 1,
799 // If the where clause cannot fit on the same line,
800 // put the where clause on a new line
801 if !where_clause_str.contains('\n') &&
802 last_line_width(&result) + where_clause_str.len() + offset.width() >
803 context.config.comment_width() {
805 let width = offset.block_indent + context.config.tab_spaces() - 1;
806 let where_indent = Indent::new(0, width);
807 result.push_str(&where_indent.to_string(context.config));
809 result.push_str(&where_clause_str);
811 match context.config.item_brace_style() {
812 BraceStyle::AlwaysNextLine => {
814 result.push_str(&offset.to_string(context.config));
816 BraceStyle::PreferSameLine => result.push(' '),
817 BraceStyle::SameLineWhere => {
818 if !where_clause_str.is_empty() &&
819 (!trait_items.is_empty() || result.contains('\n')) {
821 result.push_str(&offset.to_string(context.config));
829 let snippet = context.snippet(item.span);
830 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
832 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
833 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
834 visitor.block_indent = offset.block_only().block_indent(context.config);
835 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
837 for item in trait_items {
838 visitor.visit_trait_item(item);
841 visitor.format_missing(item.span.hi - BytePos(1));
843 let inner_indent_str = visitor.block_indent.to_string(context.config);
844 let outer_indent_str = offset.block_only().to_string(context.config);
847 result.push_str(&inner_indent_str);
848 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
850 result.push_str(&outer_indent_str);
851 } else if result.contains('\n') {
862 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
863 format!("{};", format_header(item_name, ident, vis))
866 fn format_struct_struct(context: &RewriteContext,
869 vis: &ast::Visibility,
870 fields: &[ast::StructField],
871 generics: Option<&ast::Generics>,
874 one_line_width: Option<usize>)
876 let mut result = String::with_capacity(1024);
878 let header_str = format_header(item_name, ident, vis);
879 result.push_str(&header_str);
881 let body_lo = context.codemap.span_after(span, "{");
883 let generics_str = match generics {
885 try_opt!(format_generics(context,
889 context.config.item_brace_style(),
892 mk_sp(span.lo, body_lo)))
895 if context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
897 format!("\n{}{{", offset.block_only().to_string(context.config))
903 result.push_str(&generics_str);
905 if fields.is_empty() {
906 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
907 if snippet.trim().is_empty() {
909 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
911 result.push_str(&snippet.trim_right());
913 result.push_str(&offset.to_string(context.config));
915 result.push_str(&snippet);
921 let item_indent = offset.block_indent(context.config);
923 let item_budget = try_opt!(context
926 .checked_sub(item_indent.width() + 1));
929 itemize_list(context.codemap,
933 // Include attributes and doc comments, if present
934 if !field.attrs.is_empty() {
935 field.attrs[0].span.lo
940 |field| field.ty.span.hi,
941 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
942 context.codemap.span_after(span, "{"),
944 .collect::<Vec<_>>();
946 let budget = context.config.max_width() - offset.width() + context.config.tab_spaces() - 1;
948 let tactic = match one_line_width {
949 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
950 None => DefinitiveListTactic::Vertical,
953 let fmt = ListFormatting {
956 trailing_separator: context.config.trailing_comma(),
957 shape: Shape::legacy(budget, item_indent),
958 ends_with_newline: true,
959 config: context.config,
961 let items_str = try_opt!(write_list(&items, &fmt));
962 if one_line_width.is_some() && !items_str.contains('\n') {
963 Some(format!("{} {} }}", result, items_str))
965 Some(format!("{}\n{}{}\n{}}}",
968 .block_indent(context.config)
969 .to_string(context.config),
971 offset.to_string(context.config)))
975 fn format_tuple_struct(context: &RewriteContext,
978 vis: &ast::Visibility,
979 fields: &[ast::StructField],
980 generics: Option<&ast::Generics>,
984 let mut result = String::with_capacity(1024);
986 let header_str = format_header(item_name, ident, vis);
987 result.push_str(&header_str);
989 let body_lo = if fields.is_empty() {
990 context.codemap.span_after(span, "(")
995 let where_clause_str = match generics {
997 let generics_indent = offset + last_line_width(&header_str);
998 let shape = Shape::indented(generics_indent, context.config);
1000 try_opt!(rewrite_generics(context, generics, shape, mk_sp(span.lo, body_lo)));
1001 result.push_str(&generics_str);
1003 let where_budget = try_opt!(context
1006 .checked_sub(last_line_width(&result)));
1007 try_opt!(rewrite_where_clause(context,
1008 &generics.where_clause,
1009 context.config.item_brace_style(),
1010 Shape::legacy(where_budget, offset.block_only()),
1011 Density::Compressed,
1017 None => "".to_owned(),
1020 if fields.is_empty() {
1022 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1023 if snippet.is_empty() {
1025 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1026 result.push_str(&snippet.trim_right());
1028 result.push_str(&offset.to_string(context.config));
1030 result.push_str(&snippet);
1034 let (tactic, item_indent) = match context.config.fn_args_layout() {
1035 IndentStyle::Visual => {
1037 (ListTactic::HorizontalVertical, offset.block_only() + result.len() + 1)
1039 IndentStyle::Block => {
1040 (ListTactic::HorizontalVertical, offset.block_only().block_indent(&context.config))
1044 let item_budget = try_opt!(context
1047 .checked_sub(item_indent.width() + 3));
1050 itemize_list(context.codemap,
1054 // Include attributes and doc comments, if present
1055 if !field.attrs.is_empty() {
1056 field.attrs[0].span.lo
1061 |field| field.ty.span.hi,
1062 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1063 context.codemap.span_after(span, "("),
1065 let body_budget = try_opt!(context
1068 .checked_sub(offset.block_only().width() + result.len() +
1070 let body = try_opt!(list_helper(items,
1071 // TODO budget is wrong in block case
1072 Shape::legacy(body_budget, item_indent),
1076 if context.config.fn_args_layout() == IndentStyle::Visual || !body.contains('\n') {
1078 if context.config.spaces_within_parens() && body.len() > 0 {
1082 result.push_str(&body);
1084 if context.config.spaces_within_parens() && body.len() > 0 {
1089 result.push_str("(\n");
1090 result.push_str(&item_indent.to_string(&context.config));
1091 result.push_str(&body);
1093 result.push_str(&offset.block_only().to_string(&context.config));
1098 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1099 (result.contains('\n') ||
1100 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1101 context.config.max_width()) {
1102 // We need to put the where clause on a new line, but we didn't
1103 // know that earlier, so the where clause will not be indented properly.
1105 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1106 .to_string(context.config));
1108 result.push_str(&where_clause_str);
1113 pub fn rewrite_type_alias(context: &RewriteContext,
1117 generics: &ast::Generics,
1118 vis: &ast::Visibility,
1121 let mut result = String::new();
1123 result.push_str(&format_visibility(vis));
1124 result.push_str("type ");
1125 result.push_str(&ident.to_string());
1127 let generics_indent = indent + result.len();
1128 let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1129 let shape = try_opt!(Shape::indented(generics_indent, context.config)
1130 .sub_width(" =".len()));
1131 let generics_str = try_opt!(rewrite_generics(context, generics, shape, generics_span));
1133 result.push_str(&generics_str);
1135 let where_budget = try_opt!(context
1138 .checked_sub(last_line_width(&result)));
1139 let where_clause_str = try_opt!(rewrite_where_clause(context,
1140 &generics.where_clause,
1141 context.config.item_brace_style(),
1142 Shape::legacy(where_budget, indent),
1143 context.config.where_density(),
1148 result.push_str(&where_clause_str);
1149 result.push_str(" = ");
1151 let line_width = last_line_width(&result);
1152 // This checked_sub may fail as the extra space after '=' is not taken into account
1153 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1154 let budget = context
1157 .checked_sub(indent.width() + line_width + ";".len())
1159 let type_indent = indent + line_width;
1160 // Try to fit the type on the same line
1161 let ty_str = try_opt!(ty.rewrite(context, Shape::legacy(budget, type_indent))
1163 // The line was too short, try to put the type on the next line
1165 // Remove the space after '='
1167 let type_indent = indent.block_indent(context.config);
1169 result.push_str(&type_indent.to_string(context.config));
1170 let budget = try_opt!(context
1173 .checked_sub(type_indent.width() + ";".len()));
1174 ty.rewrite(context, Shape::legacy(budget, type_indent))
1176 result.push_str(&ty_str);
1177 result.push_str(";");
1181 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1182 (if config.space_before_type_annotation() {
1187 if config.space_after_type_annotation_colon() {
1194 impl Rewrite for ast::StructField {
1195 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1196 if contains_skip(&self.attrs) {
1197 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1198 return wrap_str(span, context.config.max_width(), shape);
1201 let name = self.ident;
1202 let vis = format_visibility(&self.vis);
1203 let mut attr_str = try_opt!(self.attrs.rewrite(context,
1204 Shape::indented(shape.indent,
1206 if !attr_str.is_empty() {
1207 attr_str.push('\n');
1208 attr_str.push_str(&shape.indent.to_string(context.config));
1211 let type_annotation_spacing = type_annotation_spacing(context.config);
1212 let mut result = match name {
1213 Some(name) => format!("{}{}{}{}:", attr_str, vis, name, type_annotation_spacing.0),
1214 None => format!("{}{}", attr_str, vis),
1217 let type_offset = shape.indent.block_indent(context.config);
1218 let rewrite_type_in_next_line = || {
1220 .rewrite(context, Shape::indented(type_offset, context.config))
1223 let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len();
1224 let budget = try_opt!(shape.width.checked_sub(last_line_width));
1226 self.ty.rewrite(context,
1227 Shape::legacy(budget, shape.indent + last_line_width));
1228 match ty_rewritten {
1229 Some(ref ty) if ty.contains('\n') => {
1230 let new_ty = rewrite_type_in_next_line();
1232 Some(ref new_ty) if !new_ty.contains('\n') &&
1233 new_ty.len() + type_offset.width() <=
1234 context.config.max_width() => {
1235 Some(format!("{}\n{}{}",
1237 type_offset.to_string(&context.config),
1242 result.push_str(type_annotation_spacing.1);
1250 result.push_str(type_annotation_spacing.1);
1255 let ty = try_opt!(rewrite_type_in_next_line());
1256 Some(format!("{}\n{}{}",
1258 type_offset.to_string(&context.config),
1265 pub fn rewrite_static(prefix: &str,
1266 vis: &ast::Visibility,
1269 mutability: ast::Mutability,
1270 expr_opt: Option<&ptr::P<ast::Expr>>,
1272 context: &RewriteContext)
1274 let type_annotation_spacing = type_annotation_spacing(context.config);
1275 let prefix = format!("{}{} {}{}{}:{}",
1276 format_visibility(vis),
1278 format_mutability(mutability),
1280 type_annotation_spacing.0,
1281 type_annotation_spacing.1);
1283 let ty_str = try_opt!(ty.rewrite(context,
1284 Shape::legacy(context.config.max_width() -
1285 offset.block_indent -
1288 offset.block_only())));
1290 if let Some(expr) = expr_opt {
1291 let lhs = format!("{}{} =", prefix, ty_str);
1293 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1294 rewrite_assign_rhs(context,
1297 Shape::legacy(remaining_width, offset.block_only()))
1300 let lhs = format!("{}{};", prefix, ty_str);
1305 pub fn rewrite_associated_type(ident: ast::Ident,
1306 ty_opt: Option<&ptr::P<ast::Ty>>,
1307 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1308 context: &RewriteContext,
1311 let prefix = format!("type {}", ident);
1313 let type_bounds_str =
1314 if let Some(ty_param_bounds) = ty_param_bounds_opt {
1315 let joiner = match context.config.type_punctuation_density() {
1316 TypeDensity::Compressed => "+",
1317 TypeDensity::Wide => " + ",
1319 let bounds: &[_] = ty_param_bounds;
1320 let bound_str = try_opt!(bounds
1323 ty_bound.rewrite(context, Shape::legacy(context.config.max_width(), indent))
1325 .intersperse(Some(joiner.to_string()))
1326 .collect::<Option<String>>());
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, &result, indent, ret_str_len, newline_brace));
1569 if context.config.fn_args_layout() == IndentStyle::Block {
1570 arg_indent = indent.block_indent(context.config);
1571 multi_line_budget = context.config.max_width() - arg_indent.width();
1574 debug!("rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1579 // Check if vertical layout was forced.
1580 if one_line_budget == 0 {
1581 if snuggle_angle_bracket {
1582 result.push_str("(");
1583 } else if context.config.fn_args_paren_newline() {
1585 result.push_str(&arg_indent.to_string(context.config));
1586 arg_indent = arg_indent + 1; // extra space for `(`
1588 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1592 result.push_str("(\n");
1593 result.push_str(&arg_indent.to_string(context.config));
1597 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1602 if multi_line_ret_str {
1603 one_line_budget = 0;
1606 // A conservative estimation, to goal is to be over all parens in generics
1607 let args_start = generics
1610 .map_or(span.lo, |tp| end_typaram(tp));
1611 let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1612 span_for_return(&fd.output).lo);
1613 let arg_str = try_opt!(rewrite_args(context,
1615 fd.get_self().as_ref(),
1622 generics_str.contains('\n')));
1624 let multi_line_arg_str = arg_str.contains('\n') ||
1625 arg_str.chars().last().map_or(false, |c| c == ',');
1627 let put_args_in_block = match context.config.fn_args_layout() {
1628 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1630 } && !fd.inputs.is_empty();
1632 if put_args_in_block {
1633 arg_indent = indent.block_indent(context.config);
1635 result.push_str(&arg_indent.to_string(context.config));
1636 result.push_str(&arg_str);
1638 result.push_str(&indent.to_string(context.config));
1641 result.push_str(&arg_str);
1642 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1649 if !ret_str.is_empty() {
1650 let ret_should_indent = match context.config.fn_args_layout() {
1651 // If our args are block layout then we surely must have space.
1652 IndentStyle::Block if put_args_in_block => false,
1654 // If we've already gone multi-line, or the return type would push over the max
1655 // width, then put the return type on a new line. With the +1 for the signature
1656 // length an additional space between the closing parenthesis of the argument and
1657 // the arrow '->' is considered.
1658 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1660 // If there is no where clause, take into account the space after the return type
1662 if where_clause.predicates.is_empty() {
1666 let overlong_sig = sig_length > context.config.max_width();
1668 result.contains('\n') || multi_line_ret_str || overlong_sig
1671 let ret_indent = if ret_should_indent {
1672 let indent = match context.config.fn_return_indent() {
1673 ReturnIndent::WithWhereClause => indent + 4,
1674 // Aligning with non-existent args looks silly.
1675 _ if arg_str.is_empty() => {
1676 force_new_line_for_brace = true;
1679 // FIXME: we might want to check that using the arg indent
1680 // doesn't blow our budget, and if it does, then fallback to
1681 // the where clause indent.
1686 result.push_str(&indent.to_string(context.config));
1690 Indent::new(indent.width(), result.len())
1693 if multi_line_ret_str || ret_should_indent {
1694 // Now that we know the proper indent and width, we need to
1695 // re-layout the return type.
1696 let ret_str = try_opt!(fd.output.rewrite(context,
1697 Shape::indented(ret_indent, context.config)));
1698 result.push_str(&ret_str);
1700 result.push_str(&ret_str);
1703 // Comment between return type and the end of the decl.
1704 let snippet_lo = fd.output.span().hi;
1705 if where_clause.predicates.is_empty() {
1706 let snippet_hi = span.hi;
1707 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1708 let snippet = snippet.trim();
1709 if !snippet.is_empty() {
1711 result.push_str(snippet);
1714 // FIXME it would be nice to catch comments between the return type
1715 // and the where clause, but we don't have a span for the where
1720 let should_compress_where = match context.config.where_density() {
1721 Density::Compressed => !result.contains('\n') || put_args_in_block,
1722 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1724 } || (put_args_in_block && ret_str.is_empty());
1726 if where_clause.predicates.len() == 1 && should_compress_where {
1727 let budget = try_opt!(context
1730 .checked_sub(last_line_width(&result)));
1731 if let Some(where_clause_str) =
1732 rewrite_where_clause(context,
1734 context.config.fn_brace_style(),
1735 Shape::legacy(budget, indent),
1736 Density::Compressed,
1739 put_args_in_block && ret_str.is_empty(),
1741 if !where_clause_str.contains('\n') {
1742 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
1746 result.push_str(&where_clause_str);
1748 return Some((result, force_new_line_for_brace));
1753 let where_clause_str = try_opt!(rewrite_where_clause(context,
1755 context.config.fn_brace_style(),
1756 Shape::indented(indent, context.config),
1760 put_args_in_block && ret_str.is_empty(),
1763 result.push_str(&where_clause_str);
1765 Some((result, force_new_line_for_brace))
1768 fn rewrite_args(context: &RewriteContext,
1770 explicit_self: Option<&ast::ExplicitSelf>,
1771 one_line_budget: usize,
1772 multi_line_budget: usize,
1777 generics_str_contains_newline: bool)
1779 let mut arg_item_strs =
1780 try_opt!(args.iter()
1782 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
1784 .collect::<Option<Vec<_>>>());
1786 // Account for sugary self.
1787 // FIXME: the comment for the self argument is dropped. This is blocked
1788 // on rust issue #27522.
1789 let min_args = explicit_self
1790 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
1791 .map_or(1, |self_str| {
1792 arg_item_strs[0] = self_str;
1796 // Comments between args.
1797 let mut arg_items = Vec::new();
1799 arg_items.push(ListItem::from_str(""));
1802 // FIXME(#21): if there are no args, there might still be a comment, but
1803 // without spans for the comment or parens, there is no chance of
1804 // getting it right. You also don't get to put a comment on self, unless
1806 if args.len() >= min_args || variadic {
1807 let comment_span_start = if min_args == 2 {
1808 let second_arg_start = if arg_has_pattern(&args[1]) {
1813 let reduced_span = mk_sp(span.lo, second_arg_start);
1815 context.codemap.span_after_last(reduced_span, ",")
1820 enum ArgumentKind<'a> {
1821 Regular(&'a ast::Arg),
1825 let variadic_arg = if variadic {
1826 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1827 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
1828 Some(ArgumentKind::Variadic(variadic_start))
1833 let more_items = itemize_list(context.codemap,
1834 args[min_args - 1..]
1836 .map(ArgumentKind::Regular)
1837 .chain(variadic_arg),
1840 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1841 ArgumentKind::Variadic(start) => start,
1844 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1845 ArgumentKind::Variadic(start) => start + BytePos(3),
1848 ArgumentKind::Regular(..) => None,
1849 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1854 arg_items.extend(more_items);
1857 let fits_in_one_line = !generics_str_contains_newline &&
1858 (arg_items.len() == 0 ||
1859 arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
1861 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1862 item.item = Some(arg);
1865 let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout() {
1866 IndentStyle::Block if fits_in_one_line => {
1867 (indent.block_indent(context.config), SeparatorTactic::Never, true)
1869 IndentStyle::Block => {
1870 (indent.block_indent(context.config), SeparatorTactic::Vertical, true)
1872 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never, false),
1875 let tactic = definitive_tactic(&arg_items,
1876 context.config.fn_args_density().to_list_tactic(),
1878 let budget = match tactic {
1879 DefinitiveListTactic::Horizontal => one_line_budget,
1880 _ => multi_line_budget,
1883 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
1885 let fmt = ListFormatting {
1888 trailing_separator: trailing_comma,
1889 shape: Shape::legacy(budget, indent),
1890 ends_with_newline: end_with_newline,
1891 config: context.config,
1894 write_list(&arg_items, &fmt)
1897 fn arg_has_pattern(arg: &ast::Arg) -> bool {
1898 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1899 ident.node != symbol::keywords::Invalid.ident()
1905 fn compute_budgets_for_args(context: &RewriteContext,
1909 newline_brace: bool)
1910 -> Option<((usize, usize, Indent))> {
1911 debug!("compute_budgets_for_args {} {:?}, {}, {}",
1916 // Try keeping everything on the same line.
1917 if !result.contains('\n') {
1918 // 3 = `() `, space is before ret_string.
1919 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1923 let one_line_budget = context
1926 .checked_sub(used_space)
1929 if one_line_budget > 0 {
1931 let multi_line_budget = try_opt!(context
1934 .checked_sub(indent.width() + result.len() +
1937 return Some((one_line_budget, multi_line_budget, indent + result.len() + 1));
1941 // Didn't work. we must force vertical layout and put args on a newline.
1942 let new_indent = indent.block_indent(context.config);
1943 let used_space = new_indent.width() + 4; // Account for `(` and `)` and possibly ` {`.
1944 let max_space = context.config.max_width();
1945 if used_space <= max_space {
1946 Some((0, max_space - used_space, new_indent))
1948 // Whoops! bankrupt.
1953 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1954 match config.fn_brace_style() {
1955 BraceStyle::AlwaysNextLine => true,
1956 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1961 fn rewrite_generics(context: &RewriteContext,
1962 generics: &ast::Generics,
1966 // FIXME: convert bounds to where clauses where they get too big or if
1967 // there is a where clause at all.
1968 let lifetimes: &[_] = &generics.lifetimes;
1969 let tys: &[_] = &generics.ty_params;
1970 if lifetimes.is_empty() && tys.is_empty() {
1971 return Some(String::new());
1974 let offset = match context.config.generics_indent() {
1975 IndentStyle::Block => shape.indent.block_only().block_indent(context.config),
1977 IndentStyle::Visual => shape.indent + 1,
1980 let h_budget = try_opt!(shape.width.checked_sub(2));
1981 // FIXME: might need to insert a newline if the generics are really long.
1983 // Strings for the generics.
1984 let lt_strs = lifetimes
1986 .map(|lt| lt.rewrite(context, Shape::legacy(h_budget, offset)));
1987 let ty_strs = tys.iter()
1988 .map(|ty_param| ty_param.rewrite(context, Shape::legacy(h_budget, offset)));
1990 // Extract comments between generics.
1991 let lt_spans = lifetimes.iter().map(|l| {
1992 let hi = if l.bounds.is_empty() {
1995 l.bounds[l.bounds.len() - 1].span.hi
1997 mk_sp(l.lifetime.span.lo, hi)
1999 let ty_spans = tys.iter().map(span_for_ty_param);
2001 let items = itemize_list(context.codemap,
2002 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2006 // FIXME: don't clone
2007 |&(_, ref str)| str.clone(),
2008 context.codemap.span_after(span, "<"),
2011 try_opt!(format_item_list(items, Shape::legacy(h_budget, offset), context.config));
2013 let result = if context.config.generics_indent() != IndentStyle::Visual &&
2014 list_str.contains('\n') {
2015 format!("<\n{}{}\n{}>",
2016 offset.to_string(context.config),
2018 shape.indent.block_only().to_string(context.config))
2019 } else if context.config.spaces_within_angle_brackets() {
2020 format!("< {} >", list_str)
2022 format!("<{}>", list_str)
2027 fn rewrite_trait_bounds(context: &RewriteContext,
2028 type_param_bounds: &ast::TyParamBounds,
2031 let bounds: &[_] = type_param_bounds;
2033 if bounds.is_empty() {
2034 return Some(String::new());
2036 let joiner = match context.config.type_punctuation_density() {
2037 TypeDensity::Compressed => "+",
2038 TypeDensity::Wide => " + ",
2040 let bound_str = try_opt!(bounds
2042 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2043 .intersperse(Some(joiner.to_string()))
2044 .collect::<Option<String>>());
2046 let mut result = String::new();
2047 result.push_str(": ");
2048 result.push_str(&bound_str);
2052 // fn reflow_list_node_with_rule(
2054 // node: &CompoundNode,
2058 // ) -> Result<String, ()>
2064 fn rewrite_where_clause_rfc_style(context: &RewriteContext,
2065 where_clause: &ast::WhereClause,
2068 suppress_comma: bool,
2069 // where clause can be kept on the current line.
2071 span_end: Option<BytePos>)
2073 let block_shape = shape.block();
2075 let starting_newline = if snuggle {
2078 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2081 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2082 // each clause on one line, trailing comma (except if suppress_comma)
2083 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2084 // If we don't have the start of the next span, then use the end of the
2085 // predicates, but that means we miss comments.
2086 let len = where_clause.predicates.len();
2087 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2088 let span_end = span_end.unwrap_or(end_of_preds);
2089 let items = itemize_list(context.codemap,
2090 where_clause.predicates.iter(),
2092 |pred| span_for_where_pred(pred).lo,
2093 |pred| span_for_where_pred(pred).hi,
2094 |pred| pred.rewrite(context, clause_shape),
2097 let comma_tactic = if suppress_comma {
2098 SeparatorTactic::Never
2100 SeparatorTactic::Always
2103 let fmt = ListFormatting {
2104 tactic: DefinitiveListTactic::Vertical,
2106 trailing_separator: comma_tactic,
2107 shape: clause_shape,
2108 ends_with_newline: true,
2109 config: context.config,
2111 let preds_str = try_opt!(write_list(items, &fmt));
2113 Some(format!("{}where\n{}{}",
2115 clause_shape.indent.to_string(context.config),
2119 fn rewrite_where_clause(context: &RewriteContext,
2120 where_clause: &ast::WhereClause,
2121 brace_style: BraceStyle,
2125 suppress_comma: bool,
2127 span_end: Option<BytePos>)
2129 if where_clause.predicates.is_empty() {
2130 return Some(String::new());
2133 if context.config.where_style() == Style::Rfc {
2134 return rewrite_where_clause_rfc_style(context,
2143 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2145 let offset = match context.config.where_pred_indent() {
2146 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2147 // 6 = "where ".len()
2148 IndentStyle::Visual => shape.indent + extra_indent + 6,
2150 // FIXME: if where_pred_indent != Visual, then the budgets below might
2151 // be out by a char or two.
2153 let budget = context.config.max_width() - offset.width();
2154 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2155 // If we don't have the start of the next span, then use the end of the
2156 // predicates, but that means we miss comments.
2157 let len = where_clause.predicates.len();
2158 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2159 let span_end = span_end.unwrap_or(end_of_preds);
2160 let items = itemize_list(context.codemap,
2161 where_clause.predicates.iter(),
2163 |pred| span_for_where_pred(pred).lo,
2164 |pred| span_for_where_pred(pred).hi,
2165 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2168 let item_vec = items.collect::<Vec<_>>();
2169 // FIXME: we don't need to collect here if the where_layout isn't
2170 // HorizontalVertical.
2171 let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget);
2173 let mut comma_tactic = context.config.trailing_comma();
2174 // Kind of a hack because we don't usually have trailing commas in where clauses.
2175 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2176 comma_tactic = SeparatorTactic::Never;
2179 let fmt = ListFormatting {
2182 trailing_separator: comma_tactic,
2183 shape: Shape::legacy(budget, offset),
2184 ends_with_newline: true,
2185 config: context.config,
2187 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2189 let end_length = if terminator == "{" {
2190 // If the brace is on the next line we don't need to count it otherwise it needs two
2193 BraceStyle::AlwaysNextLine |
2194 BraceStyle::SameLineWhere => 0,
2195 BraceStyle::PreferSameLine => 2,
2197 } else if terminator == "=" {
2202 if density == Density::Tall || preds_str.contains('\n') ||
2203 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width {
2204 Some(format!("\n{}where {}",
2205 (shape.indent + extra_indent).to_string(context.config),
2208 Some(format!(" where {}", preds_str))
2212 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2213 format!("{}{}{}", format_visibility(vis), item_name, ident)
2216 fn format_generics(context: &RewriteContext,
2217 generics: &ast::Generics,
2220 brace_style: BraceStyle,
2221 force_same_line_brace: bool,
2225 let shape = Shape::indented(offset, context.config);
2226 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2228 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2229 let budget = try_opt!(context
2232 .checked_sub(last_line_width(&result)));
2233 let where_clause_str =
2234 try_opt!(rewrite_where_clause(context,
2235 &generics.where_clause,
2237 Shape::legacy(budget, offset.block_only()),
2241 trimmed_last_line_width(&result) == 1,
2243 result.push_str(&where_clause_str);
2244 let same_line_brace = force_same_line_brace ||
2245 (generics.where_clause.predicates.is_empty() &&
2246 trimmed_last_line_width(&result) == 1);
2247 if !same_line_brace &&
2248 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
2250 result.push_str(&offset.block_only().to_string(context.config));
2254 result.push_str(opener);
2256 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2257 brace_style != BraceStyle::AlwaysNextLine {
2261 result.push_str(&offset.block_only().to_string(context.config));
2263 result.push_str(opener);