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 utils::{format_mutability, format_visibility, contains_skip, span_after, end_typaram,
15 wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
17 DefinitiveListTactic, definitive_tactic, format_item_list};
18 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
19 use comment::FindUncommented;
20 use visitor::FmtVisitor;
21 use rewrite::{Rewrite, RewriteContext};
22 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, StructLitStyle};
24 use syntax::{ast, abi};
25 use syntax::codemap::{Span, BytePos, mk_sp};
26 use syntax::print::pprust;
27 use syntax::parse::token;
29 // Statements of the form
30 // let pat: ty = init;
31 impl Rewrite for ast::Local {
32 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33 let mut result = "let ".to_owned();
34 let pattern_offset = offset + result.len();
36 let pattern_width = try_opt!(width.checked_sub(pattern_offset.width() + 1));
38 let pat_str = try_opt!(self.pat.rewrite(&context, pattern_width, pattern_offset));
39 result.push_str(&pat_str);
41 // String that is placed within the assignment pattern and expression.
43 let mut infix = String::new();
45 if let Some(ref ty) = self.ty {
48 let indent = offset + last_line_width(&result) + 2;
49 let budget = try_opt!(width.checked_sub(indent.width() + 1));
50 let rewrite = try_opt!(ty.rewrite(context, budget, indent));
53 infix.push_str(&rewrite);
56 if self.init.is_some() {
63 result.push_str(&infix);
65 if let Some(ref ex) = self.init {
66 let budget = try_opt!(width.checked_sub(context.block_indent.width() + 1));
68 // 1 = trailing semicolon;
69 result = try_opt!(rewrite_assign_rhs(&context,
73 context.block_indent));
81 impl<'a> FmtVisitor<'a> {
82 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
83 self.buffer.push_str(&::utils::format_abi(fm.abi));
85 let snippet = self.snippet(span);
86 let brace_pos = snippet.find_uncommented("{").unwrap() as u32;
88 // FIXME: this skips comments between the extern keyword and the opening
90 self.last_pos = span.lo + BytePos(brace_pos);
91 self.block_indent = self.block_indent.block_indent(self.config);
93 for item in &fm.items {
94 self.format_foreign_item(&*item);
97 self.block_indent = self.block_indent.block_unindent(self.config);
98 self.format_missing_with_indent(span.hi - BytePos(1));
99 self.buffer.push_str("}");
100 self.last_pos = span.hi;
103 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
104 self.format_missing_with_indent(item.span.lo);
105 // Drop semicolon or it will be interpreted as comment.
106 // FIXME: this may be a faulty span from libsyntax.
107 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
110 ast::ForeignItem_::ForeignItemFn(ref fn_decl, ref generics) => {
111 let indent = self.block_indent;
112 let rewrite = rewrite_fn_base(&self.get_context(),
118 ast::Unsafety::Normal,
119 ast::Constness::NotConst,
120 // These are not actually rust functions,
121 // but we format them as such.
129 Some((new_fn, _)) => {
130 self.buffer.push_str(&new_fn);
131 self.buffer.push_str(";");
133 None => self.format_missing(item.span.hi),
136 ast::ForeignItem_::ForeignItemStatic(ref ty, is_mutable) => {
137 // FIXME(#21): we're dropping potential comments in between the
138 // function keywords here.
139 let mut_str = if is_mutable {
144 let prefix = format!("{}static {}{}: ",
145 format_visibility(item.vis),
148 let offset = self.block_indent + prefix.len();
150 let width = self.config.max_width - offset.width() - 1;
151 let rewrite = ty.rewrite(&self.get_context(), width, offset);
155 self.buffer.push_str(&prefix);
156 self.buffer.push_str(&result);
157 self.buffer.push_str(";");
159 None => self.format_missing(item.span.hi),
164 self.last_pos = item.span.hi;
167 pub fn rewrite_fn(&mut self,
171 explicit_self: Option<&ast::ExplicitSelf>,
172 generics: &ast::Generics,
173 unsafety: ast::Unsafety,
174 constness: ast::Constness,
176 vis: ast::Visibility,
180 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
181 let context = self.get_context();
183 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(&context,
197 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
198 newline_brace = false;
199 } else if force_newline_brace {
200 newline_brace = true;
203 // Prepare for the function body by possibly adding a newline and
205 // FIXME we'll miss anything between the end of the signature and the
206 // start of the body, but we need more spans from the compiler to solve
210 result.push_str(&indent.to_string(self.config));
215 self.single_line_fn(&result, block).or_else(|| Some(result))
218 pub fn rewrite_required_fn(&mut self,
221 sig: &ast::MethodSig,
224 // Drop semicolon or it will be interpreted as comment
225 let span = mk_sp(span.lo, span.hi - BytePos(1));
226 let context = self.get_context();
228 // FIXME: silly formatting of the `.0`.
229 let mut result = try_opt!(rewrite_fn_base(&context,
233 Some(&sig.explicit_self),
238 ast::Visibility::Inherited,
244 // Re-attach semicolon
250 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
251 if fn_str.contains('\n') {
255 let codemap = self.get_context().codemap;
257 if self.config.fn_empty_single_line && is_empty_block(block, codemap) &&
258 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width {
259 return Some(format!("{}{{}}", fn_str));
262 if self.config.fn_single_line && is_simple_block_stmt(block, codemap) {
264 if let Some(ref e) = block.expr {
265 let suffix = if semicolon_for_expr(e) {
271 e.rewrite(&self.get_context(),
272 self.config.max_width - self.block_indent.width(),
275 .or_else(|| Some(self.snippet(e.span)))
276 } else if let Some(ref stmt) = block.stmts.first() {
277 stmt.rewrite(&self.get_context(),
278 self.config.max_width - self.block_indent.width(),
285 if let Some(res) = rewrite {
286 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
287 if !res.contains('\n') && width <= self.config.max_width {
288 return Some(format!("{}{{ {} }}", fn_str, res));
296 pub fn visit_enum(&mut self,
298 vis: ast::Visibility,
299 enum_def: &ast::EnumDef,
300 generics: &ast::Generics,
302 let header_str = format_header("enum ", ident, vis);
303 self.buffer.push_str(&header_str);
305 let enum_snippet = self.snippet(span);
306 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
307 let generics_str = format_generics(&self.get_context(),
311 self.config.item_brace_style,
312 enum_def.variants.is_empty(),
314 self.block_indent.block_indent(self.config),
315 mk_sp(span.lo, body_start))
317 self.buffer.push_str(&generics_str);
319 self.last_pos = body_start;
321 self.block_indent = self.block_indent.block_indent(self.config);
322 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
324 Some(ref body_str) => self.buffer.push_str(&body_str),
325 None => self.format_missing(span.hi - BytePos(1)),
327 self.block_indent = self.block_indent.block_unindent(self.config);
329 if variant_list.is_some() {
330 self.buffer.push_str(&self.block_indent.to_string(self.config));
332 self.buffer.push_str("}");
333 self.last_pos = span.hi;
336 // Format the body of an enum definition
337 fn format_variant_list(&self,
338 enum_def: &ast::EnumDef,
342 if enum_def.variants.is_empty() {
345 let mut result = String::with_capacity(1024);
347 let indentation = self.block_indent.to_string(self.config);
348 result.push_str(&indentation);
350 let items = itemize_list(self.codemap,
351 enum_def.variants.iter(),
354 if !f.node.attrs.is_empty() {
355 f.node.attrs[0].span.lo
361 |f| self.format_variant(f),
365 let budget = self.config.max_width - self.block_indent.width() - 2;
366 let fmt = ListFormatting {
367 tactic: DefinitiveListTactic::Vertical,
369 trailing_separator: SeparatorTactic::from_bool(self.config.enum_trailing_comma),
370 indent: self.block_indent,
372 ends_with_newline: true,
376 let list = try_opt!(write_list(items, &fmt));
377 result.push_str(&list);
382 // Variant of an enum.
383 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
384 if contains_skip(&field.node.attrs) {
385 let lo = field.node.attrs[0].span.lo;
386 let span = mk_sp(lo, field.span.hi);
387 return Some(self.snippet(span));
390 let indent = self.block_indent;
391 let mut result = try_opt!(field.node
393 .rewrite(&self.get_context(),
394 self.config.max_width - indent.width(),
396 if !result.is_empty() {
398 result.push_str(&indent.to_string(self.config));
401 let context = self.get_context();
402 let variant_body = match field.node.data {
403 ast::VariantData::Tuple(..) |
404 ast::VariantData::Struct(..) => {
405 // FIXME: Should limit the width, as we have a trailing comma
406 format_struct(&context,
409 ast::Visibility::Inherited,
415 ast::VariantData::Unit(..) => {
416 let tag = if let Some(ref expr) = field.node.disr_expr {
417 format!("{} = {}", field.node.name, self.snippet(expr.span))
419 field.node.name.to_string()
423 self.config.max_width,
424 self.config.max_width - indent.width(),
429 if let Some(variant_str) = variant_body {
430 result.push_str(&variant_str);
438 pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
439 if let ast::Item_::ItemImpl(unsafety,
444 ref items) = item.node {
445 let mut result = String::new();
446 result.push_str(format_visibility(item.vis));
447 result.push_str(format_unsafety(unsafety));
448 result.push_str("impl");
450 let lo = span_after(item.span, "impl", context.codemap);
451 let hi = match *trait_ref {
452 Some(ref tr) => tr.path.span.lo,
453 None => self_ty.span.lo,
455 let generics_str = try_opt!(rewrite_generics(context,
458 offset + result.len(),
460 result.push_str(&generics_str);
462 // FIXME might need to linebreak in the impl header, here would be a
465 if polarity == ast::ImplPolarity::Negative {
466 result.push_str("!");
468 if let &Some(ref trait_ref) = trait_ref {
469 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
470 let indent = offset + result.len();
471 result.push_str(&*try_opt!(trait_ref.rewrite(context, budget, indent)));
472 result.push_str(" for ");
475 let budget = try_opt!(context.config.max_width.checked_sub(result.len()));
476 let indent = offset + result.len();
477 result.push_str(&*try_opt!(self_ty.rewrite(context, budget, indent)));
479 let where_clause_str = try_opt!(rewrite_where_clause(context,
480 &generics.where_clause,
482 context.block_indent,
483 context.config.where_density,
486 if !where_clause_str.contains('\n') &&
487 result.len() + where_clause_str.len() + offset.width() > context.config.max_width {
489 let width = context.block_indent.width() + context.config.tab_spaces - 1;
490 let where_indent = Indent::new(0, width);
491 result.push_str(&where_indent.to_string(context.config));
493 result.push_str(&where_clause_str);
495 match context.config.item_brace_style {
496 BraceStyle::AlwaysNextLine => result.push('\n'),
497 BraceStyle::PreferSameLine => result.push(' '),
498 BraceStyle::SameLineWhere => {
499 if where_clause_str.len() > 0 {
508 if !items.is_empty() {
509 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config, None);
510 visitor.block_indent = context.block_indent.block_indent(context.config);
512 let snippet = context.snippet(item.span);
513 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
514 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
517 visitor.visit_impl_item(&item);
521 result.push_str(trim_newlines(&visitor.buffer.to_string()));
524 let indent_str = context.block_indent.to_string(context.config);
525 result.push_str(&indent_str);
535 pub fn format_struct(context: &RewriteContext,
538 vis: ast::Visibility,
539 struct_def: &ast::VariantData,
540 generics: Option<&ast::Generics>,
545 ast::VariantData::Unit(..) => format_unit_struct(item_name, ident, vis),
546 ast::VariantData::Tuple(ref fields, _) => {
547 format_tuple_struct(context,
556 ast::VariantData::Struct(ref fields, _) => {
557 format_struct_struct(context,
569 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> Option<String> {
570 let mut result = String::with_capacity(1024);
572 let header_str = format_header(item_name, ident, vis);
573 result.push_str(&header_str);
579 fn format_struct_struct(context: &RewriteContext,
582 vis: ast::Visibility,
583 fields: &[ast::StructField],
584 generics: Option<&ast::Generics>,
588 let mut result = String::with_capacity(1024);
590 let header_str = format_header(item_name, ident, vis);
591 result.push_str(&header_str);
593 let body_lo = span_after(span, "{", context.codemap);
595 let generics_str = match generics {
597 try_opt!(format_generics(context,
601 context.config.item_brace_style,
604 offset + header_str.len(),
605 mk_sp(span.lo, body_lo)))
608 if context.config.item_brace_style == BraceStyle::AlwaysNextLine && !fields.is_empty() {
609 format!("\n{}{{", context.block_indent.to_string(context.config))
615 result.push_str(&generics_str);
617 // FIXME: properly format empty structs and their comments.
618 if fields.is_empty() {
619 result.push_str(&context.snippet(mk_sp(body_lo, span.hi)));
623 let item_indent = offset.block_indent(context.config);
625 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 1));
627 let items = itemize_list(context.codemap,
631 // Include attributes and doc comments, if present
632 if !field.node.attrs.is_empty() {
633 field.node.attrs[0].span.lo
638 |field| field.node.ty.span.hi,
639 |field| field.rewrite(context, item_budget, item_indent),
640 span_after(span, "{", context.codemap),
643 let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
644 let fmt = ListFormatting {
645 tactic: DefinitiveListTactic::Vertical,
647 trailing_separator: context.config.struct_trailing_comma,
650 ends_with_newline: true,
651 config: context.config,
653 Some(format!("{}\n{}{}\n{}}}",
655 offset.block_indent(context.config).to_string(context.config),
656 try_opt!(write_list(items, &fmt)),
657 offset.to_string(context.config)))
660 fn format_tuple_struct(context: &RewriteContext,
663 vis: ast::Visibility,
664 fields: &[ast::StructField],
665 generics: Option<&ast::Generics>,
669 assert!(!fields.is_empty(), "Tuple struct with no fields?");
670 let mut result = String::with_capacity(1024);
672 let header_str = format_header(item_name, ident, vis);
673 result.push_str(&header_str);
675 let body_lo = fields[0].span.lo;
677 let (generics_str, where_clause_str) = match generics {
678 Some(ref generics) => {
679 let generics_str = try_opt!(rewrite_generics(context,
682 offset + header_str.len(),
683 mk_sp(span.lo, body_lo)));
685 let where_clause_str = try_opt!(rewrite_where_clause(context,
686 &generics.where_clause,
688 context.block_indent,
693 (generics_str, where_clause_str)
695 None => ("".to_owned(), "".to_owned()),
697 result.push_str(&generics_str);
700 let item_indent = context.block_indent + result.len();
702 let item_budget = try_opt!(context.config.max_width.checked_sub(item_indent.width() + 2));
704 let items = itemize_list(context.codemap,
708 // Include attributes and doc comments, if present
709 if !field.node.attrs.is_empty() {
710 field.node.attrs[0].span.lo
715 |field| field.node.ty.span.hi,
716 |field| field.rewrite(context, item_budget, item_indent),
717 span_after(span, "(", context.codemap),
719 let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
720 result.push_str(&body);
723 if where_clause_str.len() > 0 && !where_clause_str.contains('\n') &&
724 (result.contains('\n') ||
725 context.block_indent.width() + result.len() + where_clause_str.len() + 1 >
726 context.config.max_width) {
727 // We need to put the where clause on a new line, but we didn'to_string
728 // know that earlier, so the where clause will not be indented properly.
730 result.push_str(&(context.block_indent + (context.config.tab_spaces - 1))
731 .to_string(context.config));
733 result.push_str(&where_clause_str);
738 impl Rewrite for ast::StructField {
739 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
740 if contains_skip(&self.node.attrs) {
741 let span = context.snippet(mk_sp(self.node.attrs[0].span.lo, self.span.hi));
742 return wrap_str(span, context.config.max_width, width, offset);
745 let name = match self.node.kind {
746 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
747 ast::StructFieldKind::UnnamedField(_) => None,
749 let vis = match self.node.kind {
750 ast::StructFieldKind::NamedField(_, vis) |
751 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
753 let mut attr_str = try_opt!(self.node
756 context.config.max_width - offset.width(),
758 if !attr_str.is_empty() {
760 attr_str.push_str(&offset.to_string(context.config));
763 let result = match name {
764 Some(name) => format!("{}{}{}: ", attr_str, vis, name),
765 None => format!("{}{}", attr_str, vis),
768 let last_line_width = last_line_width(&result);
769 let budget = try_opt!(width.checked_sub(last_line_width));
770 let rewrite = try_opt!(self.node.ty.rewrite(context, budget, offset + last_line_width));
771 Some(result + &rewrite)
775 pub fn rewrite_static(prefix: &str,
776 vis: ast::Visibility,
779 mutability: ast::Mutability,
781 context: &RewriteContext)
783 let prefix = format!("{}{} {}{}: ",
784 format_visibility(vis),
786 format_mutability(mutability),
789 let ty_str = try_opt!(ty.rewrite(context,
790 context.config.max_width - context.block_indent.width() -
792 context.block_indent));
793 let lhs = format!("{}{} =", prefix, ty_str);
796 let remaining_width = context.config.max_width - context.block_indent.width() - 1;
797 rewrite_assign_rhs(context, lhs, expr, remaining_width, context.block_indent).map(|s| s + ";")
800 impl Rewrite for ast::FunctionRetTy {
801 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
803 ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
804 ast::FunctionRetTy::NoReturn(_) => {
806 Some("-> !".to_owned())
811 ast::FunctionRetTy::Return(ref ty) => {
812 let inner_width = try_opt!(width.checked_sub(3));
813 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
819 impl Rewrite for ast::Arg {
820 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
821 if is_named_arg(self) {
822 if let ast::Ty_::TyInfer = self.ty.node {
823 wrap_str(pprust::pat_to_string(&self.pat),
824 context.config.max_width,
828 let mut result = pprust::pat_to_string(&self.pat);
829 result.push_str(": ");
830 let max_width = try_opt!(width.checked_sub(result.len()));
831 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
832 result.push_str(&ty_str);
836 self.ty.rewrite(context, width, offset)
841 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
842 match explicit_self.node {
843 ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
844 let mut_str = format_mutability(m);
846 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
847 None => Some(format!("&{}self", mut_str)),
850 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
851 Some(format!("self: {}", pprust::ty_to_string(ty)))
853 ast::ExplicitSelf_::SelfValue(_) => {
854 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
856 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
858 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
860 format_mutability(mutability)
862 panic!("there is a bug or change in structure of AST, aborting.");
866 Some(format!("{}self", mut_str))
872 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
873 if is_named_arg(arg) {
880 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
882 ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
887 fn is_named_arg(arg: &ast::Arg) -> bool {
888 if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
889 ident.node != token::special_idents::invalid
895 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
897 ast::FunctionRetTy::NoReturn(ref span) |
898 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
899 ast::FunctionRetTy::Return(ref ty) => ty.span,
903 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
904 // Note that ty.span is the span for ty.ident, not the whole item.
906 if let Some(ref def) = ty.default {
907 return mk_sp(lo, def.span.hi);
909 if ty.bounds.is_empty() {
912 let hi = match ty.bounds[ty.bounds.len() - 1] {
913 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
914 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
919 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
921 ast::WherePredicate::BoundPredicate(ref p) => p.span,
922 ast::WherePredicate::RegionPredicate(ref p) => p.span,
923 ast::WherePredicate::EqPredicate(ref p) => p.span,
927 // Return type is (result, force_new_line_for_brace)
928 fn rewrite_fn_base(context: &RewriteContext,
932 explicit_self: Option<&ast::ExplicitSelf>,
933 generics: &ast::Generics,
934 unsafety: ast::Unsafety,
935 constness: ast::Constness,
937 vis: ast::Visibility,
941 -> Option<(String, bool)> {
942 let mut force_new_line_for_brace = false;
943 // FIXME we'll lose any comments in between parts of the function decl, but
944 // anyone who comments there probably deserves what they get.
946 let where_clause = &generics.where_clause;
948 let mut result = String::with_capacity(1024);
950 result.push_str(format_visibility(vis));
951 result.push_str(::utils::format_unsafety(unsafety));
953 if let ast::Constness::Const = constness {
954 result.push_str("const ");
957 if abi != abi::Rust {
958 result.push_str(&::utils::format_abi(abi));
962 result.push_str("fn ");
963 result.push_str(&ident.to_string());
966 let generics_indent = indent + result.len();
967 let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
968 let generics_str = try_opt!(rewrite_generics(context,
973 result.push_str(&generics_str);
975 // Note that if the width and indent really matter, we'll re-layout the
976 // return type later anyway.
977 let ret_str = fd.output
978 .rewrite(&context, context.config.max_width - indent.width(), indent)
981 let multi_line_ret_str = ret_str.contains('\n');
982 let ret_str_len = if multi_line_ret_str {
989 let (mut one_line_budget, multi_line_budget, mut arg_indent) =
990 compute_budgets_for_args(context, &result, indent, ret_str_len, newline_brace);
992 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
997 // Check if vertical layout was forced by compute_budget_for_args.
998 if one_line_budget <= 0 {
999 if context.config.fn_args_paren_newline {
1001 result.push_str(&arg_indent.to_string(context.config));
1002 arg_indent = arg_indent + 1; // extra space for `(`
1005 result.push_str("(\n");
1006 result.push_str(&arg_indent.to_string(context.config));
1008 } else if context.config.fn_args_layout == StructLitStyle::Block {
1009 arg_indent = indent.block_indent(context.config);
1010 result.push_str("(\n");
1011 result.push_str(&arg_indent.to_string(context.config));
1016 if multi_line_ret_str {
1017 one_line_budget = 0;
1020 // A conservative estimation, to goal is to be over all parens in generics
1021 let args_start = generics.ty_params
1023 .map(|tp| end_typaram(tp))
1024 .unwrap_or(span.lo);
1025 let args_span = mk_sp(span_after(mk_sp(args_start, span.hi), "(", context.codemap),
1026 span_for_return(&fd.output).lo);
1027 let arg_str = try_opt!(rewrite_args(context,
1036 result.push_str(&arg_str);
1037 if context.config.fn_args_layout == StructLitStyle::Block {
1043 if !ret_str.is_empty() {
1044 // If we've already gone multi-line, or the return type would push
1045 // over the max width, then put the return type on a new line.
1046 // Unless we are formatting args like a block, in which case there
1047 // should always be room for the return type.
1048 let ret_indent = if (result.contains("\n") || multi_line_ret_str ||
1049 result.len() + indent.width() + ret_str_len >
1050 context.config.max_width) &&
1051 context.config.fn_args_layout != StructLitStyle::Block {
1052 let indent = match context.config.fn_return_indent {
1053 ReturnIndent::WithWhereClause => indent + 4,
1054 // Aligning with non-existent args looks silly.
1055 _ if arg_str.len() == 0 => {
1056 force_new_line_for_brace = true;
1059 // FIXME: we might want to check that using the arg indent
1060 // doesn't blow our budget, and if it does, then fallback to
1061 // the where clause indent.
1066 result.push_str(&indent.to_string(context.config));
1070 Indent::new(indent.width(), result.len())
1073 if multi_line_ret_str {
1074 // Now that we know the proper indent and width, we need to
1075 // re-layout the return type.
1077 let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
1078 let ret_str = fd.output
1079 .rewrite(context, budget, ret_indent)
1081 result.push_str(&ret_str);
1083 result.push_str(&ret_str);
1086 // Comment between return type and the end of the decl.
1087 let snippet_lo = fd.output.span().hi;
1088 if where_clause.predicates.is_empty() {
1089 let snippet_hi = span.hi;
1090 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1091 let snippet = snippet.trim();
1092 if !snippet.is_empty() {
1094 result.push_str(snippet);
1097 // FIXME it would be nice to catch comments between the return type
1098 // and the where clause, but we don't have a span for the where
1103 let where_density = if (context.config.where_density == Density::Compressed &&
1104 (!result.contains('\n') ||
1105 context.config.fn_args_layout == StructLitStyle::Block)) ||
1106 (context.config.fn_args_layout == StructLitStyle::Block &&
1107 ret_str.is_empty()) ||
1108 (context.config.where_density == Density::CompressedIfEmpty &&
1116 let where_clause_str = try_opt!(rewrite_where_clause(context,
1123 result.push_str(&where_clause_str);
1125 Some((result, force_new_line_for_brace))
1128 fn rewrite_args(context: &RewriteContext,
1130 explicit_self: Option<&ast::ExplicitSelf>,
1131 one_line_budget: usize,
1132 multi_line_budget: usize,
1138 let mut arg_item_strs = try_opt!(args.iter()
1140 arg.rewrite(&context, multi_line_budget, arg_indent)
1142 .collect::<Option<Vec<_>>>());
1144 // Account for sugary self.
1145 // FIXME: the comment for the self argument is dropped. This is blocked
1146 // on rust issue #27522.
1147 let min_args = explicit_self.and_then(|explicit_self| {
1148 rewrite_explicit_self(explicit_self, args)
1151 arg_item_strs[0] = self_str;
1156 // Comments between args.
1157 let mut arg_items = Vec::new();
1159 arg_items.push(ListItem::from_str(""));
1162 // FIXME(#21): if there are no args, there might still be a comment, but
1163 // without spans for the comment or parens, there is no chance of
1164 // getting it right. You also don't get to put a comment on self, unless
1166 if args.len() >= min_args || variadic {
1167 let comment_span_start = if min_args == 2 {
1168 span_after(span, ",", context.codemap)
1173 enum ArgumentKind<'a> {
1174 Regular(&'a ast::Arg),
1178 let variadic_arg = if variadic {
1179 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
1180 let variadic_start = span_after(variadic_span, "...", context.codemap) - BytePos(3);
1181 Some(ArgumentKind::Variadic(variadic_start))
1186 let more_items = itemize_list(context.codemap,
1187 args[min_args - 1..]
1189 .map(ArgumentKind::Regular)
1190 .chain(variadic_arg),
1194 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
1195 ArgumentKind::Variadic(start) => start,
1200 ArgumentKind::Regular(arg) => arg.ty.span.hi,
1201 ArgumentKind::Variadic(start) => start + BytePos(3),
1206 ArgumentKind::Regular(..) => None,
1207 ArgumentKind::Variadic(..) => Some("...".to_owned()),
1213 arg_items.extend(more_items);
1216 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
1217 item.item = Some(arg);
1220 let indent = match context.config.fn_arg_indent {
1221 BlockIndentStyle::Inherit => indent,
1222 BlockIndentStyle::Tabbed => indent.block_indent(context.config),
1223 BlockIndentStyle::Visual => arg_indent,
1226 let tactic = definitive_tactic(&arg_items,
1227 context.config.fn_args_density.to_list_tactic(),
1229 let budget = match tactic {
1230 DefinitiveListTactic::Horizontal => one_line_budget,
1231 _ => multi_line_budget,
1234 let fmt = ListFormatting {
1237 trailing_separator: SeparatorTactic::Never,
1240 ends_with_newline: false,
1241 config: context.config,
1244 write_list(&arg_items, &fmt)
1247 fn compute_budgets_for_args(context: &RewriteContext,
1251 newline_brace: bool)
1252 -> (usize, usize, Indent) {
1253 // Try keeping everything on the same line
1254 if !result.contains("\n") {
1255 // 3 = `() `, space is before ret_string
1256 let mut used_space = indent.width() + result.len() + ret_str_len + 3;
1260 let one_line_budget = if used_space > context.config.max_width {
1263 context.config.max_width - used_space
1267 let used_space = indent.width() + result.len() + 2;
1268 let max_space = context.config.max_width;
1269 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
1272 if used_space < max_space {
1273 return (one_line_budget,
1274 max_space - used_space,
1275 indent + result.len() + 1);
1279 // Didn't work. we must force vertical layout and put args on a newline.
1280 let new_indent = indent.block_indent(context.config);
1281 let used_space = new_indent.width() + 2; // account for `(` and `)`
1282 let max_space = context.config.max_width;
1283 if used_space <= max_space {
1284 (0, max_space - used_space, new_indent)
1286 // Whoops! bankrupt.
1287 // FIXME: take evasive action, perhaps kill the indent or something.
1288 panic!("in compute_budgets_for_args");
1292 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
1293 match config.fn_brace_style {
1294 BraceStyle::AlwaysNextLine => true,
1295 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
1300 fn rewrite_generics(context: &RewriteContext,
1301 generics: &ast::Generics,
1303 generics_offset: Indent,
1306 // FIXME: convert bounds to where clauses where they get too big or if
1307 // there is a where clause at all.
1308 let lifetimes: &[_] = &generics.lifetimes;
1309 let tys: &[_] = &generics.ty_params;
1310 if lifetimes.is_empty() && tys.is_empty() {
1311 return Some(String::new());
1314 let offset = match context.config.generics_indent {
1315 BlockIndentStyle::Inherit => offset,
1316 BlockIndentStyle::Tabbed => offset.block_indent(context.config),
1318 BlockIndentStyle::Visual => generics_offset + 1,
1321 let h_budget = context.config.max_width - generics_offset.width() - 2;
1322 // FIXME: might need to insert a newline if the generics are really long.
1324 // Strings for the generics.
1325 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset));
1326 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(&context, h_budget, offset));
1328 // Extract comments between generics.
1329 let lt_spans = lifetimes.iter().map(|l| {
1330 let hi = if l.bounds.is_empty() {
1333 l.bounds[l.bounds.len() - 1].span.hi
1335 mk_sp(l.lifetime.span.lo, hi)
1337 let ty_spans = tys.iter().map(span_for_ty_param);
1339 let items = itemize_list(context.codemap,
1340 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
1344 // FIXME: don't clone
1345 |&(_, ref str)| str.clone(),
1346 span_after(span, "<", context.codemap),
1348 let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));
1350 Some(format!("<{}>", list_str))
1353 fn rewrite_where_clause(context: &RewriteContext,
1354 where_clause: &ast::WhereClause,
1359 span_end: Option<BytePos>)
1361 if where_clause.predicates.is_empty() {
1362 return Some(String::new());
1365 let extra_indent = match context.config.where_indent {
1366 BlockIndentStyle::Inherit => Indent::empty(),
1367 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces, 0),
1370 let offset = match context.config.where_pred_indent {
1371 BlockIndentStyle::Inherit => indent + extra_indent,
1372 BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
1373 // 6 = "where ".len()
1374 BlockIndentStyle::Visual => indent + extra_indent + 6,
1376 // FIXME: if where_pred_indent != Visual, then the budgets below might
1377 // be out by a char or two.
1379 let budget = context.config.max_width - offset.width();
1380 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
1381 // If we don't have the start of the next span, then use the end of the
1382 // predicates, but that means we miss comments.
1383 let len = where_clause.predicates.len();
1384 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
1385 let span_end = span_end.unwrap_or(end_of_preds);
1386 let items = itemize_list(context.codemap,
1387 where_clause.predicates.iter(),
1389 |pred| span_for_where_pred(pred).lo,
1390 |pred| span_for_where_pred(pred).hi,
1391 |pred| pred.rewrite(&context, budget, offset),
1394 let item_vec = items.collect::<Vec<_>>();
1395 // FIXME: we don't need to collect here if the where_layout isn't
1396 // HorizontalVertical.
1397 let tactic = definitive_tactic(&item_vec, context.config.where_layout, budget);
1399 let fmt = ListFormatting {
1402 trailing_separator: SeparatorTactic::Never,
1405 ends_with_newline: true,
1406 config: context.config,
1408 let preds_str = try_opt!(write_list(&item_vec, &fmt));
1410 // 9 = " where ".len() + " {".len()
1411 if density == Density::Tall || preds_str.contains('\n') ||
1412 indent.width() + 9 + preds_str.len() > context.config.max_width {
1413 Some(format!("\n{}where {}",
1414 (indent + extra_indent).to_string(context.config),
1417 Some(format!(" where {}", preds_str))
1421 fn format_header(item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
1422 format!("{}{}{}", format_visibility(vis), item_name, ident)
1425 fn format_generics(context: &RewriteContext,
1426 generics: &ast::Generics,
1429 brace_style: BraceStyle,
1430 force_same_line_brace: bool,
1432 generics_offset: Indent,
1435 let mut result = try_opt!(rewrite_generics(context, generics, offset, generics_offset, span));
1437 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
1438 let where_clause_str = try_opt!(rewrite_where_clause(context,
1439 &generics.where_clause,
1441 context.block_indent,
1445 result.push_str(&where_clause_str);
1446 if !force_same_line_brace &&
1447 (brace_style == BraceStyle::SameLineWhere || brace_style == BraceStyle::AlwaysNextLine) {
1449 result.push_str(&context.block_indent.to_string(context.config));
1453 result.push_str(opener);
1455 if !force_same_line_brace && brace_style == BraceStyle::AlwaysNextLine {
1457 result.push_str(&context.block_indent.to_string(context.config));
1461 result.push_str(opener);