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, colon_spaces, mk_sp};
18 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
19 DefinitiveListTactic, ListTactic, definitive_tactic};
20 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
21 rewrite_call_inner, ExprType};
22 use comment::{FindUncommented, contains_comment, rewrite_comment, recover_comment_removed};
23 use visitor::FmtVisitor;
24 use rewrite::{Rewrite, RewriteContext};
25 use config::{Config, IndentStyle, Density, ReturnIndent, BraceStyle, Style};
26 use types::join_bounds;
27 use vertical::rewrite_with_alignment;
29 use syntax::{ast, abi, ptr, symbol};
30 use syntax::codemap::{Span, BytePos};
31 use syntax::ast::ImplItem;
33 fn type_annotation_separator(config: &Config) -> &str {
35 config.space_before_type_annotation(),
36 config.space_after_type_annotation_colon(),
41 // Statements of the form
42 // let pat: ty = init;
43 impl Rewrite for ast::Local {
44 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
46 "Local::rewrite {:?} {} {:?}",
51 let mut result = "let ".to_owned();
54 let pat_shape = try_opt!(shape.offset_left(4));
56 let pat_shape = try_opt!(pat_shape.sub_width(1));
57 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
58 result.push_str(&pat_str);
60 // String that is placed within the assignment pattern and expression.
62 let mut infix = String::new();
64 if let Some(ref ty) = self.ty {
65 let separator = type_annotation_separator(context.config);
66 let indent = shape.indent + last_line_width(&result) + separator.len();
68 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
69 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
71 infix.push_str(separator);
72 infix.push_str(&rewrite);
75 if self.init.is_some() {
82 result.push_str(&infix);
84 if let Some(ref ex) = self.init {
85 // 1 = trailing semicolon;
86 let nested_shape = try_opt!(shape.sub_width(1));
88 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
96 // TODO convert to using rewrite style rather than visitor
97 // TODO format modules in this style
100 keyword: &'static str,
102 vis: Option<&'a ast::Visibility>,
103 body: Vec<BodyElement<'a>>,
108 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
109 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
112 format!("extern {}", fm.abi)
120 .map(|i| BodyElement::ForeignItem(i))
127 enum BodyElement<'a> {
128 // Stmt(&'a ast::Stmt),
129 // Field(&'a ast::Field),
130 // Variant(&'a ast::Variant),
131 // Item(&'a ast::Item),
132 ForeignItem(&'a ast::ForeignItem),
135 impl<'a> FmtVisitor<'a> {
136 fn format_item(&mut self, item: Item) {
137 self.buffer.push_str(&item.abi);
138 self.buffer.push_str(" ");
140 let snippet = self.snippet(item.span);
141 let brace_pos = snippet.find_uncommented("{").unwrap();
143 self.buffer.push_str("{");
144 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
145 // FIXME: this skips comments between the extern keyword and the opening
147 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
148 self.block_indent = self.block_indent.block_indent(self.config);
150 if item.body.is_empty() {
151 self.format_missing_no_indent(item.span.hi - BytePos(1));
152 self.block_indent = self.block_indent.block_unindent(self.config);
155 .push_str(&self.block_indent.to_string(self.config));
157 for item in &item.body {
158 self.format_body_element(item);
161 self.block_indent = self.block_indent.block_unindent(self.config);
162 self.format_missing_with_indent(item.span.hi - BytePos(1));
166 self.buffer.push_str("}");
167 self.last_pos = item.span.hi;
170 fn format_body_element(&mut self, element: &BodyElement) {
172 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
176 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
177 let item = Item::from_foreign_mod(fm, span, self.config);
178 self.format_item(item);
181 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
182 self.format_missing_with_indent(item.span.lo);
183 // Drop semicolon or it will be interpreted as comment.
184 // FIXME: this may be a faulty span from libsyntax.
185 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
188 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
189 let indent = self.block_indent;
190 let rewrite = rewrite_fn_base(
196 ast::Unsafety::Normal,
197 ast::Constness::NotConst,
198 ast::Defaultness::Final,
199 // These are not actually rust functions,
200 // but we format them as such.
210 Some((new_fn, _)) => {
211 self.buffer.push_str(&new_fn);
212 self.buffer.push_str(";");
214 None => self.format_missing(item.span.hi),
217 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
218 // FIXME(#21): we're dropping potential comments in between the
219 // function keywords here.
220 let vis = format_visibility(&item.vis);
221 let mut_str = if is_mutable { "mut " } else { "" };
222 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
223 let offset = self.block_indent + prefix.len();
225 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
226 let rewrite = ty.rewrite(&self.get_context(), shape);
230 self.buffer.push_str(&prefix);
231 self.buffer.push_str(&result);
232 self.buffer.push_str(";");
234 None => self.format_missing(item.span.hi),
239 self.last_pos = item.span.hi;
247 generics: &ast::Generics,
248 unsafety: ast::Unsafety,
249 constness: ast::Constness,
250 defaultness: ast::Defaultness,
252 vis: &ast::Visibility,
255 ) -> Option<String> {
256 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
257 let context = self.get_context();
259 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
260 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
261 !context.config.fn_empty_single_line();
263 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
280 if force_newline_brace {
281 newline_brace = true;
282 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
283 !result.contains('\n')
285 newline_brace = false;
288 // Prepare for the function body by possibly adding a newline and
290 // FIXME we'll miss anything between the end of the signature and the
291 // start of the body, but we need more spans from the compiler to solve
295 result.push_str(&indent.to_string(self.config));
300 self.single_line_fn(&result, block).or_else(|| Some(result))
303 pub fn rewrite_required_fn(
307 sig: &ast::MethodSig,
309 ) -> Option<String> {
310 // Drop semicolon or it will be interpreted as comment.
311 let span = mk_sp(span.lo, span.hi - BytePos(1));
312 let context = self.get_context();
314 let (mut result, _) = try_opt!(rewrite_fn_base(
322 ast::Defaultness::Final,
324 &ast::Visibility::Inherited,
331 // Re-attach semicolon
337 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
338 if fn_str.contains('\n') {
342 let codemap = self.get_context().codemap;
344 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
345 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
347 return Some(format!("{}{{}}", fn_str));
350 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
352 if let Some(ref stmt) = block.stmts.first() {
353 match stmt_expr(stmt) {
355 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
361 Shape::indented(self.block_indent, self.config),
362 ).map(|s| s + suffix)
363 .or_else(|| Some(self.snippet(e.span)))
368 Shape::indented(self.block_indent, self.config),
377 if let Some(res) = rewrite {
378 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
379 if !res.contains('\n') && width <= self.config.max_width() {
380 return Some(format!("{}{{ {} }}", fn_str, res));
391 vis: &ast::Visibility,
392 enum_def: &ast::EnumDef,
393 generics: &ast::Generics,
396 let enum_header = format_header("enum ", ident, vis);
397 self.buffer.push_str(&enum_header);
399 let enum_snippet = self.snippet(span);
400 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
401 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
402 let generics_str = format_generics(
407 self.config.item_brace_style(),
408 enum_def.variants.is_empty(),
410 mk_sp(span.lo, body_start),
411 last_line_width(&enum_header),
413 self.buffer.push_str(&generics_str);
415 self.last_pos = body_start;
417 self.block_indent = self.block_indent.block_indent(self.config);
418 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
420 Some(ref body_str) => self.buffer.push_str(body_str),
422 if contains_comment(&enum_snippet[brace_pos..]) {
423 self.format_missing_no_indent(span.hi - BytePos(1))
425 self.format_missing(span.hi - BytePos(1))
429 self.block_indent = self.block_indent.block_unindent(self.config);
431 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
433 .push_str(&self.block_indent.to_string(self.config));
435 self.buffer.push_str("}");
436 self.last_pos = span.hi;
439 // Format the body of an enum definition
440 fn format_variant_list(
442 enum_def: &ast::EnumDef,
445 ) -> Option<String> {
446 if enum_def.variants.is_empty() {
449 let mut result = String::with_capacity(1024);
451 let indentation = self.block_indent.to_string(self.config);
452 result.push_str(&indentation);
454 let items = itemize_list(
456 enum_def.variants.iter(),
458 |f| if !f.node.attrs.is_empty() {
459 f.node.attrs[0].span.lo
464 |f| self.format_variant(f),
469 let shape = Shape::indented(self.block_indent, self.config)
472 let fmt = ListFormatting {
473 tactic: DefinitiveListTactic::Vertical,
475 trailing_separator: self.config.trailing_comma(),
477 ends_with_newline: true,
481 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
482 result.push_str(&list);
487 // Variant of an enum.
488 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
489 if contains_skip(&field.node.attrs) {
490 let lo = field.node.attrs[0].span.lo;
491 let span = mk_sp(lo, field.span.hi);
492 return Some(self.snippet(span));
495 let context = self.get_context();
496 let indent = self.block_indent;
497 let mut result = try_opt!(
501 .rewrite(&context, Shape::indented(indent, self.config))
503 if !result.is_empty() {
505 width: context.config.max_width(),
506 indent: self.block_indent,
507 offset: self.block_indent.alignment,
509 let missing_comment = rewrite_missing_comment_on_field(
512 field.node.attrs[field.node.attrs.len() - 1].span.hi,
515 ).unwrap_or(String::new());
516 result.push_str(&missing_comment);
519 let variant_body = match field.node.data {
520 ast::VariantData::Tuple(..) |
521 ast::VariantData::Struct(..) => {
522 // FIXME: Should limit the width, as we have a trailing comma
527 &ast::Visibility::Inherited,
532 Some(self.config.struct_variant_width()),
535 ast::VariantData::Unit(..) => {
536 let tag = if let Some(ref expr) = field.node.disr_expr {
537 format!("{} = {}", field.node.name, self.snippet(expr.span))
539 field.node.name.to_string()
544 self.config.max_width(),
545 Shape::indented(indent, self.config),
550 if let Some(variant_str) = variant_body {
551 result.push_str(&variant_str);
560 context: &RewriteContext,
563 where_span_end: Option<BytePos>,
564 ) -> Option<String> {
565 if let ast::ItemKind::Impl(_, _, _, ref generics, _, _, ref items) = item.node {
566 let mut result = String::new();
567 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
568 result.push_str(&ref_and_type);
570 let where_budget = if result.contains('\n') {
571 context.config.max_width()
576 .checked_sub(last_line_width(&result))
579 let where_clause_str = try_opt!(rewrite_where_clause(
581 &generics.where_clause,
582 context.config.item_brace_style(),
583 Shape::legacy(where_budget, offset.block_only()),
584 context.config.where_density(),
587 last_line_width(&ref_and_type) == 1,
591 if try_opt!(is_impl_single_line(
598 result.push_str(&where_clause_str);
599 if where_clause_str.contains('\n') {
600 let white_space = offset.to_string(context.config);
601 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
603 result.push_str(" {}");
608 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
610 let width = offset.block_indent + context.config.tab_spaces() - 1;
611 let where_indent = Indent::new(0, width);
612 result.push_str(&where_indent.to_string(context.config));
614 result.push_str(&where_clause_str);
616 match context.config.item_brace_style() {
617 BraceStyle::AlwaysNextLine => {
619 result.push_str(&offset.to_string(context.config));
621 BraceStyle::PreferSameLine => result.push(' '),
622 BraceStyle::SameLineWhere => {
623 if !where_clause_str.is_empty() {
625 result.push_str(&offset.to_string(context.config));
634 let snippet = context.snippet(item.span);
635 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
637 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
638 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
639 visitor.block_indent = offset.block_only().block_indent(context.config);
640 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
643 visitor.visit_impl_item(item);
646 visitor.format_missing(item.span.hi - BytePos(1));
648 let inner_indent_str = visitor.block_indent.to_string(context.config);
649 let outer_indent_str = offset.block_only().to_string(context.config);
652 result.push_str(&inner_indent_str);
653 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
655 result.push_str(&outer_indent_str);
658 if result.chars().last().unwrap() == '{' {
660 result.push_str(&offset.to_string(context.config));
670 fn is_impl_single_line(
671 context: &RewriteContext,
674 where_clause_str: &str,
677 let snippet = context.snippet(item.span);
678 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
681 context.config.impl_empty_single_line() && items.is_empty() &&
682 result.len() + where_clause_str.len() <= context.config.max_width() &&
683 !contains_comment(&snippet[open_pos..]),
687 fn format_impl_ref_and_type(
688 context: &RewriteContext,
691 ) -> Option<String> {
692 if let ast::ItemKind::Impl(
702 let mut result = String::new();
704 result.push_str(&format_visibility(&item.vis));
705 result.push_str(format_unsafety(unsafety));
706 result.push_str("impl");
708 let lo = context.codemap.span_after(item.span, "impl");
709 let hi = match *trait_ref {
710 Some(ref tr) => tr.path.span.lo,
711 None => self_ty.span.lo,
713 let shape = try_opt!(generics_shape_from_config(
715 Shape::indented(offset + last_line_width(&result), context.config),
718 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
719 let generics_str = try_opt!(rewrite_generics_inner(
727 let polarity_str = if polarity == ast::ImplPolarity::Negative {
733 if let Some(ref trait_ref) = *trait_ref {
734 let result_len = result.len();
735 if let Some(trait_ref_str) =
745 result.push_str(&trait_ref_str);
747 let generics_str = try_opt!(rewrite_generics_inner(
754 result.push_str(&try_opt!(rewrite_trait_ref(
765 result.push_str(&generics_str);
768 // Try to put the self type in a single line.
770 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
771 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
772 // If there is no where clause adapt budget for type formatting to take space and curly
773 // brace into account.
774 match context.config.item_brace_style() {
775 BraceStyle::AlwaysNextLine => 0,
781 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
782 // 1 = space before the type.
786 .checked_sub(used_space + 1)
788 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
789 if !self_ty_str.contains('\n') {
790 if trait_ref.is_some() {
791 result.push_str(" for ");
795 result.push_str(&self_ty_str);
800 // Couldn't fit the self type on a single line, put it on a new line.
802 // Add indentation of one additional tab.
803 let new_line_offset = offset.block_indent(context.config);
804 result.push_str(&new_line_offset.to_string(context.config));
805 if trait_ref.is_some() {
806 result.push_str("for ");
808 let budget = context.config.max_width() - last_line_width(&result);
809 let type_offset = match context.config.where_style() {
810 Style::Legacy => new_line_offset + trait_ref_overhead,
811 Style::Rfc => new_line_offset,
813 result.push_str(&*try_opt!(
814 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
822 fn rewrite_trait_ref(
823 context: &RewriteContext,
824 trait_ref: &ast::TraitRef,
830 ) -> Option<String> {
831 // 1 = space between generics and trait_ref
832 let used_space = 1 + polarity_str.len() +
833 if generics_str.contains('\n') {
834 last_line_width(&generics_str)
836 result_len + generics_str.len()
838 let shape = Shape::indented(offset + used_space, context.config);
839 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
840 if !(retry && trait_ref_str.contains('\n')) {
849 // We could not make enough space for trait_ref, so put it on new line.
851 let offset = offset.block_indent(context.config);
852 let shape = Shape::indented(offset, context.config);
853 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
857 &offset.to_string(context.config),
866 pub fn format_struct(
867 context: &RewriteContext,
870 vis: &ast::Visibility,
871 struct_def: &ast::VariantData,
872 generics: Option<&ast::Generics>,
875 one_line_width: Option<usize>,
876 ) -> Option<String> {
878 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
879 ast::VariantData::Tuple(ref fields, _) => {
891 ast::VariantData::Struct(ref fields, _) => {
892 format_struct_struct(
907 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
908 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
911 let mut result = String::new();
912 let header = format!(
914 format_visibility(&item.vis),
915 format_unsafety(unsafety),
919 result.push_str(&header);
921 let body_lo = context.codemap.span_after(item.span, "{");
923 let shape = Shape::indented(offset + last_line_width(&result), context.config);
924 let generics_str = try_opt!(rewrite_generics(
928 mk_sp(item.span.lo, body_lo),
930 result.push_str(&generics_str);
932 let trait_bound_str = try_opt!(rewrite_trait_bounds(
935 Shape::indented(offset, context.config),
937 // If the trait, generics, and trait bound cannot fit on the same line,
938 // put the trait bounds on an indented new line
939 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
940 context.config.comment_width()
943 let trait_indent = offset.block_only().block_indent(context.config);
944 result.push_str(&trait_indent.to_string(context.config));
946 result.push_str(&trait_bound_str);
948 let has_body = !trait_items.is_empty();
950 let where_density = if (context.config.where_density() == Density::Compressed &&
951 (!result.contains('\n') ||
952 context.config.fn_args_layout() == IndentStyle::Block)) ||
953 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
954 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
955 !result.contains('\n'))
962 let where_budget = try_opt!(
966 .checked_sub(last_line_width(&result))
968 let where_clause_str = try_opt!(rewrite_where_clause(
970 &generics.where_clause,
971 context.config.item_brace_style(),
972 Shape::legacy(where_budget, offset.block_only()),
976 trait_bound_str.is_empty() && last_line_width(&generics_str) == 1,
979 // If the where clause cannot fit on the same line,
980 // put the where clause on a new line
981 if !where_clause_str.contains('\n') &&
982 last_line_width(&result) + where_clause_str.len() + offset.width() >
983 context.config.comment_width()
986 let width = offset.block_indent + context.config.tab_spaces() - 1;
987 let where_indent = Indent::new(0, width);
988 result.push_str(&where_indent.to_string(context.config));
990 result.push_str(&where_clause_str);
992 match context.config.item_brace_style() {
993 BraceStyle::AlwaysNextLine => {
995 result.push_str(&offset.to_string(context.config));
997 BraceStyle::PreferSameLine => result.push(' '),
998 BraceStyle::SameLineWhere => {
999 if !where_clause_str.is_empty() &&
1000 (!trait_items.is_empty() || result.contains('\n'))
1003 result.push_str(&offset.to_string(context.config));
1011 let snippet = context.snippet(item.span);
1012 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1014 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1015 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1016 visitor.block_indent = offset.block_only().block_indent(context.config);
1017 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1019 for item in trait_items {
1020 visitor.visit_trait_item(item);
1023 visitor.format_missing(item.span.hi - BytePos(1));
1025 let inner_indent_str = visitor.block_indent.to_string(context.config);
1026 let outer_indent_str = offset.block_only().to_string(context.config);
1029 result.push_str(&inner_indent_str);
1030 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1032 result.push_str(&outer_indent_str);
1033 } else if result.contains('\n') {
1044 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1045 format!("{};", format_header(item_name, ident, vis))
1048 fn format_struct_struct(
1049 context: &RewriteContext,
1052 vis: &ast::Visibility,
1053 fields: &[ast::StructField],
1054 generics: Option<&ast::Generics>,
1057 one_line_width: Option<usize>,
1058 ) -> Option<String> {
1059 let mut result = String::with_capacity(1024);
1061 let header_str = format_header(item_name, ident, vis);
1062 result.push_str(&header_str);
1064 let body_lo = context.codemap.span_after(span, "{");
1066 let generics_str = match generics {
1068 try_opt!(format_generics(
1073 context.config.item_brace_style(),
1076 mk_sp(span.lo, body_lo),
1077 last_line_width(&result),
1081 // 3 = ` {}`, 2 = ` {`.
1082 let overhead = if fields.is_empty() { 3 } else { 2 };
1083 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1084 !fields.is_empty()) ||
1088 .checked_sub(result.len())
1089 .unwrap_or(0) < overhead
1091 format!("\n{}{{", offset.block_only().to_string(context.config))
1098 let overhead = if fields.is_empty() { 1 } else { 0 };
1099 let max_len = context.config.max_width() - offset.width();
1100 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1102 result.push_str(&offset
1103 .block_indent(context.config)
1104 .to_string(context.config));
1105 result.push_str(&generics_str.trim_left());
1107 result.push_str(&generics_str);
1110 if fields.is_empty() {
1111 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1112 if snippet.trim().is_empty() {
1114 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1116 result.push_str(&snippet.trim_right());
1118 result.push_str(&offset.to_string(context.config));
1120 result.push_str(&snippet);
1123 return Some(result);
1126 let items_str = try_opt!(rewrite_with_alignment(
1129 Shape::indented(offset, context.config),
1130 mk_sp(body_lo, span.hi),
1131 one_line_width.unwrap_or(0),
1134 if one_line_width.is_some() && !items_str.contains('\n') {
1135 Some(format!("{} {} }}", result, items_str))
1141 .block_indent(context.config)
1142 .to_string(context.config),
1144 offset.to_string(context.config)
1149 fn format_tuple_struct(
1150 context: &RewriteContext,
1153 vis: &ast::Visibility,
1154 fields: &[ast::StructField],
1155 generics: Option<&ast::Generics>,
1158 ) -> Option<String> {
1159 let mut result = String::with_capacity(1024);
1161 let header_str = format_header(item_name, ident, vis);
1162 result.push_str(&header_str);
1164 let body_lo = if fields.is_empty() {
1165 context.codemap.span_after(span, "(")
1170 let where_clause_str = match generics {
1172 let budget = context.budget(last_line_width(&header_str));
1173 let shape = Shape::legacy(budget, offset);
1174 let g_span = mk_sp(span.lo, body_lo);
1175 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1176 result.push_str(&generics_str);
1178 let where_budget = context.budget(last_line_width(&result));
1179 try_opt!(rewrite_where_clause(
1181 &generics.where_clause,
1182 context.config.item_brace_style(),
1183 Shape::legacy(where_budget, offset.block_only()),
1184 Density::Compressed,
1191 None => "".to_owned(),
1194 if fields.is_empty() {
1196 let used_width = if result.contains('\n') {
1197 last_line_width(&result) + 3
1199 offset.width() + result.len() + 3
1201 if used_width > context.config.max_width() {
1203 result.push_str(&offset
1204 .block_indent(context.config)
1205 .to_string(context.config))
1208 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1209 if snippet.is_empty() {
1211 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1212 result.push_str(&snippet.trim_right());
1214 result.push_str(&offset.to_string(context.config));
1216 result.push_str(&snippet);
1221 let body = try_opt!(
1225 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1227 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1228 context.config.fn_call_width(),
1232 result.push_str(&body);
1235 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1236 (result.contains('\n') ||
1237 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1238 context.config.max_width())
1240 // We need to put the where clause on a new line, but we didn't
1241 // know that earlier, so the where clause will not be indented properly.
1243 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1244 .to_string(context.config));
1246 result.push_str(&where_clause_str);
1251 pub fn rewrite_type_alias(
1252 context: &RewriteContext,
1256 generics: &ast::Generics,
1257 vis: &ast::Visibility,
1259 ) -> Option<String> {
1260 let mut result = String::new();
1262 result.push_str(&format_visibility(vis));
1263 result.push_str("type ");
1264 result.push_str(&ident.to_string());
1267 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1268 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1269 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1270 result.push_str(&generics_str);
1272 let where_budget = try_opt!(
1276 .checked_sub(last_line_width(&result))
1278 let where_clause_str = try_opt!(rewrite_where_clause(
1280 &generics.where_clause,
1281 context.config.item_brace_style(),
1282 Shape::legacy(where_budget, indent),
1283 context.config.where_density(),
1289 result.push_str(&where_clause_str);
1290 result.push_str(" = ");
1292 let line_width = last_line_width(&result);
1293 // This checked_sub may fail as the extra space after '=' is not taken into account
1294 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1295 let budget = context
1298 .checked_sub(indent.width() + line_width + ";".len())
1300 let type_indent = indent + line_width;
1301 // Try to fit the type on the same line
1302 let ty_str = try_opt!(
1303 ty.rewrite(context, Shape::legacy(budget, type_indent))
1305 // The line was too short, try to put the type on the next line
1307 // Remove the space after '='
1309 let type_indent = indent.block_indent(context.config);
1311 result.push_str(&type_indent.to_string(context.config));
1312 let budget = try_opt!(
1316 .checked_sub(type_indent.width() + ";".len())
1318 ty.rewrite(context, Shape::legacy(budget, type_indent))
1321 result.push_str(&ty_str);
1322 result.push_str(";");
1326 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1328 if config.space_before_type_annotation() {
1333 if config.space_after_type_annotation_colon() {
1341 fn rewrite_missing_comment_on_field(
1342 context: &RewriteContext,
1346 result: &mut String,
1347 ) -> Option<String> {
1348 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1349 let newline_index = possibly_comment_snippet.find('\n');
1350 let comment_index = possibly_comment_snippet.find('/');
1351 match (newline_index, comment_index) {
1352 (Some(i), Some(j)) if i > j => result.push(' '),
1355 result.push_str(&shape.indent.to_string(context.config));
1358 let trimmed = possibly_comment_snippet.trim();
1359 if trimmed.is_empty() {
1362 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1363 format!("{}\n{}", s, shape.indent.to_string(context.config))
1368 pub fn rewrite_struct_field_prefix(
1369 context: &RewriteContext,
1370 field: &ast::StructField,
1372 ) -> Option<String> {
1373 let vis = format_visibility(&field.vis);
1374 let mut attr_str = try_opt!(
1377 .rewrite(context, Shape::indented(shape.indent, context.config))
1379 // Try format missing comments after attributes
1380 let missing_comment = if !field.attrs.is_empty() {
1381 rewrite_missing_comment_on_field(
1384 field.attrs[field.attrs.len() - 1].span.hi,
1387 ).unwrap_or(String::new())
1392 let type_annotation_spacing = type_annotation_spacing(context.config);
1393 Some(match field.ident {
1401 type_annotation_spacing.0
1404 None => format!("{}{}{}", attr_str, missing_comment, vis),
1408 fn rewrite_struct_field_type(
1409 context: &RewriteContext,
1410 last_line_width: usize,
1411 field: &ast::StructField,
1414 ) -> Option<String> {
1415 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1418 .rewrite(context, ty_shape)
1419 .map(|ty| format!("{}{}", spacing, ty))
1422 impl Rewrite for ast::StructField {
1423 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1424 rewrite_struct_field(context, self, shape, 0)
1428 pub fn rewrite_struct_field(
1429 context: &RewriteContext,
1430 field: &ast::StructField,
1432 lhs_max_width: usize,
1433 ) -> Option<String> {
1434 if contains_skip(&field.attrs) {
1435 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1436 return wrap_str(span, context.config.max_width(), shape);
1439 let type_annotation_spacing = type_annotation_spacing(context.config);
1440 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1442 // Try to put everything on a single line.
1443 let last_line_width = last_line_width(&prefix);
1444 let mut spacing = String::from(if field.ident.is_some() {
1445 type_annotation_spacing.1
1449 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1450 for _ in 0..lhs_offset {
1453 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1454 if let Some(ref ty) = ty_rewritten {
1455 if !ty.contains('\n') {
1456 return Some(prefix + &ty);
1460 // We must use multiline.
1461 let type_offset = shape.indent.block_indent(context.config);
1462 let rewrite_type_in_next_line = || {
1465 .rewrite(context, Shape::indented(type_offset, context.config))
1468 match ty_rewritten {
1469 // If we start from the next line and type fits in a single line, then do so.
1471 match rewrite_type_in_next_line() {
1472 Some(ref new_ty) if !new_ty.contains('\n') => {
1476 type_offset.to_string(&context.config),
1480 _ => Some(prefix + &ty),
1484 let ty = try_opt!(rewrite_type_in_next_line());
1488 type_offset.to_string(&context.config),
1495 pub fn rewrite_static(
1497 vis: &ast::Visibility,
1500 mutability: ast::Mutability,
1501 expr_opt: Option<&ptr::P<ast::Expr>>,
1504 context: &RewriteContext,
1505 ) -> Option<String> {
1506 let colon = colon_spaces(
1507 context.config.space_before_type_annotation(),
1508 context.config.space_after_type_annotation_colon(),
1510 let prefix = format!(
1512 format_visibility(vis),
1514 format_mutability(mutability),
1519 let ty_str = try_opt!(ty.rewrite(
1522 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1526 if let Some(expr) = expr_opt {
1527 let lhs = format!("{}{} =", prefix, ty_str);
1529 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1534 Shape::legacy(remaining_width, offset.block_only()),
1536 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1538 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1540 Some(format!("{}{};", prefix, ty_str))
1544 pub fn rewrite_associated_type(
1546 ty_opt: Option<&ptr::P<ast::Ty>>,
1547 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1548 context: &RewriteContext,
1550 ) -> Option<String> {
1551 let prefix = format!("type {}", ident);
1553 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1554 let shape = Shape::indented(indent, context.config);
1555 let bounds: &[_] = ty_param_bounds;
1556 let bound_str = try_opt!(
1559 .map(|ty_bound| ty_bound.rewrite(context, shape))
1560 .collect::<Option<Vec<_>>>()
1562 if bounds.len() > 0 {
1563 format!(": {}", join_bounds(context, shape, &bound_str))
1571 if let Some(ty) = ty_opt {
1572 let ty_str = try_opt!(ty.rewrite(
1575 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1576 indent.block_only(),
1579 Some(format!("{} = {};", prefix, ty_str))
1581 Some(format!("{}{};", prefix, type_bounds_str))
1585 pub fn rewrite_associated_impl_type(
1587 defaultness: ast::Defaultness,
1588 ty_opt: Option<&ptr::P<ast::Ty>>,
1589 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1590 context: &RewriteContext,
1592 ) -> Option<String> {
1593 let result = try_opt!(rewrite_associated_type(
1596 ty_param_bounds_opt,
1602 ast::Defaultness::Default => Some(format!("default {}", result)),
1607 impl Rewrite for ast::FunctionRetTy {
1608 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1610 ast::FunctionRetTy::Default(_) => Some(String::new()),
1611 ast::FunctionRetTy::Ty(ref ty) => {
1612 let inner_width = try_opt!(shape.width.checked_sub(3));
1613 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1614 .map(|r| format!("-> {}", r))
1620 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1622 ast::TyKind::Infer => {
1623 let original = context.snippet(ty.span);
1630 impl Rewrite for ast::Arg {
1631 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1632 if is_named_arg(self) {
1633 let mut result = try_opt!(
1635 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1638 if !is_empty_infer(context, &*self.ty) {
1639 if context.config.space_before_type_annotation() {
1640 result.push_str(" ");
1642 result.push_str(":");
1643 if context.config.space_after_type_annotation_colon() {
1644 result.push_str(" ");
1646 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1647 let ty_str = try_opt!(self.ty.rewrite(
1649 Shape::legacy(max_width, shape.indent + result.len()),
1651 result.push_str(&ty_str);
1656 self.ty.rewrite(context, shape)
1661 fn rewrite_explicit_self(
1662 explicit_self: &ast::ExplicitSelf,
1664 context: &RewriteContext,
1665 ) -> Option<String> {
1666 match explicit_self.node {
1667 ast::SelfKind::Region(lt, m) => {
1668 let mut_str = format_mutability(m);
1671 let lifetime_str = try_opt!(l.rewrite(
1673 Shape::legacy(context.config.max_width(), Indent::empty()),
1675 Some(format!("&{} {}self", lifetime_str, mut_str))
1677 None => Some(format!("&{}self", mut_str)),
1680 ast::SelfKind::Explicit(ref ty, _) => {
1681 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1683 let mutability = explicit_self_mutability(&args[0]);
1684 let type_str = try_opt!(ty.rewrite(
1686 Shape::legacy(context.config.max_width(), Indent::empty()),
1691 format_mutability(mutability),
1695 ast::SelfKind::Value(_) => {
1696 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1698 let mutability = explicit_self_mutability(&args[0]);
1700 Some(format!("{}self", format_mutability(mutability)))
1705 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1706 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1707 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1708 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1715 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1716 if is_named_arg(arg) {
1723 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1725 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1726 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1727 _ => arg.ty.span.hi,
1731 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1732 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1733 ident.node != symbol::keywords::Invalid.ident()
1739 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1741 ast::FunctionRetTy::Default(ref span) => span.clone(),
1742 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1746 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1747 // Note that ty.span is the span for ty.ident, not the whole item.
1748 let lo = if ty.attrs.is_empty() {
1753 if let Some(ref def) = ty.default {
1754 return mk_sp(lo, def.span.hi);
1756 if ty.bounds.is_empty() {
1757 return mk_sp(lo, ty.span.hi);
1759 let hi = match ty.bounds[ty.bounds.len() - 1] {
1760 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1761 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1766 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1768 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1769 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1770 ast::WherePredicate::EqPredicate(ref p) => p.span,
1774 // Return type is (result, force_new_line_for_brace)
1776 context: &RewriteContext,
1780 generics: &ast::Generics,
1781 unsafety: ast::Unsafety,
1782 constness: ast::Constness,
1783 defaultness: ast::Defaultness,
1785 vis: &ast::Visibility,
1787 newline_brace: bool,
1790 ) -> Option<(String, bool)> {
1791 let mut force_new_line_for_brace = false;
1793 let where_clause = &generics.where_clause;
1795 let mut result = String::with_capacity(1024);
1796 // Vis unsafety abi.
1797 result.push_str(&*format_visibility(vis));
1799 if let ast::Defaultness::Default = defaultness {
1800 result.push_str("default ");
1803 if let ast::Constness::Const = constness {
1804 result.push_str("const ");
1807 result.push_str(::utils::format_unsafety(unsafety));
1809 if abi != abi::Abi::Rust {
1810 result.push_str(&::utils::format_abi(
1812 context.config.force_explicit_abi(),
1817 result.push_str("fn ");
1818 result.push_str(&ident.to_string());
1821 let overhead = if has_braces && !newline_brace {
1828 let shape = try_opt!(
1829 Shape::indented(indent + last_line_width(&result), context.config).sub_width(overhead)
1831 let g_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1832 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1833 result.push_str(&generics_str);
1835 let snuggle_angle_bracket = generics_str
1838 .map_or(false, |l| l.trim_left().len() == 1);
1840 // Note that the width and indent don't really matter, we'll re-layout the
1841 // return type later anyway.
1842 let ret_str = try_opt!(
1844 .rewrite(&context, Shape::indented(indent, context.config))
1847 let multi_line_ret_str = ret_str.contains('\n');
1848 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1851 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1852 try_opt!(compute_budgets_for_args(
1861 if context.config.fn_args_layout() == IndentStyle::Block {
1862 arg_indent = indent.block_indent(context.config);
1864 multi_line_budget = context.config.max_width() - (arg_indent.width() + 1);
1868 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1874 // Check if vertical layout was forced.
1875 if one_line_budget == 0 {
1876 if snuggle_angle_bracket {
1879 if context.config.fn_args_paren_newline() {
1881 result.push_str(&arg_indent.to_string(context.config));
1882 if context.config.fn_args_layout() == IndentStyle::Visual {
1883 arg_indent = arg_indent + 1; // extra space for `(`
1887 result.push_str("(");
1888 if context.config.fn_args_layout() == IndentStyle::Visual {
1890 result.push_str(&arg_indent.to_string(context.config));
1897 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1901 if multi_line_ret_str {
1902 one_line_budget = 0;
1905 // A conservative estimation, to goal is to be over all parens in generics
1906 let args_start = generics
1909 .map_or(span.lo, |tp| end_typaram(tp));
1910 let args_span = mk_sp(
1911 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1912 span_for_return(&fd.output).lo,
1914 let arg_str = try_opt!(rewrite_args(
1917 fd.get_self().as_ref(),
1924 generics_str.contains('\n'),
1927 let multi_line_arg_str =
1928 arg_str.contains('\n') || arg_str.chars().last().map_or(false, |c| c == ',');
1930 let put_args_in_block = match context.config.fn_args_layout() {
1931 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1933 } && !fd.inputs.is_empty();
1935 let mut args_last_line_contains_comment = false;
1936 if put_args_in_block {
1937 arg_indent = indent.block_indent(context.config);
1939 result.push_str(&arg_indent.to_string(context.config));
1940 result.push_str(&arg_str);
1942 result.push_str(&indent.to_string(context.config));
1945 result.push_str(&arg_str);
1946 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1949 // If the last line of args contains comment, we cannot put the closing paren
1950 // on the same line.
1954 .map_or(false, |last_line| last_line.contains("//"))
1956 args_last_line_contains_comment = true;
1958 result.push_str(&arg_indent.to_string(context.config));
1964 if !ret_str.is_empty() {
1965 let ret_should_indent = match context.config.fn_args_layout() {
1966 // If our args are block layout then we surely must have space.
1967 IndentStyle::Block if put_args_in_block => false,
1969 // If we've already gone multi-line, or the return type would push over the max
1970 // width, then put the return type on a new line. With the +1 for the signature
1971 // length an additional space between the closing parenthesis of the argument and
1972 // the arrow '->' is considered.
1973 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1975 // If there is no where clause, take into account the space after the return type
1977 if where_clause.predicates.is_empty() {
1981 let overlong_sig = sig_length > context.config.max_width();
1983 (!args_last_line_contains_comment) &&
1984 (result.contains('\n') || multi_line_ret_str || overlong_sig)
1987 let ret_indent = if ret_should_indent {
1988 let indent = match context.config.fn_return_indent() {
1989 ReturnIndent::WithWhereClause => indent + 4,
1990 // Aligning with non-existent args looks silly.
1991 _ if arg_str.is_empty() => {
1992 force_new_line_for_brace = true;
1995 // FIXME: we might want to check that using the arg indent
1996 // doesn't blow our budget, and if it does, then fallback to
1997 // the where clause indent.
2002 result.push_str(&indent.to_string(context.config));
2006 Indent::new(indent.block_indent, last_line_width(&result))
2009 if multi_line_ret_str || ret_should_indent {
2010 // Now that we know the proper indent and width, we need to
2011 // re-layout the return type.
2012 let ret_str = try_opt!(
2014 .rewrite(context, Shape::indented(ret_indent, context.config))
2016 result.push_str(&ret_str);
2018 result.push_str(&ret_str);
2021 // Comment between return type and the end of the decl.
2022 let snippet_lo = fd.output.span().hi;
2023 if where_clause.predicates.is_empty() {
2024 let snippet_hi = span.hi;
2025 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2026 // Try to preserve the layout of the original snippet.
2027 let original_starts_with_newline = snippet
2029 .map_or(false, |i| snippet[i..].starts_with('\n'));
2030 let original_ends_with_newline = snippet
2031 .rfind(|c| c != ' ')
2032 .map_or(false, |i| snippet[i..].ends_with('\n'));
2033 let snippet = snippet.trim();
2034 if !snippet.is_empty() {
2035 result.push(if original_starts_with_newline {
2040 result.push_str(snippet);
2041 if original_ends_with_newline {
2042 force_new_line_for_brace = true;
2046 // FIXME it would be nice to catch comments between the return type
2047 // and the where clause, but we don't have a span for the where
2052 let should_compress_where = match context.config.where_density() {
2053 Density::Compressed => !result.contains('\n') || put_args_in_block,
2054 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2056 } || (put_args_in_block && ret_str.is_empty());
2058 if where_clause.predicates.len() == 1 && should_compress_where {
2059 let budget = try_opt!(
2063 .checked_sub(last_line_width(&result))
2065 if let Some(where_clause_str) =
2066 rewrite_where_clause(
2069 context.config.fn_brace_style(),
2070 Shape::legacy(budget, indent),
2071 Density::Compressed,
2074 put_args_in_block && ret_str.is_empty(),
2077 if !where_clause_str.contains('\n') {
2078 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
2082 result.push_str(&where_clause_str);
2084 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2085 return Some((result, force_new_line_for_brace));
2090 let where_clause_str = try_opt!(rewrite_where_clause(
2093 context.config.fn_brace_style(),
2094 Shape::indented(indent, context.config),
2098 put_args_in_block && ret_str.is_empty(),
2102 result.push_str(&where_clause_str);
2104 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2105 return Some((result, force_new_line_for_brace));
2108 fn last_line_contains_single_line_comment(s: &str) -> bool {
2109 s.lines().last().map_or(false, |l| l.contains("//"))
2113 context: &RewriteContext,
2115 explicit_self: Option<&ast::ExplicitSelf>,
2116 one_line_budget: usize,
2117 multi_line_budget: usize,
2122 generics_str_contains_newline: bool,
2123 ) -> Option<String> {
2124 let mut arg_item_strs = try_opt!(
2127 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2129 .collect::<Option<Vec<_>>>()
2132 // Account for sugary self.
2133 // FIXME: the comment for the self argument is dropped. This is blocked
2134 // on rust issue #27522.
2135 let min_args = explicit_self
2136 .and_then(|explicit_self| {
2137 rewrite_explicit_self(explicit_self, args, context)
2139 .map_or(1, |self_str| {
2140 arg_item_strs[0] = self_str;
2144 // Comments between args.
2145 let mut arg_items = Vec::new();
2147 arg_items.push(ListItem::from_str(""));
2150 // FIXME(#21): if there are no args, there might still be a comment, but
2151 // without spans for the comment or parens, there is no chance of
2152 // getting it right. You also don't get to put a comment on self, unless
2154 if args.len() >= min_args || variadic {
2155 let comment_span_start = if min_args == 2 {
2156 let second_arg_start = if arg_has_pattern(&args[1]) {
2161 let reduced_span = mk_sp(span.lo, second_arg_start);
2163 context.codemap.span_after_last(reduced_span, ",")
2168 enum ArgumentKind<'a> {
2169 Regular(&'a ast::Arg),
2173 let variadic_arg = if variadic {
2174 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2175 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2176 Some(ArgumentKind::Variadic(variadic_start))
2181 let more_items = itemize_list(
2183 args[min_args - 1..]
2185 .map(ArgumentKind::Regular)
2186 .chain(variadic_arg),
2189 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2190 ArgumentKind::Variadic(start) => start,
2193 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2194 ArgumentKind::Variadic(start) => start + BytePos(3),
2197 ArgumentKind::Regular(..) => None,
2198 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2204 arg_items.extend(more_items);
2207 let fits_in_one_line = !generics_str_contains_newline &&
2208 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2210 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2211 item.item = Some(arg);
2214 let last_line_ends_with_comment = arg_items
2217 .and_then(|item| item.post_comment.as_ref())
2218 .map_or(false, |s| s.trim().starts_with("//"));
2220 let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout() {
2221 IndentStyle::Block if fits_in_one_line => {
2223 indent.block_indent(context.config),
2224 SeparatorTactic::Never,
2228 IndentStyle::Block => {
2230 indent.block_indent(context.config),
2231 context.config.trailing_comma(),
2235 IndentStyle::Visual if last_line_ends_with_comment => {
2236 (arg_indent, context.config.trailing_comma(), true)
2238 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never, false),
2241 let tactic = definitive_tactic(
2243 context.config.fn_args_density().to_list_tactic(),
2246 let budget = match tactic {
2247 DefinitiveListTactic::Horizontal => one_line_budget,
2248 _ => multi_line_budget,
2251 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2253 let fmt = ListFormatting {
2256 trailing_separator: if variadic {
2257 SeparatorTactic::Never
2261 shape: Shape::legacy(budget, indent),
2262 ends_with_newline: end_with_newline,
2263 config: context.config,
2266 write_list(&arg_items, &fmt)
2269 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2270 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2271 ident.node != symbol::keywords::Invalid.ident()
2277 fn compute_budgets_for_args(
2278 context: &RewriteContext,
2282 newline_brace: bool,
2284 ) -> Option<((usize, usize, Indent))> {
2286 "compute_budgets_for_args {} {:?}, {}, {}",
2292 // Try keeping everything on the same line.
2293 if !result.contains('\n') {
2294 // 2 = `()`, 3 = `() `, space is before ret_string.
2295 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2296 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2306 let one_line_budget = context
2309 .checked_sub(used_space)
2312 if one_line_budget > 0 {
2314 let multi_line_overhead =
2315 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2316 let multi_line_budget =
2317 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2322 indent + result.len() + 1,
2327 // Didn't work. we must force vertical layout and put args on a newline.
2328 let new_indent = indent.block_indent(context.config);
2329 // Account for `)` and possibly ` {`.
2330 let used_space = new_indent.width() + if ret_str_len == 0 { 1 } else { 3 };
2331 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2332 Some((0, max_space, new_indent))
2335 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2336 match config.fn_brace_style() {
2337 BraceStyle::AlwaysNextLine => true,
2338 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
2343 fn rewrite_generics(
2344 context: &RewriteContext,
2345 generics: &ast::Generics,
2348 ) -> Option<String> {
2349 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2350 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2351 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2352 rewrite_generics_inner(context, generics, g_shape, 0, span)
2356 fn rewrite_generics_inner(
2357 context: &RewriteContext,
2358 generics: &ast::Generics,
2360 one_line_width: usize,
2362 ) -> Option<String> {
2363 // FIXME: convert bounds to where clauses where they get too big or if
2364 // there is a where clause at all.
2365 let lifetimes: &[_] = &generics.lifetimes;
2366 let tys: &[_] = &generics.ty_params;
2367 if lifetimes.is_empty() && tys.is_empty() {
2368 return Some(String::new());
2371 // Strings for the generics.
2372 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2373 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2375 // Extract comments between generics.
2376 let lt_spans = lifetimes.iter().map(|l| {
2377 let hi = if l.bounds.is_empty() {
2380 l.bounds[l.bounds.len() - 1].span.hi
2382 mk_sp(l.lifetime.span.lo, hi)
2384 let ty_spans = tys.iter().map(span_for_ty_param);
2386 let items = itemize_list(
2388 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2392 // FIXME: don't clone
2393 |&(_, ref str)| str.clone(),
2394 context.codemap.span_after(span, "<"),
2397 format_generics_item_list(context, items, shape, one_line_width)
2400 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2401 match config.generics_indent() {
2402 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2403 IndentStyle::Block => {
2407 .block_indent(config.tab_spaces())
2408 .with_max_width(config)
2414 pub fn format_generics_item_list<I>(
2415 context: &RewriteContext,
2418 one_line_budget: usize,
2421 I: Iterator<Item = ListItem>,
2423 let item_vec = items.collect::<Vec<_>>();
2425 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, one_line_budget);
2426 let ends_with_newline = context.config.generics_indent() == IndentStyle::Block &&
2427 tactic == DefinitiveListTactic::Vertical;
2428 let fmt = ListFormatting {
2431 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2432 SeparatorTactic::Never
2434 context.config.trailing_comma()
2437 ends_with_newline: ends_with_newline,
2438 config: context.config,
2441 let list_str = try_opt!(write_list(&item_vec, &fmt));
2443 Some(wrap_generics_with_angle_brackets(
2450 pub fn wrap_generics_with_angle_brackets(
2451 context: &RewriteContext,
2453 list_offset: Indent,
2455 if context.config.generics_indent() == IndentStyle::Block &&
2456 (list_str.contains('\n') || list_str.ends_with(','))
2460 list_offset.to_string(context.config),
2463 .block_unindent(context.config)
2464 .to_string(context.config)
2466 } else if context.config.spaces_within_angle_brackets() {
2467 format!("< {} >", list_str)
2469 format!("<{}>", list_str)
2473 fn rewrite_trait_bounds(
2474 context: &RewriteContext,
2475 type_param_bounds: &ast::TyParamBounds,
2477 ) -> Option<String> {
2478 let bounds: &[_] = type_param_bounds;
2480 if bounds.is_empty() {
2481 return Some(String::new());
2483 let bound_str = try_opt!(
2486 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2487 .collect::<Option<Vec<_>>>()
2489 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2492 fn rewrite_where_clause_rfc_style(
2493 context: &RewriteContext,
2494 where_clause: &ast::WhereClause,
2497 suppress_comma: bool,
2498 // where clause can be kept on the current line.
2500 span_end: Option<BytePos>,
2501 ) -> Option<String> {
2502 let block_shape = shape.block().with_max_width(context.config);
2504 let starting_newline = if snuggle {
2507 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2510 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2511 // each clause on one line, trailing comma (except if suppress_comma)
2512 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2513 // If we don't have the start of the next span, then use the end of the
2514 // predicates, but that means we miss comments.
2515 let len = where_clause.predicates.len();
2516 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2517 let span_end = span_end.unwrap_or(end_of_preds);
2518 let items = itemize_list(
2520 where_clause.predicates.iter(),
2522 |pred| span_for_where_pred(pred).lo,
2523 |pred| span_for_where_pred(pred).hi,
2524 |pred| pred.rewrite(context, block_shape),
2528 let comma_tactic = if suppress_comma {
2529 SeparatorTactic::Never
2531 context.config.trailing_comma()
2534 let fmt = ListFormatting {
2535 tactic: DefinitiveListTactic::Vertical,
2537 trailing_separator: comma_tactic,
2538 shape: clause_shape,
2539 ends_with_newline: true,
2540 config: context.config,
2542 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2547 clause_shape.indent.to_string(context.config),
2552 fn rewrite_where_clause(
2553 context: &RewriteContext,
2554 where_clause: &ast::WhereClause,
2555 brace_style: BraceStyle,
2559 suppress_comma: bool,
2561 span_end: Option<BytePos>,
2562 ) -> Option<String> {
2563 if where_clause.predicates.is_empty() {
2564 return Some(String::new());
2567 if context.config.where_style() == Style::Rfc {
2568 return rewrite_where_clause_rfc_style(
2579 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2581 let offset = match context.config.where_pred_indent() {
2582 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2583 // 6 = "where ".len()
2584 IndentStyle::Visual => shape.indent + extra_indent + 6,
2586 // FIXME: if where_pred_indent != Visual, then the budgets below might
2587 // be out by a char or two.
2589 let budget = context.config.max_width() - offset.width();
2590 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2591 // If we don't have the start of the next span, then use the end of the
2592 // predicates, but that means we miss comments.
2593 let len = where_clause.predicates.len();
2594 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2595 let span_end = span_end.unwrap_or(end_of_preds);
2596 let items = itemize_list(
2598 where_clause.predicates.iter(),
2600 |pred| span_for_where_pred(pred).lo,
2601 |pred| span_for_where_pred(pred).hi,
2602 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2606 let item_vec = items.collect::<Vec<_>>();
2607 // FIXME: we don't need to collect here if the where_layout isn't
2608 // HorizontalVertical.
2609 let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget);
2611 let mut comma_tactic = context.config.trailing_comma();
2612 // Kind of a hack because we don't usually have trailing commas in where clauses.
2613 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2614 comma_tactic = SeparatorTactic::Never;
2617 let fmt = ListFormatting {
2620 trailing_separator: comma_tactic,
2621 shape: Shape::legacy(budget, offset),
2622 ends_with_newline: true,
2623 config: context.config,
2625 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2627 let end_length = if terminator == "{" {
2628 // If the brace is on the next line we don't need to count it otherwise it needs two
2631 BraceStyle::AlwaysNextLine |
2632 BraceStyle::SameLineWhere => 0,
2633 BraceStyle::PreferSameLine => 2,
2635 } else if terminator == "=" {
2640 if density == Density::Tall || preds_str.contains('\n') ||
2641 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2645 (shape.indent + extra_indent).to_string(context.config),
2649 Some(format!(" where {}", preds_str))
2653 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2654 format!("{}{}{}", format_visibility(vis), item_name, ident)
2658 context: &RewriteContext,
2659 generics: &ast::Generics,
2662 brace_style: BraceStyle,
2663 force_same_line_brace: bool,
2667 ) -> Option<String> {
2668 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2669 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2671 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2672 let budget = try_opt!(
2676 .checked_sub(last_line_width(&result))
2678 let where_clause_str = try_opt!(rewrite_where_clause(
2680 &generics.where_clause,
2682 Shape::legacy(budget, offset.block_only()),
2686 trimmed_last_line_width(&result) == 1,
2689 result.push_str(&where_clause_str);
2690 let same_line_brace = force_same_line_brace ||
2691 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1);
2692 if !same_line_brace &&
2693 (brace_style == BraceStyle::SameLineWhere ||
2694 brace_style == BraceStyle::AlwaysNextLine)
2697 result.push_str(&offset.block_only().to_string(context.config));
2701 result.push_str(opener);
2703 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2704 brace_style != BraceStyle::AlwaysNextLine
2709 result.push_str(&offset.block_only().to_string(context.config));
2711 result.push_str(opener);