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.
15 use syntax::{abi, ast, ptr, symbol};
16 use syntax::ast::ImplItem;
17 use syntax::codemap::{BytePos, Span};
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
22 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
23 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
24 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
25 rewrite_call_inner, ExprType};
26 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
27 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
28 use rewrite::{Rewrite, RewriteContext};
29 use shape::{Indent, Shape};
30 use types::join_bounds;
31 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
32 format_constness, format_defaultness, format_mutability, format_unsafety,
33 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
34 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, stmt_expr,
35 trim_newlines, trimmed_last_line_width};
36 use vertical::rewrite_with_alignment;
37 use visitor::FmtVisitor;
39 fn type_annotation_separator(config: &Config) -> &str {
41 config.space_before_type_annotation(),
42 config.space_after_type_annotation_colon(),
46 // Statements of the form
47 // let pat: ty = init;
48 impl Rewrite for ast::Local {
49 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
51 "Local::rewrite {:?} {} {:?}",
57 skip_out_of_file_lines_range!(context, self.span);
59 if contains_skip(&self.attrs) {
63 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
64 let mut result = if attrs_str.is_empty() {
67 try_opt!(combine_strs_with_missing_comments(
72 self.attrs.last().map(|a| a.span.hi()).unwrap(),
81 let pat_shape = try_opt!(shape.offset_left(4));
83 let pat_shape = try_opt!(pat_shape.sub_width(1));
84 let pat_str = try_opt!(self.pat.rewrite(context, pat_shape));
85 result.push_str(&pat_str);
87 // String that is placed within the assignment pattern and expression.
89 let mut infix = String::with_capacity(32);
91 if let Some(ref ty) = self.ty {
92 let separator = type_annotation_separator(context.config);
93 let indent = shape.indent + last_line_width(&result) + separator.len();
95 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
96 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
98 infix.push_str(separator);
99 infix.push_str(&rewrite);
102 if self.init.is_some() {
103 infix.push_str(" =");
109 result.push_str(&infix);
111 if let Some(ref ex) = self.init {
112 // 1 = trailing semicolon;
113 let nested_shape = try_opt!(shape.sub_width(1));
115 result = try_opt!(rewrite_assign_rhs(context, result, ex, nested_shape));
123 // TODO convert to using rewrite style rather than visitor
124 // TODO format modules in this style
127 keyword: &'static str,
129 vis: Option<&'a ast::Visibility>,
130 body: Vec<BodyElement<'a>>,
135 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
136 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
139 format!("extern {}", fm.abi)
147 .map(|i| BodyElement::ForeignItem(i))
154 enum BodyElement<'a> {
155 // Stmt(&'a ast::Stmt),
156 // Field(&'a ast::Field),
157 // Variant(&'a ast::Variant),
158 // Item(&'a ast::Item),
159 ForeignItem(&'a ast::ForeignItem),
162 impl<'a> FmtVisitor<'a> {
163 fn format_item(&mut self, item: Item) {
164 self.buffer.push_str(&item.abi);
165 self.buffer.push_str(" ");
167 let snippet = self.snippet(item.span);
168 let brace_pos = snippet.find_uncommented("{").unwrap();
170 self.buffer.push_str("{");
171 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
172 // FIXME: this skips comments between the extern keyword and the opening
174 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
175 self.block_indent = self.block_indent.block_indent(self.config);
177 if item.body.is_empty() {
178 self.format_missing_no_indent(item.span.hi() - BytePos(1));
179 self.block_indent = self.block_indent.block_unindent(self.config);
182 .push_str(&self.block_indent.to_string(self.config));
184 for item in &item.body {
185 self.format_body_element(item);
188 self.block_indent = self.block_indent.block_unindent(self.config);
189 self.format_missing_with_indent(item.span.hi() - BytePos(1));
193 self.buffer.push_str("}");
194 self.last_pos = item.span.hi();
197 fn format_body_element(&mut self, element: &BodyElement) {
199 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
203 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
204 let item = Item::from_foreign_mod(fm, span, self.config);
205 self.format_item(item);
209 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
210 let rewrite = item.rewrite(&self.get_context(), self.shape());
211 self.push_rewrite(item.span(), rewrite);
212 self.last_pos = item.span.hi();
220 generics: &ast::Generics,
221 unsafety: ast::Unsafety,
222 constness: ast::Constness,
223 defaultness: ast::Defaultness,
225 vis: &ast::Visibility,
228 ) -> Option<String> {
229 let context = self.get_context();
231 let block_snippet = self.snippet(mk_sp(block.span.lo(), block.span.hi()));
232 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty()
233 || !context.config.fn_empty_single_line();
234 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
236 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
253 if force_newline_brace {
254 newline_brace = true;
255 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine
256 && !result.contains('\n')
258 newline_brace = false;
261 // Prepare for the function body by possibly adding a newline and
263 // FIXME we'll miss anything between the end of the signature and the
264 // start of the body, but we need more spans from the compiler to solve
268 result.push_str(&indent.to_string(self.config));
273 self.single_line_fn(&result, block).or_else(|| Some(result))
276 pub fn rewrite_required_fn(
280 sig: &ast::MethodSig,
282 ) -> Option<String> {
283 // Drop semicolon or it will be interpreted as comment.
284 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
285 let context = self.get_context();
287 let (mut result, _) = try_opt!(rewrite_fn_base(
295 ast::Defaultness::Final,
297 &ast::Visibility::Inherited,
304 // Re-attach semicolon
310 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
311 if fn_str.contains('\n') {
315 let codemap = self.get_context().codemap;
317 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
318 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
320 return Some(format!("{}{{}}", fn_str));
323 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
325 if let Some(stmt) = block.stmts.first() {
326 match stmt_expr(stmt) {
328 let suffix = if semicolon_for_expr(&self.get_context(), e) {
334 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
336 .or_else(|| Some(self.snippet(e.span)))
338 None => stmt.rewrite(&self.get_context(), self.shape()),
345 if let Some(res) = rewrite {
346 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
347 if !res.contains('\n') && width <= self.config.max_width() {
348 return Some(format!("{}{{ {} }}", fn_str, res));
359 vis: &ast::Visibility,
360 enum_def: &ast::EnumDef,
361 generics: &ast::Generics,
364 let enum_header = format_header("enum ", ident, vis);
365 self.buffer.push_str(&enum_header);
367 let enum_snippet = self.snippet(span);
368 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
369 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
370 let generics_str = format_generics(
375 self.config.item_brace_style(),
376 enum_def.variants.is_empty(),
378 mk_sp(span.lo(), body_start),
379 last_line_width(&enum_header),
381 self.buffer.push_str(&generics_str);
383 self.last_pos = body_start;
385 self.block_indent = self.block_indent.block_indent(self.config);
386 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
388 Some(ref body_str) => self.buffer.push_str(body_str),
389 None => if contains_comment(&enum_snippet[brace_pos..]) {
390 self.format_missing_no_indent(span.hi() - BytePos(1))
393 self.block_indent = self.block_indent.block_unindent(self.config);
395 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
397 .push_str(&self.block_indent.to_string(self.config));
399 self.buffer.push_str("}");
400 self.last_pos = span.hi();
403 // Format the body of an enum definition
404 fn format_variant_list(
406 enum_def: &ast::EnumDef,
409 ) -> Option<String> {
410 if enum_def.variants.is_empty() {
413 let mut result = String::with_capacity(1024);
415 let indentation = self.block_indent.to_string(self.config);
416 result.push_str(&indentation);
418 let items = itemize_list(
420 enum_def.variants.iter(),
422 |f| if !f.node.attrs.is_empty() {
423 f.node.attrs[0].span.lo()
428 |f| self.format_variant(f),
434 let shape = self.shape().sub_width(2).unwrap();
435 let fmt = ListFormatting {
436 tactic: DefinitiveListTactic::Vertical,
438 trailing_separator: self.config.trailing_comma(),
439 separator_place: SeparatorPlace::Back,
441 ends_with_newline: true,
442 preserve_newline: true,
446 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
447 result.push_str(&list);
452 // Variant of an enum.
453 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
454 if contains_skip(&field.node.attrs) {
455 let lo = field.node.attrs[0].span.lo();
456 let span = mk_sp(lo, field.span.hi());
457 return Some(self.snippet(span));
460 let context = self.get_context();
461 let indent = self.block_indent;
462 let shape = self.shape();
463 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
468 .map_or(field.span.lo(), |attr| attr.span.hi());
469 let span = mk_sp(lo, field.span.lo());
471 let variant_body = match field.node.data {
472 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
473 // FIXME: Should limit the width, as we have a trailing comma
474 try_opt!(format_struct(
478 &ast::Visibility::Inherited,
483 Some(self.config.struct_variant_width()),
486 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
488 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
489 if one_line_width <= shape.width {
490 format!("{} = {}", field.node.name, self.snippet(expr.span))
497 .block_indent(self.config)
498 .to_string(self.config),
499 self.snippet(expr.span)
503 String::from(field.node.name.to_string())
507 let attrs_extendable = attrs_str.is_empty()
508 || (context.config.attributes_on_same_line_as_variant()
509 && is_attributes_extendable(&attrs_str));
510 combine_strs_with_missing_comments(
522 context: &RewriteContext,
525 where_span_end: Option<BytePos>,
526 ) -> Option<String> {
527 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
528 let mut result = String::with_capacity(128);
529 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
530 let indent_str = offset.to_string(context.config);
531 let sep = format!("\n{}", &indent_str);
532 result.push_str(&ref_and_type);
534 let where_budget = if result.contains('\n') {
535 context.config.max_width()
537 context.budget(last_line_width(&result))
539 let option = WhereClauseOption::snuggled(&ref_and_type);
540 let where_clause_str = try_opt!(rewrite_where_clause(
542 &generics.where_clause,
543 context.config.item_brace_style(),
544 Shape::legacy(where_budget, offset.block_only()),
545 context.config.where_density(),
552 // If there is no where clause, we may have missing comments between the trait name and
553 // the opening brace.
554 if generics.where_clause.predicates.is_empty() {
555 if let Some(hi) = where_span_end {
556 match recover_missing_comment_in_span(
557 mk_sp(self_ty.span.hi(), hi),
558 Shape::indented(offset, context.config),
560 last_line_width(&result),
562 Some(ref missing_comment) if !missing_comment.is_empty() => {
563 result.push_str(missing_comment);
570 if try_opt!(is_impl_single_line(
577 result.push_str(&where_clause_str);
578 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
579 result.push_str(&format!("{}{{{}}}", &sep, &sep));
581 result.push_str(" {}");
586 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
588 let width = offset.block_indent + context.config.tab_spaces() - 1;
589 let where_indent = Indent::new(0, width);
590 result.push_str(&where_indent.to_string(context.config));
592 result.push_str(&where_clause_str);
594 match context.config.item_brace_style() {
595 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
596 BraceStyle::AlwaysNextLine => result.push_str(&sep),
597 BraceStyle::PreferSameLine => result.push(' '),
598 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
599 result.push_str(&sep);
607 let snippet = context.snippet(item.span);
608 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
610 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
611 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
612 visitor.block_indent = offset.block_only().block_indent(context.config);
613 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
615 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
617 visitor.visit_impl_item(item);
620 visitor.format_missing(item.span.hi() - BytePos(1));
622 let inner_indent_str = visitor.block_indent.to_string(context.config);
623 let outer_indent_str = offset.block_only().to_string(context.config);
626 result.push_str(&inner_indent_str);
627 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
629 result.push_str(&outer_indent_str);
632 if result.chars().last().unwrap() == '{' {
633 result.push_str(&sep);
643 fn is_impl_single_line(
644 context: &RewriteContext,
647 where_clause_str: &str,
650 let snippet = context.snippet(item.span);
651 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
654 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
655 && result.len() + where_clause_str.len() <= context.config.max_width()
656 && !contains_comment(&snippet[open_pos..]),
660 fn format_impl_ref_and_type(
661 context: &RewriteContext,
664 ) -> Option<String> {
665 if let ast::ItemKind::Impl(
675 let mut result = String::with_capacity(128);
677 result.push_str(&format_visibility(&item.vis));
678 result.push_str(format_defaultness(defaultness));
679 result.push_str(format_unsafety(unsafety));
680 result.push_str("impl");
682 let lo = context.codemap.span_after(item.span, "impl");
683 let hi = match *trait_ref {
684 Some(ref tr) => tr.path.span.lo(),
685 None => self_ty.span.lo(),
687 let shape = try_opt!(generics_shape_from_config(
689 Shape::indented(offset + last_line_width(&result), context.config),
692 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
693 let generics_str = try_opt!(rewrite_generics_inner(
701 let polarity_str = if polarity == ast::ImplPolarity::Negative {
707 if let Some(ref trait_ref) = *trait_ref {
708 let result_len = result.len();
709 if let Some(trait_ref_str) = rewrite_trait_ref(
718 result.push_str(&trait_ref_str);
720 let generics_str = try_opt!(rewrite_generics_inner(
727 result.push_str(&try_opt!(rewrite_trait_ref(
738 result.push_str(&generics_str);
741 // Try to put the self type in a single line.
743 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
744 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
745 // If there is no where clause adapt budget for type formatting to take space and curly
746 // brace into account.
747 match context.config.item_brace_style() {
748 BraceStyle::AlwaysNextLine => 0,
754 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
755 // 1 = space before the type.
756 let budget = context.budget(used_space + 1);
757 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
758 if !self_ty_str.contains('\n') {
759 if trait_ref.is_some() {
760 result.push_str(" for ");
764 result.push_str(&self_ty_str);
769 // Couldn't fit the self type on a single line, put it on a new line.
771 // Add indentation of one additional tab.
772 let new_line_offset = offset.block_indent(context.config);
773 result.push_str(&new_line_offset.to_string(context.config));
774 if trait_ref.is_some() {
775 result.push_str("for ");
777 let budget = context.budget(last_line_width(&result));
778 let type_offset = match context.config.where_style() {
779 Style::Legacy => new_line_offset + trait_ref_overhead,
780 Style::Rfc => new_line_offset,
782 result.push_str(&*try_opt!(
783 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
791 fn rewrite_trait_ref(
792 context: &RewriteContext,
793 trait_ref: &ast::TraitRef,
799 ) -> Option<String> {
800 // 1 = space between generics and trait_ref
801 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
802 let shape = Shape::indented(offset + used_space, context.config);
803 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
804 if !(retry && trait_ref_str.contains('\n')) {
813 // We could not make enough space for trait_ref, so put it on new line.
815 let offset = offset.block_indent(context.config);
816 let shape = Shape::indented(offset, context.config);
817 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
821 &offset.to_string(context.config),
830 pub fn format_struct(
831 context: &RewriteContext,
834 vis: &ast::Visibility,
835 struct_def: &ast::VariantData,
836 generics: Option<&ast::Generics>,
839 one_line_width: Option<usize>,
840 ) -> Option<String> {
842 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
843 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
853 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
867 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
868 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
871 let mut result = String::with_capacity(128);
872 let header = format!(
874 format_visibility(&item.vis),
875 format_unsafety(unsafety),
879 result.push_str(&header);
881 let body_lo = context.codemap.span_after(item.span, "{");
883 let shape = Shape::indented(offset + last_line_width(&result), context.config);
884 let generics_str = try_opt!(rewrite_generics(
888 mk_sp(item.span.lo(), body_lo),
890 result.push_str(&generics_str);
892 let trait_bound_str = try_opt!(rewrite_trait_bounds(
895 Shape::indented(offset, context.config),
897 // If the trait, generics, and trait bound cannot fit on the same line,
898 // put the trait bounds on an indented new line
899 if offset.width() + last_line_width(&result) + trait_bound_str.len()
900 > context.config.comment_width()
903 let trait_indent = offset.block_only().block_indent(context.config);
904 result.push_str(&trait_indent.to_string(context.config));
906 result.push_str(&trait_bound_str);
908 let has_body = !trait_items.is_empty();
910 let where_density = if (context.config.where_density() == Density::Compressed
911 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
912 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
913 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
914 && !result.contains('\n'))
921 let where_budget = context.budget(last_line_width(&result));
922 let pos_before_where = if type_param_bounds.is_empty() {
923 generics.where_clause.span.lo()
925 type_param_bounds[type_param_bounds.len() - 1].span().hi()
927 let option = WhereClauseOption::snuggled(&generics_str);
928 let where_clause_str = try_opt!(rewrite_where_clause(
930 &generics.where_clause,
931 context.config.item_brace_style(),
932 Shape::legacy(where_budget, offset.block_only()),
939 // If the where clause cannot fit on the same line,
940 // put the where clause on a new line
941 if !where_clause_str.contains('\n')
942 && last_line_width(&result) + where_clause_str.len() + offset.width()
943 > context.config.comment_width()
946 let width = offset.block_indent + context.config.tab_spaces() - 1;
947 let where_indent = Indent::new(0, width);
948 result.push_str(&where_indent.to_string(context.config));
950 result.push_str(&where_clause_str);
952 if generics.where_clause.predicates.is_empty() {
953 let item_snippet = context.snippet(item.span);
954 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
956 let comment_hi = body_lo - BytePos(1);
957 let comment_lo = item.span.lo() + BytePos(lo as u32);
958 if comment_lo < comment_hi {
959 match recover_missing_comment_in_span(
960 mk_sp(comment_lo, comment_hi),
961 Shape::indented(offset, context.config),
963 last_line_width(&result),
965 Some(ref missing_comment) if !missing_comment.is_empty() => {
966 result.push_str(missing_comment);
974 match context.config.item_brace_style() {
975 _ if last_line_contains_single_line_comment(&result) => {
977 result.push_str(&offset.to_string(context.config));
979 BraceStyle::AlwaysNextLine => {
981 result.push_str(&offset.to_string(context.config));
983 BraceStyle::PreferSameLine => result.push(' '),
984 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
985 && (!trait_items.is_empty() || result.contains('\n'))
988 result.push_str(&offset.to_string(context.config));
995 let snippet = context.snippet(item.span);
996 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
998 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
999 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1000 visitor.block_indent = offset.block_only().block_indent(context.config);
1001 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1003 for item in trait_items {
1004 visitor.visit_trait_item(item);
1007 visitor.format_missing(item.span.hi() - BytePos(1));
1009 let inner_indent_str = visitor.block_indent.to_string(context.config);
1010 let outer_indent_str = offset.block_only().to_string(context.config);
1013 result.push_str(&inner_indent_str);
1014 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1016 result.push_str(&outer_indent_str);
1017 } else if result.contains('\n') {
1028 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1029 format!("{};", format_header(item_name, ident, vis))
1032 pub fn format_struct_struct(
1033 context: &RewriteContext,
1036 vis: &ast::Visibility,
1037 fields: &[ast::StructField],
1038 generics: Option<&ast::Generics>,
1041 one_line_width: Option<usize>,
1042 ) -> Option<String> {
1043 let mut result = String::with_capacity(1024);
1045 let header_str = format_header(item_name, ident, vis);
1046 result.push_str(&header_str);
1048 let body_lo = context.codemap.span_after(span, "{");
1050 let generics_str = match generics {
1051 Some(g) => try_opt!(format_generics(
1056 context.config.item_brace_style(),
1059 mk_sp(span.lo(), body_lo),
1060 last_line_width(&result),
1063 // 3 = ` {}`, 2 = ` {`.
1064 let overhead = if fields.is_empty() { 3 } else { 2 };
1065 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1066 && !fields.is_empty())
1067 || context.config.max_width() < overhead + result.len()
1069 format!("\n{}{{", offset.block_only().to_string(context.config))
1076 let overhead = if fields.is_empty() { 1 } else { 0 };
1077 let total_width = result.len() + generics_str.len() + overhead;
1078 if !generics_str.is_empty() && !generics_str.contains('\n')
1079 && total_width > context.config.max_width()
1082 result.push_str(&offset.to_string(context.config));
1083 result.push_str(generics_str.trim_left());
1085 result.push_str(&generics_str);
1088 if fields.is_empty() {
1089 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1090 if snippet.trim().is_empty() {
1092 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1094 result.push_str(snippet.trim_right());
1096 result.push_str(&offset.to_string(context.config));
1098 result.push_str(&snippet);
1101 return Some(result);
1105 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1106 let one_line_budget =
1107 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1109 let items_str = try_opt!(rewrite_with_alignment(
1112 Shape::indented(offset, context.config),
1113 mk_sp(body_lo, span.hi()),
1117 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1118 Some(format!("{} {} }}", result, items_str))
1124 .block_indent(context.config)
1125 .to_string(context.config),
1127 offset.to_string(context.config)
1132 fn format_tuple_struct(
1133 context: &RewriteContext,
1136 vis: &ast::Visibility,
1137 fields: &[ast::StructField],
1138 generics: Option<&ast::Generics>,
1141 ) -> Option<String> {
1142 let mut result = String::with_capacity(1024);
1144 let header_str = format_header(item_name, ident, vis);
1145 result.push_str(&header_str);
1147 let body_lo = if fields.is_empty() {
1148 context.codemap.span_after(span, "(")
1152 let body_hi = if fields.is_empty() {
1153 context.codemap.span_after(span, ")")
1155 // This is a dirty hack to work around a missing `)` from the span of the last field.
1156 let last_arg_span = fields[fields.len() - 1].span;
1157 if context.snippet(last_arg_span).ends_with(')') {
1162 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1166 let where_clause_str = match generics {
1168 let budget = context.budget(last_line_width(&header_str));
1169 let shape = Shape::legacy(budget, offset);
1170 let g_span = mk_sp(span.lo(), body_lo);
1171 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1172 result.push_str(&generics_str);
1174 let where_budget = context.budget(last_line_width(&result));
1175 let option = WhereClauseOption::new(true, false);
1176 try_opt!(rewrite_where_clause(
1178 &generics.where_clause,
1179 context.config.item_brace_style(),
1180 Shape::legacy(where_budget, offset.block_only()),
1181 Density::Compressed,
1188 None => "".to_owned(),
1191 if fields.is_empty() {
1193 let used_width = last_line_used_width(&result, offset.width()) + 3;
1194 if used_width > context.config.max_width() {
1196 result.push_str(&offset
1197 .block_indent(context.config)
1198 .to_string(context.config))
1201 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1202 if snippet.is_empty() {
1204 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1205 result.push_str(snippet.trim_right());
1207 result.push_str(&offset.to_string(context.config));
1209 result.push_str(&snippet);
1214 let body = try_opt!(
1218 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1220 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1221 context.config.fn_call_width(),
1225 result.push_str(&body);
1228 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1229 && (result.contains('\n')
1230 || offset.block_indent + result.len() + where_clause_str.len() + 1
1231 > context.config.max_width())
1233 // We need to put the where clause on a new line, but we didn't
1234 // know that earlier, so the where clause will not be indented properly.
1236 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1237 .to_string(context.config));
1239 result.push_str(&where_clause_str);
1244 pub fn rewrite_type_alias(
1245 context: &RewriteContext,
1249 generics: &ast::Generics,
1250 vis: &ast::Visibility,
1252 ) -> Option<String> {
1253 let mut result = String::with_capacity(128);
1255 result.push_str(&format_visibility(vis));
1256 result.push_str("type ");
1257 result.push_str(&ident.to_string());
1260 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1261 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1262 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1263 result.push_str(&generics_str);
1265 let where_budget = context.budget(last_line_width(&result));
1266 let option = WhereClauseOption::snuggled(&result);
1267 let where_clause_str = try_opt!(rewrite_where_clause(
1269 &generics.where_clause,
1270 context.config.item_brace_style(),
1271 Shape::legacy(where_budget, indent),
1272 context.config.where_density(),
1278 result.push_str(&where_clause_str);
1279 if where_clause_str.is_empty() {
1280 result.push_str(" = ");
1282 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1285 let line_width = last_line_width(&result);
1286 // This checked_sub may fail as the extra space after '=' is not taken into account
1287 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1288 let budget = context.budget(indent.width() + line_width + ";".len());
1289 let type_indent = indent + line_width;
1290 // Try to fit the type on the same line
1291 let ty_str = try_opt!(
1292 ty.rewrite(context, Shape::legacy(budget, type_indent))
1294 // The line was too short, try to put the type on the next line
1296 // Remove the space after '='
1298 let type_indent = indent.block_indent(context.config);
1300 result.push_str(&type_indent.to_string(context.config));
1301 let budget = context.budget(type_indent.width() + ";".len());
1302 ty.rewrite(context, Shape::legacy(budget, type_indent))
1305 result.push_str(&ty_str);
1306 result.push_str(";");
1310 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1312 if config.space_before_type_annotation() {
1317 if config.space_after_type_annotation_colon() {
1325 pub fn rewrite_struct_field_prefix(
1326 context: &RewriteContext,
1327 field: &ast::StructField,
1328 ) -> Option<String> {
1329 let vis = format_visibility(&field.vis);
1330 let type_annotation_spacing = type_annotation_spacing(context.config);
1331 Some(match field.ident {
1332 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1333 None => format!("{}", vis),
1337 fn rewrite_struct_field_type(
1338 context: &RewriteContext,
1339 last_line_width: usize,
1340 field: &ast::StructField,
1343 ) -> Option<String> {
1344 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1347 .rewrite(context, ty_shape)
1348 .map(|ty| format!("{}{}", spacing, ty))
1351 impl Rewrite for ast::StructField {
1352 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1353 rewrite_struct_field(context, self, shape, 0)
1357 pub fn rewrite_struct_field(
1358 context: &RewriteContext,
1359 field: &ast::StructField,
1361 lhs_max_width: usize,
1362 ) -> Option<String> {
1363 if contains_skip(&field.attrs) {
1364 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1367 let type_annotation_spacing = type_annotation_spacing(context.config);
1368 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1370 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1371 let attrs_extendable = attrs_str.is_empty()
1372 || (context.config.attributes_on_same_line_as_field()
1373 && is_attributes_extendable(&attrs_str));
1374 let missing_span = if field.attrs.is_empty() {
1375 mk_sp(field.span.lo(), field.span.lo())
1377 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1379 let mut spacing = String::from(if field.ident.is_some() {
1380 type_annotation_spacing.1
1384 // Try to put everything on a single line.
1385 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1393 let overhead = last_line_width(&attr_prefix);
1394 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1395 for _ in 0..lhs_offset {
1398 // In this extreme case we will be missing a space betweeen an attribute and a field.
1399 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1402 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1403 if let Some(ref ty) = ty_rewritten {
1404 if !ty.contains('\n') {
1405 return Some(attr_prefix + ty);
1409 // We must use multiline.
1410 let last_line_width = last_line_width(&prefix);
1411 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1413 let type_offset = shape.indent.block_indent(context.config);
1414 let rewrite_type_in_next_line = || {
1417 .rewrite(context, Shape::indented(type_offset, context.config))
1420 let field_str = match ty_rewritten {
1421 // If we start from the next line and type fits in a single line, then do so.
1422 Some(ref ty) => match rewrite_type_in_next_line() {
1423 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1426 type_offset.to_string(context.config),
1432 let ty = try_opt!(rewrite_type_in_next_line());
1436 type_offset.to_string(context.config),
1441 combine_strs_with_missing_comments(
1451 pub fn rewrite_static(
1453 vis: &ast::Visibility,
1456 mutability: ast::Mutability,
1457 expr_opt: Option<&ptr::P<ast::Expr>>,
1460 context: &RewriteContext,
1461 ) -> Option<String> {
1462 let colon = colon_spaces(
1463 context.config.space_before_type_annotation(),
1464 context.config.space_after_type_annotation_colon(),
1466 let prefix = format!(
1468 format_visibility(vis),
1470 format_mutability(mutability),
1475 let ty_str = try_opt!(ty.rewrite(
1478 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1482 if let Some(expr) = expr_opt {
1483 let lhs = format!("{}{} =", prefix, ty_str);
1485 let remaining_width = context.budget(offset.block_indent + 1);
1490 Shape::legacy(remaining_width, offset.block_only()),
1491 ).and_then(|res| recover_comment_removed(res, span, context))
1492 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1494 Some(format!("{}{};", prefix, ty_str))
1498 pub fn rewrite_associated_type(
1500 ty_opt: Option<&ptr::P<ast::Ty>>,
1501 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1502 context: &RewriteContext,
1504 ) -> Option<String> {
1505 let prefix = format!("type {}", ident);
1507 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1509 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1510 let bounds: &[_] = ty_param_bounds;
1511 let bound_str = try_opt!(
1514 .map(|ty_bound| ty_bound.rewrite(context, shape))
1515 .collect::<Option<Vec<_>>>()
1517 if !bounds.is_empty() {
1518 format!(": {}", join_bounds(context, shape, &bound_str))
1526 if let Some(ty) = ty_opt {
1527 let ty_str = try_opt!(ty.rewrite(
1530 context.budget(indent.block_indent + prefix.len() + 2),
1531 indent.block_only(),
1534 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1536 Some(format!("{}{};", prefix, type_bounds_str))
1540 pub fn rewrite_associated_impl_type(
1542 defaultness: ast::Defaultness,
1543 ty_opt: Option<&ptr::P<ast::Ty>>,
1544 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1545 context: &RewriteContext,
1547 ) -> Option<String> {
1548 let result = try_opt!(rewrite_associated_type(
1551 ty_param_bounds_opt,
1557 ast::Defaultness::Default => Some(format!("default {}", result)),
1562 impl Rewrite for ast::FunctionRetTy {
1563 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1565 ast::FunctionRetTy::Default(_) => Some(String::new()),
1566 ast::FunctionRetTy::Ty(ref ty) => {
1567 let inner_width = try_opt!(shape.width.checked_sub(3));
1568 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1569 .map(|r| format!("-> {}", r))
1575 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1577 ast::TyKind::Infer => {
1578 let original = context.snippet(ty.span);
1585 impl Rewrite for ast::Arg {
1586 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1587 if is_named_arg(self) {
1588 let mut result = try_opt!(
1590 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1593 if !is_empty_infer(context, &*self.ty) {
1594 if context.config.space_before_type_annotation() {
1595 result.push_str(" ");
1597 result.push_str(":");
1598 if context.config.space_after_type_annotation_colon() {
1599 result.push_str(" ");
1601 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1602 let ty_str = try_opt!(self.ty.rewrite(
1604 Shape::legacy(max_width, shape.indent + result.len()),
1606 result.push_str(&ty_str);
1611 self.ty.rewrite(context, shape)
1616 fn rewrite_explicit_self(
1617 explicit_self: &ast::ExplicitSelf,
1619 context: &RewriteContext,
1620 ) -> Option<String> {
1621 match explicit_self.node {
1622 ast::SelfKind::Region(lt, m) => {
1623 let mut_str = format_mutability(m);
1626 let lifetime_str = try_opt!(l.rewrite(
1628 Shape::legacy(context.config.max_width(), Indent::empty()),
1630 Some(format!("&{} {}self", lifetime_str, mut_str))
1632 None => Some(format!("&{}self", mut_str)),
1635 ast::SelfKind::Explicit(ref ty, _) => {
1636 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1638 let mutability = explicit_self_mutability(&args[0]);
1639 let type_str = try_opt!(ty.rewrite(
1641 Shape::legacy(context.config.max_width(), Indent::empty()),
1646 format_mutability(mutability),
1650 ast::SelfKind::Value(_) => {
1651 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1653 let mutability = explicit_self_mutability(&args[0]);
1655 Some(format!("{}self", format_mutability(mutability)))
1660 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1661 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1662 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1663 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1670 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1671 if is_named_arg(arg) {
1678 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1680 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1681 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1682 _ => arg.ty.span.hi(),
1686 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1687 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1688 ident.node != symbol::keywords::Invalid.ident()
1694 // Return type is (result, force_new_line_for_brace)
1696 context: &RewriteContext,
1700 generics: &ast::Generics,
1701 unsafety: ast::Unsafety,
1702 constness: ast::Constness,
1703 defaultness: ast::Defaultness,
1705 vis: &ast::Visibility,
1707 newline_brace: bool,
1710 ) -> Option<(String, bool)> {
1711 let mut force_new_line_for_brace = false;
1713 let where_clause = &generics.where_clause;
1715 let mut result = String::with_capacity(1024);
1716 // Vis defaultness constness unsafety abi.
1717 result.push_str(&*format_visibility(vis));
1718 result.push_str(format_defaultness(defaultness));
1719 result.push_str(format_constness(constness));
1720 result.push_str(format_unsafety(unsafety));
1721 if abi != abi::Abi::Rust {
1722 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1726 result.push_str("fn ");
1727 result.push_str(&ident.to_string());
1730 let overhead = if has_braces && !newline_brace {
1737 let used_width = last_line_used_width(&result, indent.width());
1738 let one_line_budget = context.budget(used_width + overhead);
1740 width: one_line_budget,
1744 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1745 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1746 result.push_str(&generics_str);
1748 let snuggle_angle_bracket = generics_str
1751 .map_or(false, |l| l.trim_left().len() == 1);
1753 // Note that the width and indent don't really matter, we'll re-layout the
1754 // return type later anyway.
1755 let ret_str = try_opt!(
1757 .rewrite(context, Shape::indented(indent, context.config))
1760 let multi_line_ret_str = ret_str.contains('\n');
1761 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1764 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1775 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1781 // Check if vertical layout was forced.
1782 if one_line_budget == 0 {
1783 if snuggle_angle_bracket {
1785 } else if context.config.fn_args_paren_newline() {
1787 result.push_str(&arg_indent.to_string(context.config));
1788 if context.config.fn_args_layout() == IndentStyle::Visual {
1789 arg_indent = arg_indent + 1; // extra space for `(`
1793 result.push_str("(");
1794 if context.config.fn_args_layout() == IndentStyle::Visual {
1796 result.push_str(&arg_indent.to_string(context.config));
1802 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1806 // A conservative estimation, to goal is to be over all parens in generics
1807 let args_start = generics
1810 .map_or(span.lo(), |tp| end_typaram(tp));
1811 let args_end = if fd.inputs.is_empty() {
1814 .span_after(mk_sp(args_start, span.hi()), ")")
1816 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1817 context.codemap.span_after(last_span, ")")
1819 let args_span = mk_sp(
1822 .span_after(mk_sp(args_start, span.hi()), "("),
1825 let arg_str = try_opt!(rewrite_args(
1828 fd.get_self().as_ref(),
1835 generics_str.contains('\n'),
1838 let put_args_in_block = match context.config.fn_args_layout() {
1839 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1841 } && !fd.inputs.is_empty();
1843 let mut args_last_line_contains_comment = false;
1844 if put_args_in_block {
1845 arg_indent = indent.block_indent(context.config);
1847 result.push_str(&arg_indent.to_string(context.config));
1848 result.push_str(&arg_str);
1850 result.push_str(&indent.to_string(context.config));
1853 result.push_str(&arg_str);
1854 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1855 // Put the closing brace on the next line if it overflows the max width.
1857 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1860 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1863 // If the last line of args contains comment, we cannot put the closing paren
1864 // on the same line.
1868 .map_or(false, |last_line| last_line.contains("//"))
1870 args_last_line_contains_comment = true;
1872 result.push_str(&arg_indent.to_string(context.config));
1878 if let ast::FunctionRetTy::Ty(..) = fd.output {
1879 let ret_should_indent = match context.config.fn_args_layout() {
1880 // If our args are block layout then we surely must have space.
1881 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1882 _ if args_last_line_contains_comment => false,
1883 _ if result.contains('\n') || multi_line_ret_str => true,
1885 // If the return type would push over the max width, then put the return type on
1886 // a new line. With the +1 for the signature length an additional space between
1887 // the closing parenthesis of the argument and the arrow '->' is considered.
1888 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1890 // If there is no where clause, take into account the space after the return type
1892 if where_clause.predicates.is_empty() {
1896 sig_length > context.config.max_width()
1899 let ret_indent = if ret_should_indent {
1900 let indent = match context.config.fn_return_indent() {
1901 ReturnIndent::WithWhereClause => indent + 4,
1902 // Aligning with non-existent args looks silly.
1903 _ if arg_str.is_empty() => {
1904 force_new_line_for_brace = true;
1907 // FIXME: we might want to check that using the arg indent
1908 // doesn't blow our budget, and if it does, then fallback to
1909 // the where clause indent.
1914 result.push_str(&indent.to_string(context.config));
1918 Indent::new(indent.block_indent, last_line_width(&result))
1921 if multi_line_ret_str || ret_should_indent {
1922 // Now that we know the proper indent and width, we need to
1923 // re-layout the return type.
1924 let ret_str = try_opt!(
1926 .rewrite(context, Shape::indented(ret_indent, context.config))
1928 result.push_str(&ret_str);
1930 result.push_str(&ret_str);
1933 // Comment between return type and the end of the decl.
1934 let snippet_lo = fd.output.span().hi();
1935 if where_clause.predicates.is_empty() {
1936 let snippet_hi = span.hi();
1937 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1938 // Try to preserve the layout of the original snippet.
1939 let original_starts_with_newline = snippet
1941 .map_or(false, |i| snippet[i..].starts_with('\n'));
1942 let original_ends_with_newline = snippet
1943 .rfind(|c| c != ' ')
1944 .map_or(false, |i| snippet[i..].ends_with('\n'));
1945 let snippet = snippet.trim();
1946 if !snippet.is_empty() {
1947 result.push(if original_starts_with_newline {
1952 result.push_str(snippet);
1953 if original_ends_with_newline {
1954 force_new_line_for_brace = true;
1960 let should_compress_where = match context.config.where_density() {
1961 Density::Compressed => !result.contains('\n'),
1962 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1966 let pos_before_where = match fd.output {
1967 ast::FunctionRetTy::Default(..) => args_span.hi(),
1968 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1971 if where_clause.predicates.len() == 1 && should_compress_where {
1972 let budget = context.budget(last_line_used_width(&result, indent.width()));
1973 if let Some(where_clause_str) = rewrite_where_clause(
1976 context.config.fn_brace_style(),
1977 Shape::legacy(budget, indent),
1978 Density::Compressed,
1982 WhereClauseOption::compressed(),
1984 result.push_str(&where_clause_str);
1985 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1986 return Some((result, force_new_line_for_brace));
1990 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
1991 let where_clause_str = try_opt!(rewrite_where_clause(
1994 context.config.fn_brace_style(),
1995 Shape::indented(indent, context.config),
2002 // If there are neither where clause nor return type, we may be missing comments between
2004 if where_clause_str.is_empty() {
2005 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2006 match recover_missing_comment_in_span(
2007 mk_sp(args_span.hi(), ret_span.hi()),
2010 last_line_width(&result),
2012 Some(ref missing_comment) if !missing_comment.is_empty() => {
2013 result.push_str(missing_comment);
2014 force_new_line_for_brace = true;
2021 result.push_str(&where_clause_str);
2023 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2024 Some((result, force_new_line_for_brace))
2027 #[derive(Copy, Clone)]
2028 struct WhereClauseOption {
2029 suppress_comma: bool, // Force no trailing comma
2030 snuggle: bool, // Do not insert newline before `where`
2031 compress_where: bool, // Try single line where clause instead of vertical layout
2034 impl WhereClauseOption {
2035 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2037 suppress_comma: suppress_comma,
2039 compress_where: false,
2043 pub fn compressed() -> WhereClauseOption {
2045 suppress_comma: true,
2047 compress_where: true,
2051 pub fn snuggled(current: &str) -> WhereClauseOption {
2053 suppress_comma: false,
2054 snuggle: trimmed_last_line_width(current) == 1,
2055 compress_where: false,
2061 context: &RewriteContext,
2063 explicit_self: Option<&ast::ExplicitSelf>,
2064 one_line_budget: usize,
2065 multi_line_budget: usize,
2070 generics_str_contains_newline: bool,
2071 ) -> Option<String> {
2072 let mut arg_item_strs = try_opt!(
2075 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2077 .collect::<Option<Vec<_>>>()
2080 // Account for sugary self.
2081 // FIXME: the comment for the self argument is dropped. This is blocked
2082 // on rust issue #27522.
2083 let min_args = explicit_self
2084 .and_then(|explicit_self| {
2085 rewrite_explicit_self(explicit_self, args, context)
2087 .map_or(1, |self_str| {
2088 arg_item_strs[0] = self_str;
2092 // Comments between args.
2093 let mut arg_items = Vec::new();
2095 arg_items.push(ListItem::from_str(""));
2098 // FIXME(#21): if there are no args, there might still be a comment, but
2099 // without spans for the comment or parens, there is no chance of
2100 // getting it right. You also don't get to put a comment on self, unless
2102 if args.len() >= min_args || variadic {
2103 let comment_span_start = if min_args == 2 {
2104 let second_arg_start = if arg_has_pattern(&args[1]) {
2105 args[1].pat.span.lo()
2107 args[1].ty.span.lo()
2109 let reduced_span = mk_sp(span.lo(), second_arg_start);
2111 context.codemap.span_after_last(reduced_span, ",")
2116 enum ArgumentKind<'a> {
2117 Regular(&'a ast::Arg),
2121 let variadic_arg = if variadic {
2122 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2123 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2124 Some(ArgumentKind::Variadic(variadic_start))
2129 let more_items = itemize_list(
2131 args[min_args - 1..]
2133 .map(ArgumentKind::Regular)
2134 .chain(variadic_arg),
2137 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2138 ArgumentKind::Variadic(start) => start,
2141 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2142 ArgumentKind::Variadic(start) => start + BytePos(3),
2145 ArgumentKind::Regular(..) => None,
2146 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2153 arg_items.extend(more_items);
2156 let fits_in_one_line = !generics_str_contains_newline
2157 && (arg_items.is_empty()
2158 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2160 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2161 item.item = Some(arg);
2164 let last_line_ends_with_comment = arg_items
2167 .and_then(|item| item.post_comment.as_ref())
2168 .map_or(false, |s| s.trim().starts_with("//"));
2170 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2171 IndentStyle::Block if fits_in_one_line => {
2172 (indent.block_indent(context.config), SeparatorTactic::Never)
2174 IndentStyle::Block => (
2175 indent.block_indent(context.config),
2176 context.config.trailing_comma(),
2178 IndentStyle::Visual if last_line_ends_with_comment => {
2179 (arg_indent, context.config.trailing_comma())
2181 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2184 let tactic = definitive_tactic(
2186 context.config.fn_args_density().to_list_tactic(),
2190 let budget = match tactic {
2191 DefinitiveListTactic::Horizontal => one_line_budget,
2192 _ => multi_line_budget,
2195 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2197 let fmt = ListFormatting {
2200 trailing_separator: if variadic {
2201 SeparatorTactic::Never
2205 separator_place: SeparatorPlace::Back,
2206 shape: Shape::legacy(budget, indent),
2207 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2208 preserve_newline: true,
2209 config: context.config,
2212 write_list(&arg_items, &fmt)
2215 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2216 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2217 ident.node != symbol::keywords::Invalid.ident()
2223 fn compute_budgets_for_args(
2224 context: &RewriteContext,
2228 newline_brace: bool,
2230 force_vertical_layout: bool,
2231 ) -> Option<((usize, usize, Indent))> {
2233 "compute_budgets_for_args {} {:?}, {}, {}",
2239 // Try keeping everything on the same line.
2240 if !result.contains('\n') && !force_vertical_layout {
2241 // 2 = `()`, 3 = `() `, space is before ret_string.
2242 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2243 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2253 let one_line_budget = context.budget(used_space);
2255 if one_line_budget > 0 {
2257 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2258 IndentStyle::Block => {
2259 let indent = indent.block_indent(context.config);
2260 (indent, context.budget(indent.width() + 1))
2262 IndentStyle::Visual => {
2263 let indent = indent + result.len() + 1;
2264 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2265 (indent, context.budget(multi_line_overhead))
2269 return Some((one_line_budget, multi_line_budget, indent));
2273 // Didn't work. we must force vertical layout and put args on a newline.
2274 let new_indent = indent.block_indent(context.config);
2275 let used_space = match context.config.fn_args_layout() {
2277 IndentStyle::Block => new_indent.width() + 1,
2278 // Account for `)` and possibly ` {`.
2279 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2281 Some((0, context.budget(used_space), new_indent))
2284 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2285 match (config.fn_brace_style(), config.where_density()) {
2286 (BraceStyle::AlwaysNextLine, _) => true,
2287 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2288 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2289 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2294 fn rewrite_generics(
2295 context: &RewriteContext,
2296 generics: &ast::Generics,
2299 ) -> Option<String> {
2300 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2301 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2302 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2303 rewrite_generics_inner(context, generics, g_shape, 0, span)
2307 fn rewrite_generics_inner(
2308 context: &RewriteContext,
2309 generics: &ast::Generics,
2311 one_line_width: usize,
2313 ) -> Option<String> {
2314 // FIXME: convert bounds to where clauses where they get too big or if
2315 // there is a where clause at all.
2318 enum GenericsArg<'a> {
2319 Lifetime(&'a ast::LifetimeDef),
2320 TyParam(&'a ast::TyParam),
2322 impl<'a> Rewrite for GenericsArg<'a> {
2323 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2325 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2326 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2330 impl<'a> Spanned for GenericsArg<'a> {
2331 fn span(&self) -> Span {
2333 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2334 GenericsArg::TyParam(ref ty) => ty.span(),
2339 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2340 return Some(String::new());
2343 let generics_args = generics
2346 .map(|lt| GenericsArg::Lifetime(lt))
2347 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2348 let items = itemize_list(
2352 |arg| arg.span().lo(),
2353 |arg| arg.span().hi(),
2354 |arg| arg.rewrite(context, shape),
2355 context.codemap.span_after(span, "<"),
2359 format_generics_item_list(context, items, shape, one_line_width)
2362 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2363 match config.generics_indent() {
2364 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2365 IndentStyle::Block => {
2369 .block_indent(config.tab_spaces())
2370 .with_max_width(config)
2376 pub fn format_generics_item_list<I>(
2377 context: &RewriteContext,
2380 one_line_budget: usize,
2383 I: Iterator<Item = ListItem>,
2385 let item_vec = items.collect::<Vec<_>>();
2387 let tactic = definitive_tactic(
2389 ListTactic::HorizontalVertical,
2393 let fmt = ListFormatting {
2396 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2397 SeparatorTactic::Never
2399 context.config.trailing_comma()
2401 separator_place: SeparatorPlace::Back,
2403 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2404 preserve_newline: true,
2405 config: context.config,
2408 let list_str = try_opt!(write_list(&item_vec, &fmt));
2410 Some(wrap_generics_with_angle_brackets(
2417 pub fn wrap_generics_with_angle_brackets(
2418 context: &RewriteContext,
2420 list_offset: Indent,
2422 if context.config.generics_indent() == IndentStyle::Block
2423 && (list_str.contains('\n') || list_str.ends_with(','))
2427 list_offset.to_string(context.config),
2430 .block_unindent(context.config)
2431 .to_string(context.config)
2433 } else if context.config.spaces_within_angle_brackets() {
2434 format!("< {} >", list_str)
2436 format!("<{}>", list_str)
2440 fn rewrite_trait_bounds(
2441 context: &RewriteContext,
2442 type_param_bounds: &ast::TyParamBounds,
2444 ) -> Option<String> {
2445 let bounds: &[_] = type_param_bounds;
2447 if bounds.is_empty() {
2448 return Some(String::new());
2450 let bound_str = try_opt!(
2453 .map(|ty_bound| ty_bound.rewrite(context, shape))
2454 .collect::<Option<Vec<_>>>()
2456 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2459 fn rewrite_where_clause_rfc_style(
2460 context: &RewriteContext,
2461 where_clause: &ast::WhereClause,
2464 span_end: Option<BytePos>,
2465 span_end_before_where: BytePos,
2466 where_clause_option: WhereClauseOption,
2467 ) -> Option<String> {
2468 let block_shape = shape.block().with_max_width(context.config);
2470 let (span_before, span_after) =
2471 missing_span_before_after_where(span_end_before_where, where_clause);
2472 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2479 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2482 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2485 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2486 // each clause on one line, trailing comma (except if suppress_comma)
2487 let span_start = where_clause.predicates[0].span().lo();
2488 // If we don't have the start of the next span, then use the end of the
2489 // predicates, but that means we miss comments.
2490 let len = where_clause.predicates.len();
2491 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2492 let span_end = span_end.unwrap_or(end_of_preds);
2493 let items = itemize_list(
2495 where_clause.predicates.iter(),
2497 |pred| pred.span().lo(),
2498 |pred| pred.span().hi(),
2499 |pred| pred.rewrite(context, block_shape),
2504 let comma_tactic = if where_clause_option.suppress_comma {
2505 SeparatorTactic::Never
2507 context.config.trailing_comma()
2510 let fmt = ListFormatting {
2511 tactic: DefinitiveListTactic::Vertical,
2513 trailing_separator: comma_tactic,
2514 separator_place: SeparatorPlace::Back,
2515 shape: clause_shape,
2516 ends_with_newline: true,
2517 preserve_newline: true,
2518 config: context.config,
2520 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2522 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2525 format!("\n{}", shape.indent.to_string(context.config))
2527 let newline_before_where = comment_separator(&comment_before, shape);
2528 let newline_after_where = comment_separator(&comment_after, clause_shape);
2531 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2532 && comment_after.is_empty() && !preds_str.contains('\n')
2533 && 6 + preds_str.len() <= shape.width
2537 format!("\n{}", clause_shape.indent.to_string(context.config))
2540 "{}{}{}where{}{}{}{}",
2543 newline_before_where,
2544 newline_after_where,
2551 fn rewrite_where_clause(
2552 context: &RewriteContext,
2553 where_clause: &ast::WhereClause,
2554 brace_style: BraceStyle,
2558 span_end: Option<BytePos>,
2559 span_end_before_where: BytePos,
2560 where_clause_option: WhereClauseOption,
2561 ) -> Option<String> {
2562 if where_clause.predicates.is_empty() {
2563 return Some(String::new());
2566 if context.config.where_style() == Style::Rfc {
2567 return rewrite_where_clause_rfc_style(
2573 span_end_before_where,
2574 where_clause_option,
2578 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2580 let offset = match context.config.where_pred_indent() {
2581 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2582 // 6 = "where ".len()
2583 IndentStyle::Visual => shape.indent + extra_indent + 6,
2585 // FIXME: if where_pred_indent != Visual, then the budgets below might
2586 // be out by a char or two.
2588 let budget = context.config.max_width() - offset.width();
2589 let span_start = where_clause.predicates[0].span().lo();
2590 // If we don't have the start of the next span, then use the end of the
2591 // predicates, but that means we miss comments.
2592 let len = where_clause.predicates.len();
2593 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2594 let span_end = span_end.unwrap_or(end_of_preds);
2595 let items = itemize_list(
2597 where_clause.predicates.iter(),
2599 |pred| pred.span().lo(),
2600 |pred| pred.span().hi(),
2601 |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(
2611 context.config.where_layout(),
2616 let mut comma_tactic = context.config.trailing_comma();
2617 // Kind of a hack because we don't usually have trailing commas in where clauses.
2618 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2619 comma_tactic = SeparatorTactic::Never;
2622 let fmt = ListFormatting {
2625 trailing_separator: comma_tactic,
2626 separator_place: SeparatorPlace::Back,
2627 shape: Shape::legacy(budget, offset),
2628 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2629 preserve_newline: true,
2630 config: context.config,
2632 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2634 let end_length = if terminator == "{" {
2635 // If the brace is on the next line we don't need to count it otherwise it needs two
2638 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2639 BraceStyle::PreferSameLine => 2,
2641 } else if terminator == "=" {
2646 if density == Density::Tall || preds_str.contains('\n')
2647 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2651 (shape.indent + extra_indent).to_string(context.config),
2655 Some(format!(" where {}", preds_str))
2659 fn missing_span_before_after_where(
2660 before_item_span_end: BytePos,
2661 where_clause: &ast::WhereClause,
2663 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2665 let pos_after_where = where_clause.span.lo() + BytePos(5);
2666 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2667 (missing_span_before, missing_span_after)
2670 fn rewrite_comments_before_after_where(
2671 context: &RewriteContext,
2672 span_before_where: Span,
2673 span_after_where: Span,
2675 ) -> Option<(String, String)> {
2676 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2677 let after_comment = try_opt!(rewrite_missing_comment(
2679 shape.block_indent(context.config.tab_spaces()),
2682 Some((before_comment, after_comment))
2685 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2686 format!("{}{}{}", format_visibility(vis), item_name, ident)
2690 context: &RewriteContext,
2691 generics: &ast::Generics,
2694 brace_style: BraceStyle,
2695 force_same_line_brace: bool,
2699 ) -> Option<String> {
2700 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2701 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2703 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2704 let budget = context.budget(last_line_used_width(&result, offset.width()));
2705 let option = WhereClauseOption::snuggled(&result);
2706 let where_clause_str = try_opt!(rewrite_where_clause(
2708 &generics.where_clause,
2710 Shape::legacy(budget, offset.block_only()),
2717 result.push_str(&where_clause_str);
2718 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2719 || (generics.where_clause.predicates.is_empty()
2720 && trimmed_last_line_width(&result) == 1)
2722 force_same_line_brace || trimmed_last_line_width(&result) == 1
2723 || brace_style != BraceStyle::AlwaysNextLine
2725 let total_used_width = last_line_used_width(&result, used_width);
2726 let remaining_budget = context.budget(total_used_width);
2727 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2728 // and hence we take the closer into account as well for one line budget.
2729 // We assume that the closer has the same length as the opener.
2730 let overhead = if force_same_line_brace {
2731 1 + opener.len() + opener.len()
2735 let forbid_same_line_brace = overhead > remaining_budget;
2736 if !forbid_same_line_brace && same_line_brace {
2740 result.push_str(&offset.block_only().to_string(context.config));
2742 result.push_str(opener);
2747 impl Rewrite for ast::ForeignItem {
2748 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2749 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2750 // Drop semicolon or it will be interpreted as comment.
2751 // FIXME: this may be a faulty span from libsyntax.
2752 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2754 let item_str = try_opt!(match self.node {
2755 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2762 ast::Unsafety::Normal,
2763 ast::Constness::NotConst,
2764 ast::Defaultness::Final,
2765 // These are not actually rust functions,
2766 // but we format them as such.
2773 ).map(|(s, _)| format!("{};", s))
2775 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2776 // FIXME(#21): we're dropping potential comments in between the
2777 // function keywords here.
2778 let vis = format_visibility(&self.vis);
2779 let mut_str = if is_mutable { "mut " } else { "" };
2780 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2782 let shape = try_opt!(shape.sub_width(1));
2783 ty.rewrite(context, shape).map(|ty_str| {
2784 // 1 = space between prefix and type.
2785 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2788 let nested_indent = shape.indent.block_indent(context.config);
2789 format!("\n{}", nested_indent.to_string(context.config))
2791 format!("{}{}{};", prefix, sep, ty_str)
2796 let missing_span = if self.attrs.is_empty() {
2797 mk_sp(self.span.lo(), self.span.lo())
2799 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2801 combine_strs_with_missing_comments(