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!(rewrite_call_inner(
1217 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1219 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1220 context.config.fn_call_width(),
1223 result.push_str(&body);
1226 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1227 && (result.contains('\n')
1228 || offset.block_indent + result.len() + where_clause_str.len() + 1
1229 > context.config.max_width())
1231 // We need to put the where clause on a new line, but we didn't
1232 // know that earlier, so the where clause will not be indented properly.
1234 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1235 .to_string(context.config));
1237 result.push_str(&where_clause_str);
1242 pub fn rewrite_type_alias(
1243 context: &RewriteContext,
1247 generics: &ast::Generics,
1248 vis: &ast::Visibility,
1250 ) -> Option<String> {
1251 let mut result = String::with_capacity(128);
1253 result.push_str(&format_visibility(vis));
1254 result.push_str("type ");
1255 result.push_str(&ident.to_string());
1258 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1259 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1260 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1261 result.push_str(&generics_str);
1263 let where_budget = context.budget(last_line_width(&result));
1264 let option = WhereClauseOption::snuggled(&result);
1265 let where_clause_str = try_opt!(rewrite_where_clause(
1267 &generics.where_clause,
1268 context.config.item_brace_style(),
1269 Shape::legacy(where_budget, indent),
1270 context.config.where_density(),
1276 result.push_str(&where_clause_str);
1277 if where_clause_str.is_empty() {
1278 result.push_str(" = ");
1280 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1283 let line_width = last_line_width(&result);
1284 // This checked_sub may fail as the extra space after '=' is not taken into account
1285 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1286 let budget = context.budget(indent.width() + line_width + ";".len());
1287 let type_indent = indent + line_width;
1288 // Try to fit the type on the same line
1289 let ty_str = try_opt!(
1290 ty.rewrite(context, Shape::legacy(budget, type_indent))
1292 // The line was too short, try to put the type on the next line
1294 // Remove the space after '='
1296 let type_indent = indent.block_indent(context.config);
1298 result.push_str(&type_indent.to_string(context.config));
1299 let budget = context.budget(type_indent.width() + ";".len());
1300 ty.rewrite(context, Shape::legacy(budget, type_indent))
1303 result.push_str(&ty_str);
1304 result.push_str(";");
1308 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1310 if config.space_before_type_annotation() {
1315 if config.space_after_type_annotation_colon() {
1323 pub fn rewrite_struct_field_prefix(
1324 context: &RewriteContext,
1325 field: &ast::StructField,
1326 ) -> Option<String> {
1327 let vis = format_visibility(&field.vis);
1328 let type_annotation_spacing = type_annotation_spacing(context.config);
1329 Some(match field.ident {
1330 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1331 None => format!("{}", vis),
1335 fn rewrite_struct_field_type(
1336 context: &RewriteContext,
1337 last_line_width: usize,
1338 field: &ast::StructField,
1341 ) -> Option<String> {
1342 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1345 .rewrite(context, ty_shape)
1346 .map(|ty| format!("{}{}", spacing, ty))
1349 impl Rewrite for ast::StructField {
1350 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1351 rewrite_struct_field(context, self, shape, 0)
1355 pub fn rewrite_struct_field(
1356 context: &RewriteContext,
1357 field: &ast::StructField,
1359 lhs_max_width: usize,
1360 ) -> Option<String> {
1361 if contains_skip(&field.attrs) {
1362 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1365 let type_annotation_spacing = type_annotation_spacing(context.config);
1366 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1368 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1369 let attrs_extendable = attrs_str.is_empty()
1370 || (context.config.attributes_on_same_line_as_field()
1371 && is_attributes_extendable(&attrs_str));
1372 let missing_span = if field.attrs.is_empty() {
1373 mk_sp(field.span.lo(), field.span.lo())
1375 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1377 let mut spacing = String::from(if field.ident.is_some() {
1378 type_annotation_spacing.1
1382 // Try to put everything on a single line.
1383 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1391 let overhead = last_line_width(&attr_prefix);
1392 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1393 for _ in 0..lhs_offset {
1396 // In this extreme case we will be missing a space betweeen an attribute and a field.
1397 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1400 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1401 if let Some(ref ty) = ty_rewritten {
1402 if !ty.contains('\n') {
1403 return Some(attr_prefix + ty);
1407 // We must use multiline.
1408 let last_line_width = last_line_width(&prefix);
1409 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1411 let type_offset = shape.indent.block_indent(context.config);
1412 let rewrite_type_in_next_line = || {
1415 .rewrite(context, Shape::indented(type_offset, context.config))
1418 let field_str = match ty_rewritten {
1419 // If we start from the next line and type fits in a single line, then do so.
1420 Some(ref ty) => match rewrite_type_in_next_line() {
1421 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1424 type_offset.to_string(context.config),
1430 let ty = try_opt!(rewrite_type_in_next_line());
1434 type_offset.to_string(context.config),
1439 combine_strs_with_missing_comments(
1449 pub fn rewrite_static(
1451 vis: &ast::Visibility,
1454 mutability: ast::Mutability,
1455 expr_opt: Option<&ptr::P<ast::Expr>>,
1458 context: &RewriteContext,
1459 ) -> Option<String> {
1460 let colon = colon_spaces(
1461 context.config.space_before_type_annotation(),
1462 context.config.space_after_type_annotation_colon(),
1464 let prefix = format!(
1466 format_visibility(vis),
1468 format_mutability(mutability),
1473 let ty_str = try_opt!(ty.rewrite(
1476 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1480 if let Some(expr) = expr_opt {
1481 let lhs = format!("{}{} =", prefix, ty_str);
1483 let remaining_width = context.budget(offset.block_indent + 1);
1488 Shape::legacy(remaining_width, offset.block_only()),
1489 ).and_then(|res| recover_comment_removed(res, span, context))
1490 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1492 Some(format!("{}{};", prefix, ty_str))
1496 pub fn rewrite_associated_type(
1498 ty_opt: Option<&ptr::P<ast::Ty>>,
1499 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1500 context: &RewriteContext,
1502 ) -> Option<String> {
1503 let prefix = format!("type {}", ident);
1505 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1507 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1508 let bounds: &[_] = ty_param_bounds;
1509 let bound_str = try_opt!(
1512 .map(|ty_bound| ty_bound.rewrite(context, shape))
1513 .collect::<Option<Vec<_>>>()
1515 if !bounds.is_empty() {
1516 format!(": {}", join_bounds(context, shape, &bound_str))
1524 if let Some(ty) = ty_opt {
1525 let ty_str = try_opt!(ty.rewrite(
1528 context.budget(indent.block_indent + prefix.len() + 2),
1529 indent.block_only(),
1532 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1534 Some(format!("{}{};", prefix, type_bounds_str))
1538 pub fn rewrite_associated_impl_type(
1540 defaultness: ast::Defaultness,
1541 ty_opt: Option<&ptr::P<ast::Ty>>,
1542 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1543 context: &RewriteContext,
1545 ) -> Option<String> {
1546 let result = try_opt!(rewrite_associated_type(
1549 ty_param_bounds_opt,
1555 ast::Defaultness::Default => Some(format!("default {}", result)),
1560 impl Rewrite for ast::FunctionRetTy {
1561 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1563 ast::FunctionRetTy::Default(_) => Some(String::new()),
1564 ast::FunctionRetTy::Ty(ref ty) => {
1565 let inner_width = try_opt!(shape.width.checked_sub(3));
1566 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1567 .map(|r| format!("-> {}", r))
1573 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1575 ast::TyKind::Infer => {
1576 let original = context.snippet(ty.span);
1583 impl Rewrite for ast::Arg {
1584 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1585 if is_named_arg(self) {
1586 let mut result = try_opt!(
1588 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1591 if !is_empty_infer(context, &*self.ty) {
1592 if context.config.space_before_type_annotation() {
1593 result.push_str(" ");
1595 result.push_str(":");
1596 if context.config.space_after_type_annotation_colon() {
1597 result.push_str(" ");
1599 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1600 let ty_str = try_opt!(self.ty.rewrite(
1602 Shape::legacy(max_width, shape.indent + result.len()),
1604 result.push_str(&ty_str);
1609 self.ty.rewrite(context, shape)
1614 fn rewrite_explicit_self(
1615 explicit_self: &ast::ExplicitSelf,
1617 context: &RewriteContext,
1618 ) -> Option<String> {
1619 match explicit_self.node {
1620 ast::SelfKind::Region(lt, m) => {
1621 let mut_str = format_mutability(m);
1624 let lifetime_str = try_opt!(l.rewrite(
1626 Shape::legacy(context.config.max_width(), Indent::empty()),
1628 Some(format!("&{} {}self", lifetime_str, mut_str))
1630 None => Some(format!("&{}self", mut_str)),
1633 ast::SelfKind::Explicit(ref ty, _) => {
1634 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1636 let mutability = explicit_self_mutability(&args[0]);
1637 let type_str = try_opt!(ty.rewrite(
1639 Shape::legacy(context.config.max_width(), Indent::empty()),
1644 format_mutability(mutability),
1648 ast::SelfKind::Value(_) => {
1649 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1651 let mutability = explicit_self_mutability(&args[0]);
1653 Some(format!("{}self", format_mutability(mutability)))
1658 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1659 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1660 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1661 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1668 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1669 if is_named_arg(arg) {
1676 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1678 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1679 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1680 _ => arg.ty.span.hi(),
1684 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1685 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1686 ident.node != symbol::keywords::Invalid.ident()
1692 // Return type is (result, force_new_line_for_brace)
1694 context: &RewriteContext,
1698 generics: &ast::Generics,
1699 unsafety: ast::Unsafety,
1700 constness: ast::Constness,
1701 defaultness: ast::Defaultness,
1703 vis: &ast::Visibility,
1705 newline_brace: bool,
1708 ) -> Option<(String, bool)> {
1709 let mut force_new_line_for_brace = false;
1711 let where_clause = &generics.where_clause;
1713 let mut result = String::with_capacity(1024);
1714 // Vis defaultness constness unsafety abi.
1715 result.push_str(&*format_visibility(vis));
1716 result.push_str(format_defaultness(defaultness));
1717 result.push_str(format_constness(constness));
1718 result.push_str(format_unsafety(unsafety));
1719 if abi != abi::Abi::Rust {
1720 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1724 result.push_str("fn ");
1725 result.push_str(&ident.to_string());
1728 let overhead = if has_braces && !newline_brace {
1735 let used_width = last_line_used_width(&result, indent.width());
1736 let one_line_budget = context.budget(used_width + overhead);
1738 width: one_line_budget,
1742 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1743 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1744 result.push_str(&generics_str);
1746 let snuggle_angle_bracket = generics_str
1749 .map_or(false, |l| l.trim_left().len() == 1);
1751 // Note that the width and indent don't really matter, we'll re-layout the
1752 // return type later anyway.
1753 let ret_str = try_opt!(
1755 .rewrite(context, Shape::indented(indent, context.config))
1758 let multi_line_ret_str = ret_str.contains('\n');
1759 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1762 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1773 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1779 // Check if vertical layout was forced.
1780 if one_line_budget == 0 {
1781 if snuggle_angle_bracket {
1783 } else if context.config.fn_args_paren_newline() {
1785 result.push_str(&arg_indent.to_string(context.config));
1786 if context.config.fn_args_layout() == IndentStyle::Visual {
1787 arg_indent = arg_indent + 1; // extra space for `(`
1791 result.push_str("(");
1792 if context.config.fn_args_layout() == IndentStyle::Visual {
1794 result.push_str(&arg_indent.to_string(context.config));
1800 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1804 // A conservative estimation, to goal is to be over all parens in generics
1805 let args_start = generics
1808 .map_or(span.lo(), |tp| end_typaram(tp));
1809 let args_end = if fd.inputs.is_empty() {
1812 .span_after(mk_sp(args_start, span.hi()), ")")
1814 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1815 context.codemap.span_after(last_span, ")")
1817 let args_span = mk_sp(
1820 .span_after(mk_sp(args_start, span.hi()), "("),
1823 let arg_str = try_opt!(rewrite_args(
1826 fd.get_self().as_ref(),
1833 generics_str.contains('\n'),
1836 let put_args_in_block = match context.config.fn_args_layout() {
1837 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1839 } && !fd.inputs.is_empty();
1841 let mut args_last_line_contains_comment = false;
1842 if put_args_in_block {
1843 arg_indent = indent.block_indent(context.config);
1845 result.push_str(&arg_indent.to_string(context.config));
1846 result.push_str(&arg_str);
1848 result.push_str(&indent.to_string(context.config));
1851 result.push_str(&arg_str);
1852 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1853 // Put the closing brace on the next line if it overflows the max width.
1855 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1858 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1861 // If the last line of args contains comment, we cannot put the closing paren
1862 // on the same line.
1866 .map_or(false, |last_line| last_line.contains("//"))
1868 args_last_line_contains_comment = true;
1870 result.push_str(&arg_indent.to_string(context.config));
1876 if let ast::FunctionRetTy::Ty(..) = fd.output {
1877 let ret_should_indent = match context.config.fn_args_layout() {
1878 // If our args are block layout then we surely must have space.
1879 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1880 _ if args_last_line_contains_comment => false,
1881 _ if result.contains('\n') || multi_line_ret_str => true,
1883 // If the return type would push over the max width, then put the return type on
1884 // a new line. With the +1 for the signature length an additional space between
1885 // the closing parenthesis of the argument and the arrow '->' is considered.
1886 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1888 // If there is no where clause, take into account the space after the return type
1890 if where_clause.predicates.is_empty() {
1894 sig_length > context.config.max_width()
1897 let ret_indent = if ret_should_indent {
1898 let indent = match context.config.fn_return_indent() {
1899 ReturnIndent::WithWhereClause => indent + 4,
1900 // Aligning with non-existent args looks silly.
1901 _ if arg_str.is_empty() => {
1902 force_new_line_for_brace = true;
1905 // FIXME: we might want to check that using the arg indent
1906 // doesn't blow our budget, and if it does, then fallback to
1907 // the where clause indent.
1912 result.push_str(&indent.to_string(context.config));
1916 Indent::new(indent.block_indent, last_line_width(&result))
1919 if multi_line_ret_str || ret_should_indent {
1920 // Now that we know the proper indent and width, we need to
1921 // re-layout the return type.
1922 let ret_str = try_opt!(
1924 .rewrite(context, Shape::indented(ret_indent, context.config))
1926 result.push_str(&ret_str);
1928 result.push_str(&ret_str);
1931 // Comment between return type and the end of the decl.
1932 let snippet_lo = fd.output.span().hi();
1933 if where_clause.predicates.is_empty() {
1934 let snippet_hi = span.hi();
1935 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1936 // Try to preserve the layout of the original snippet.
1937 let original_starts_with_newline = snippet
1939 .map_or(false, |i| snippet[i..].starts_with('\n'));
1940 let original_ends_with_newline = snippet
1941 .rfind(|c| c != ' ')
1942 .map_or(false, |i| snippet[i..].ends_with('\n'));
1943 let snippet = snippet.trim();
1944 if !snippet.is_empty() {
1945 result.push(if original_starts_with_newline {
1950 result.push_str(snippet);
1951 if original_ends_with_newline {
1952 force_new_line_for_brace = true;
1958 let should_compress_where = match context.config.where_density() {
1959 Density::Compressed => !result.contains('\n'),
1960 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1964 let pos_before_where = match fd.output {
1965 ast::FunctionRetTy::Default(..) => args_span.hi(),
1966 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1969 if where_clause.predicates.len() == 1 && should_compress_where {
1970 let budget = context.budget(last_line_used_width(&result, indent.width()));
1971 if let Some(where_clause_str) = rewrite_where_clause(
1974 context.config.fn_brace_style(),
1975 Shape::legacy(budget, indent),
1976 Density::Compressed,
1980 WhereClauseOption::compressed(),
1982 result.push_str(&where_clause_str);
1983 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1984 return Some((result, force_new_line_for_brace));
1988 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
1989 let where_clause_str = try_opt!(rewrite_where_clause(
1992 context.config.fn_brace_style(),
1993 Shape::indented(indent, context.config),
2000 // If there are neither where clause nor return type, we may be missing comments between
2002 if where_clause_str.is_empty() {
2003 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2004 match recover_missing_comment_in_span(
2005 mk_sp(args_span.hi(), ret_span.hi()),
2008 last_line_width(&result),
2010 Some(ref missing_comment) if !missing_comment.is_empty() => {
2011 result.push_str(missing_comment);
2012 force_new_line_for_brace = true;
2019 result.push_str(&where_clause_str);
2021 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2022 Some((result, force_new_line_for_brace))
2025 #[derive(Copy, Clone)]
2026 struct WhereClauseOption {
2027 suppress_comma: bool, // Force no trailing comma
2028 snuggle: bool, // Do not insert newline before `where`
2029 compress_where: bool, // Try single line where clause instead of vertical layout
2032 impl WhereClauseOption {
2033 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2035 suppress_comma: suppress_comma,
2037 compress_where: false,
2041 pub fn compressed() -> WhereClauseOption {
2043 suppress_comma: true,
2045 compress_where: true,
2049 pub fn snuggled(current: &str) -> WhereClauseOption {
2051 suppress_comma: false,
2052 snuggle: trimmed_last_line_width(current) == 1,
2053 compress_where: false,
2059 context: &RewriteContext,
2061 explicit_self: Option<&ast::ExplicitSelf>,
2062 one_line_budget: usize,
2063 multi_line_budget: usize,
2068 generics_str_contains_newline: bool,
2069 ) -> Option<String> {
2070 let mut arg_item_strs = try_opt!(
2073 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2075 .collect::<Option<Vec<_>>>()
2078 // Account for sugary self.
2079 // FIXME: the comment for the self argument is dropped. This is blocked
2080 // on rust issue #27522.
2081 let min_args = explicit_self
2082 .and_then(|explicit_self| {
2083 rewrite_explicit_self(explicit_self, args, context)
2085 .map_or(1, |self_str| {
2086 arg_item_strs[0] = self_str;
2090 // Comments between args.
2091 let mut arg_items = Vec::new();
2093 arg_items.push(ListItem::from_str(""));
2096 // FIXME(#21): if there are no args, there might still be a comment, but
2097 // without spans for the comment or parens, there is no chance of
2098 // getting it right. You also don't get to put a comment on self, unless
2100 if args.len() >= min_args || variadic {
2101 let comment_span_start = if min_args == 2 {
2102 let second_arg_start = if arg_has_pattern(&args[1]) {
2103 args[1].pat.span.lo()
2105 args[1].ty.span.lo()
2107 let reduced_span = mk_sp(span.lo(), second_arg_start);
2109 context.codemap.span_after_last(reduced_span, ",")
2114 enum ArgumentKind<'a> {
2115 Regular(&'a ast::Arg),
2119 let variadic_arg = if variadic {
2120 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2121 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2122 Some(ArgumentKind::Variadic(variadic_start))
2127 let more_items = itemize_list(
2129 args[min_args - 1..]
2131 .map(ArgumentKind::Regular)
2132 .chain(variadic_arg),
2135 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2136 ArgumentKind::Variadic(start) => start,
2139 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2140 ArgumentKind::Variadic(start) => start + BytePos(3),
2143 ArgumentKind::Regular(..) => None,
2144 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2151 arg_items.extend(more_items);
2154 let fits_in_one_line = !generics_str_contains_newline
2155 && (arg_items.is_empty()
2156 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2158 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2159 item.item = Some(arg);
2162 let last_line_ends_with_comment = arg_items
2165 .and_then(|item| item.post_comment.as_ref())
2166 .map_or(false, |s| s.trim().starts_with("//"));
2168 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2169 IndentStyle::Block if fits_in_one_line => {
2170 (indent.block_indent(context.config), SeparatorTactic::Never)
2172 IndentStyle::Block => (
2173 indent.block_indent(context.config),
2174 context.config.trailing_comma(),
2176 IndentStyle::Visual if last_line_ends_with_comment => {
2177 (arg_indent, context.config.trailing_comma())
2179 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2182 let tactic = definitive_tactic(
2184 context.config.fn_args_density().to_list_tactic(),
2188 let budget = match tactic {
2189 DefinitiveListTactic::Horizontal => one_line_budget,
2190 _ => multi_line_budget,
2193 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2195 let fmt = ListFormatting {
2198 trailing_separator: if variadic {
2199 SeparatorTactic::Never
2203 separator_place: SeparatorPlace::Back,
2204 shape: Shape::legacy(budget, indent),
2205 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2206 preserve_newline: true,
2207 config: context.config,
2210 write_list(&arg_items, &fmt)
2213 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2214 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2215 ident.node != symbol::keywords::Invalid.ident()
2221 fn compute_budgets_for_args(
2222 context: &RewriteContext,
2226 newline_brace: bool,
2228 force_vertical_layout: bool,
2229 ) -> Option<((usize, usize, Indent))> {
2231 "compute_budgets_for_args {} {:?}, {}, {}",
2237 // Try keeping everything on the same line.
2238 if !result.contains('\n') && !force_vertical_layout {
2239 // 2 = `()`, 3 = `() `, space is before ret_string.
2240 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2241 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2251 let one_line_budget = context.budget(used_space);
2253 if one_line_budget > 0 {
2255 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2256 IndentStyle::Block => {
2257 let indent = indent.block_indent(context.config);
2258 (indent, context.budget(indent.width() + 1))
2260 IndentStyle::Visual => {
2261 let indent = indent + result.len() + 1;
2262 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2263 (indent, context.budget(multi_line_overhead))
2267 return Some((one_line_budget, multi_line_budget, indent));
2271 // Didn't work. we must force vertical layout and put args on a newline.
2272 let new_indent = indent.block_indent(context.config);
2273 let used_space = match context.config.fn_args_layout() {
2275 IndentStyle::Block => new_indent.width() + 1,
2276 // Account for `)` and possibly ` {`.
2277 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2279 Some((0, context.budget(used_space), new_indent))
2282 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2283 match (config.fn_brace_style(), config.where_density()) {
2284 (BraceStyle::AlwaysNextLine, _) => true,
2285 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2286 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2287 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2292 fn rewrite_generics(
2293 context: &RewriteContext,
2294 generics: &ast::Generics,
2297 ) -> Option<String> {
2298 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2299 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2300 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2301 rewrite_generics_inner(context, generics, g_shape, 0, span)
2305 fn rewrite_generics_inner(
2306 context: &RewriteContext,
2307 generics: &ast::Generics,
2309 one_line_width: usize,
2311 ) -> Option<String> {
2312 // FIXME: convert bounds to where clauses where they get too big or if
2313 // there is a where clause at all.
2316 enum GenericsArg<'a> {
2317 Lifetime(&'a ast::LifetimeDef),
2318 TyParam(&'a ast::TyParam),
2320 impl<'a> Rewrite for GenericsArg<'a> {
2321 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2323 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2324 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2328 impl<'a> Spanned for GenericsArg<'a> {
2329 fn span(&self) -> Span {
2331 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2332 GenericsArg::TyParam(ref ty) => ty.span(),
2337 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2338 return Some(String::new());
2341 let generics_args = generics
2344 .map(|lt| GenericsArg::Lifetime(lt))
2345 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2346 let items = itemize_list(
2350 |arg| arg.span().lo(),
2351 |arg| arg.span().hi(),
2352 |arg| arg.rewrite(context, shape),
2353 context.codemap.span_after(span, "<"),
2357 format_generics_item_list(context, items, shape, one_line_width)
2360 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2361 match config.generics_indent() {
2362 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2363 IndentStyle::Block => {
2367 .block_indent(config.tab_spaces())
2368 .with_max_width(config)
2374 pub fn format_generics_item_list<I>(
2375 context: &RewriteContext,
2378 one_line_budget: usize,
2381 I: Iterator<Item = ListItem>,
2383 let item_vec = items.collect::<Vec<_>>();
2385 let tactic = definitive_tactic(
2387 ListTactic::HorizontalVertical,
2391 let fmt = ListFormatting {
2394 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2395 SeparatorTactic::Never
2397 context.config.trailing_comma()
2399 separator_place: SeparatorPlace::Back,
2401 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2402 preserve_newline: true,
2403 config: context.config,
2406 let list_str = try_opt!(write_list(&item_vec, &fmt));
2408 Some(wrap_generics_with_angle_brackets(
2415 pub fn wrap_generics_with_angle_brackets(
2416 context: &RewriteContext,
2418 list_offset: Indent,
2420 if context.config.generics_indent() == IndentStyle::Block
2421 && (list_str.contains('\n') || list_str.ends_with(','))
2425 list_offset.to_string(context.config),
2428 .block_unindent(context.config)
2429 .to_string(context.config)
2431 } else if context.config.spaces_within_angle_brackets() {
2432 format!("< {} >", list_str)
2434 format!("<{}>", list_str)
2438 fn rewrite_trait_bounds(
2439 context: &RewriteContext,
2440 type_param_bounds: &ast::TyParamBounds,
2442 ) -> Option<String> {
2443 let bounds: &[_] = type_param_bounds;
2445 if bounds.is_empty() {
2446 return Some(String::new());
2448 let bound_str = try_opt!(
2451 .map(|ty_bound| ty_bound.rewrite(context, shape))
2452 .collect::<Option<Vec<_>>>()
2454 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2457 fn rewrite_where_clause_rfc_style(
2458 context: &RewriteContext,
2459 where_clause: &ast::WhereClause,
2462 span_end: Option<BytePos>,
2463 span_end_before_where: BytePos,
2464 where_clause_option: WhereClauseOption,
2465 ) -> Option<String> {
2466 let block_shape = shape.block().with_max_width(context.config);
2468 let (span_before, span_after) =
2469 missing_span_before_after_where(span_end_before_where, where_clause);
2470 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2477 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2480 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2483 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2484 // each clause on one line, trailing comma (except if suppress_comma)
2485 let span_start = where_clause.predicates[0].span().lo();
2486 // If we don't have the start of the next span, then use the end of the
2487 // predicates, but that means we miss comments.
2488 let len = where_clause.predicates.len();
2489 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2490 let span_end = span_end.unwrap_or(end_of_preds);
2491 let items = itemize_list(
2493 where_clause.predicates.iter(),
2495 |pred| pred.span().lo(),
2496 |pred| pred.span().hi(),
2497 |pred| pred.rewrite(context, block_shape),
2502 let comma_tactic = if where_clause_option.suppress_comma {
2503 SeparatorTactic::Never
2505 context.config.trailing_comma()
2508 let fmt = ListFormatting {
2509 tactic: DefinitiveListTactic::Vertical,
2511 trailing_separator: comma_tactic,
2512 separator_place: SeparatorPlace::Back,
2513 shape: clause_shape,
2514 ends_with_newline: true,
2515 preserve_newline: true,
2516 config: context.config,
2518 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2520 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2523 format!("\n{}", shape.indent.to_string(context.config))
2525 let newline_before_where = comment_separator(&comment_before, shape);
2526 let newline_after_where = comment_separator(&comment_after, clause_shape);
2529 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2530 && comment_after.is_empty() && !preds_str.contains('\n')
2531 && 6 + preds_str.len() <= shape.width
2535 format!("\n{}", clause_shape.indent.to_string(context.config))
2538 "{}{}{}where{}{}{}{}",
2541 newline_before_where,
2542 newline_after_where,
2549 fn rewrite_where_clause(
2550 context: &RewriteContext,
2551 where_clause: &ast::WhereClause,
2552 brace_style: BraceStyle,
2556 span_end: Option<BytePos>,
2557 span_end_before_where: BytePos,
2558 where_clause_option: WhereClauseOption,
2559 ) -> Option<String> {
2560 if where_clause.predicates.is_empty() {
2561 return Some(String::new());
2564 if context.config.where_style() == Style::Rfc {
2565 return rewrite_where_clause_rfc_style(
2571 span_end_before_where,
2572 where_clause_option,
2576 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2578 let offset = match context.config.where_pred_indent() {
2579 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2580 // 6 = "where ".len()
2581 IndentStyle::Visual => shape.indent + extra_indent + 6,
2583 // FIXME: if where_pred_indent != Visual, then the budgets below might
2584 // be out by a char or two.
2586 let budget = context.config.max_width() - offset.width();
2587 let span_start = where_clause.predicates[0].span().lo();
2588 // If we don't have the start of the next span, then use the end of the
2589 // predicates, but that means we miss comments.
2590 let len = where_clause.predicates.len();
2591 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2592 let span_end = span_end.unwrap_or(end_of_preds);
2593 let items = itemize_list(
2595 where_clause.predicates.iter(),
2597 |pred| pred.span().lo(),
2598 |pred| pred.span().hi(),
2599 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2604 let item_vec = items.collect::<Vec<_>>();
2605 // FIXME: we don't need to collect here if the where_layout isn't
2606 // HorizontalVertical.
2607 let tactic = definitive_tactic(
2609 context.config.where_layout(),
2614 let mut comma_tactic = context.config.trailing_comma();
2615 // Kind of a hack because we don't usually have trailing commas in where clauses.
2616 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2617 comma_tactic = SeparatorTactic::Never;
2620 let fmt = ListFormatting {
2623 trailing_separator: comma_tactic,
2624 separator_place: SeparatorPlace::Back,
2625 shape: Shape::legacy(budget, offset),
2626 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2627 preserve_newline: true,
2628 config: context.config,
2630 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2632 let end_length = if terminator == "{" {
2633 // If the brace is on the next line we don't need to count it otherwise it needs two
2636 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2637 BraceStyle::PreferSameLine => 2,
2639 } else if terminator == "=" {
2644 if density == Density::Tall || preds_str.contains('\n')
2645 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2649 (shape.indent + extra_indent).to_string(context.config),
2653 Some(format!(" where {}", preds_str))
2657 fn missing_span_before_after_where(
2658 before_item_span_end: BytePos,
2659 where_clause: &ast::WhereClause,
2661 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2663 let pos_after_where = where_clause.span.lo() + BytePos(5);
2664 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2665 (missing_span_before, missing_span_after)
2668 fn rewrite_comments_before_after_where(
2669 context: &RewriteContext,
2670 span_before_where: Span,
2671 span_after_where: Span,
2673 ) -> Option<(String, String)> {
2674 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2675 let after_comment = try_opt!(rewrite_missing_comment(
2677 shape.block_indent(context.config.tab_spaces()),
2680 Some((before_comment, after_comment))
2683 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2684 format!("{}{}{}", format_visibility(vis), item_name, ident)
2688 context: &RewriteContext,
2689 generics: &ast::Generics,
2692 brace_style: BraceStyle,
2693 force_same_line_brace: bool,
2697 ) -> Option<String> {
2698 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2699 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2701 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2702 let budget = context.budget(last_line_used_width(&result, offset.width()));
2703 let option = WhereClauseOption::snuggled(&result);
2704 let where_clause_str = try_opt!(rewrite_where_clause(
2706 &generics.where_clause,
2708 Shape::legacy(budget, offset.block_only()),
2715 result.push_str(&where_clause_str);
2716 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2717 || (generics.where_clause.predicates.is_empty()
2718 && trimmed_last_line_width(&result) == 1)
2720 force_same_line_brace || trimmed_last_line_width(&result) == 1
2721 || brace_style != BraceStyle::AlwaysNextLine
2723 let total_used_width = last_line_used_width(&result, used_width);
2724 let remaining_budget = context.budget(total_used_width);
2725 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2726 // and hence we take the closer into account as well for one line budget.
2727 // We assume that the closer has the same length as the opener.
2728 let overhead = if force_same_line_brace {
2729 1 + opener.len() + opener.len()
2733 let forbid_same_line_brace = overhead > remaining_budget;
2734 if !forbid_same_line_brace && same_line_brace {
2738 result.push_str(&offset.block_only().to_string(context.config));
2740 result.push_str(opener);
2745 impl Rewrite for ast::ForeignItem {
2746 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2747 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2748 // Drop semicolon or it will be interpreted as comment.
2749 // FIXME: this may be a faulty span from libsyntax.
2750 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2752 let item_str = try_opt!(match self.node {
2753 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2760 ast::Unsafety::Normal,
2761 ast::Constness::NotConst,
2762 ast::Defaultness::Final,
2763 // These are not actually rust functions,
2764 // but we format them as such.
2771 ).map(|(s, _)| format!("{};", s))
2773 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2774 // FIXME(#21): we're dropping potential comments in between the
2775 // function keywords here.
2776 let vis = format_visibility(&self.vis);
2777 let mut_str = if is_mutable { "mut " } else { "" };
2778 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2780 let shape = try_opt!(shape.sub_width(1));
2781 ty.rewrite(context, shape).map(|ty_str| {
2782 // 1 = space between prefix and type.
2783 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2786 let nested_indent = shape.indent.block_indent(context.config);
2787 format!("\n{}", nested_indent.to_string(context.config))
2789 format!("{}{}{};", prefix, sep, ty_str)
2794 let missing_span = if self.attrs.is_empty() {
2795 mk_sp(self.span.lo(), self.span.lo())
2797 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2799 combine_strs_with_missing_comments(