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 self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
254 newline_brace = true;
255 } else if last_line_width(&result) + 2 > self.shape().width {
257 newline_brace = true;
258 } else if !result.contains('\n') {
259 newline_brace = false;
262 // Prepare for the function body by possibly adding a newline and
264 // FIXME we'll miss anything between the end of the signature and the
265 // start of the body, but we need more spans from the compiler to solve
269 result.push_str(&indent.to_string(self.config));
274 self.single_line_fn(&result, block).or_else(|| Some(result))
277 pub fn rewrite_required_fn(
281 sig: &ast::MethodSig,
283 ) -> Option<String> {
284 // Drop semicolon or it will be interpreted as comment.
285 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
286 let context = self.get_context();
288 let (mut result, _) = try_opt!(rewrite_fn_base(
296 ast::Defaultness::Final,
298 &ast::Visibility::Inherited,
305 // Re-attach semicolon
311 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
312 if fn_str.contains('\n') {
316 let codemap = self.get_context().codemap;
318 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
319 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
321 return Some(format!("{}{{}}", fn_str));
324 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
326 if let Some(stmt) = block.stmts.first() {
327 match stmt_expr(stmt) {
329 let suffix = if semicolon_for_expr(&self.get_context(), e) {
335 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
337 .or_else(|| Some(self.snippet(e.span)))
339 None => stmt.rewrite(&self.get_context(), self.shape()),
346 if let Some(res) = rewrite {
347 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
348 if !res.contains('\n') && width <= self.config.max_width() {
349 return Some(format!("{}{{ {} }}", fn_str, res));
360 vis: &ast::Visibility,
361 enum_def: &ast::EnumDef,
362 generics: &ast::Generics,
365 let enum_header = format_header("enum ", ident, vis);
366 self.buffer.push_str(&enum_header);
368 let enum_snippet = self.snippet(span);
369 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
370 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
371 let generics_str = format_generics(
376 self.config.item_brace_style(),
377 enum_def.variants.is_empty(),
379 mk_sp(span.lo(), body_start),
380 last_line_width(&enum_header),
382 self.buffer.push_str(&generics_str);
384 self.last_pos = body_start;
386 self.block_indent = self.block_indent.block_indent(self.config);
387 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
389 Some(ref body_str) => self.buffer.push_str(body_str),
390 None => if contains_comment(&enum_snippet[brace_pos..]) {
391 self.format_missing_no_indent(span.hi() - BytePos(1))
394 self.block_indent = self.block_indent.block_unindent(self.config);
396 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
398 .push_str(&self.block_indent.to_string(self.config));
400 self.buffer.push_str("}");
401 self.last_pos = span.hi();
404 // Format the body of an enum definition
405 fn format_variant_list(
407 enum_def: &ast::EnumDef,
410 ) -> Option<String> {
411 if enum_def.variants.is_empty() {
414 let mut result = String::with_capacity(1024);
416 let indentation = self.block_indent.to_string(self.config);
417 result.push_str(&indentation);
419 let items = itemize_list(
421 enum_def.variants.iter(),
423 |f| if !f.node.attrs.is_empty() {
424 f.node.attrs[0].span.lo()
429 |f| self.format_variant(f),
435 let shape = self.shape().sub_width(2).unwrap();
436 let fmt = ListFormatting {
437 tactic: DefinitiveListTactic::Vertical,
439 trailing_separator: self.config.trailing_comma(),
440 separator_place: SeparatorPlace::Back,
442 ends_with_newline: true,
443 preserve_newline: true,
447 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
448 result.push_str(&list);
453 // Variant of an enum.
454 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
455 if contains_skip(&field.node.attrs) {
456 let lo = field.node.attrs[0].span.lo();
457 let span = mk_sp(lo, field.span.hi());
458 return Some(self.snippet(span));
461 let context = self.get_context();
462 let indent = self.block_indent;
463 let shape = self.shape();
464 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
469 .map_or(field.span.lo(), |attr| attr.span.hi());
470 let span = mk_sp(lo, field.span.lo());
472 let variant_body = match field.node.data {
473 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
474 // FIXME: Should limit the width, as we have a trailing comma
475 try_opt!(format_struct(
479 &ast::Visibility::Inherited,
484 Some(self.config.struct_variant_width()),
487 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
489 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
490 if one_line_width <= shape.width {
491 format!("{} = {}", field.node.name, self.snippet(expr.span))
498 .block_indent(self.config)
499 .to_string(self.config),
500 self.snippet(expr.span)
504 String::from(field.node.name.to_string())
508 let attrs_extendable = attrs_str.is_empty()
509 || (context.config.attributes_on_same_line_as_variant()
510 && is_attributes_extendable(&attrs_str));
511 combine_strs_with_missing_comments(
523 context: &RewriteContext,
526 where_span_end: Option<BytePos>,
527 ) -> Option<String> {
528 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
529 let mut result = String::with_capacity(128);
530 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
531 let indent_str = offset.to_string(context.config);
532 let sep = format!("\n{}", &indent_str);
533 result.push_str(&ref_and_type);
535 let where_budget = if result.contains('\n') {
536 context.config.max_width()
538 context.budget(last_line_width(&result))
540 let option = WhereClauseOption::snuggled(&ref_and_type);
541 let where_clause_str = try_opt!(rewrite_where_clause(
543 &generics.where_clause,
544 context.config.item_brace_style(),
545 Shape::legacy(where_budget, offset.block_only()),
546 context.config.where_density(),
553 // If there is no where clause, we may have missing comments between the trait name and
554 // the opening brace.
555 if generics.where_clause.predicates.is_empty() {
556 if let Some(hi) = where_span_end {
557 match recover_missing_comment_in_span(
558 mk_sp(self_ty.span.hi(), hi),
559 Shape::indented(offset, context.config),
561 last_line_width(&result),
563 Some(ref missing_comment) if !missing_comment.is_empty() => {
564 result.push_str(missing_comment);
571 if try_opt!(is_impl_single_line(
578 result.push_str(&where_clause_str);
579 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
580 result.push_str(&format!("{}{{{}}}", &sep, &sep));
582 result.push_str(" {}");
587 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
589 let width = offset.block_indent + context.config.tab_spaces() - 1;
590 let where_indent = Indent::new(0, width);
591 result.push_str(&where_indent.to_string(context.config));
593 result.push_str(&where_clause_str);
595 match context.config.item_brace_style() {
596 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
597 BraceStyle::AlwaysNextLine => result.push_str(&sep),
598 BraceStyle::PreferSameLine => result.push(' '),
599 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
600 result.push_str(&sep);
608 let snippet = context.snippet(item.span);
609 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
611 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
612 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
613 visitor.block_indent = offset.block_only().block_indent(context.config);
614 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
616 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
618 visitor.visit_impl_item(item);
621 visitor.format_missing(item.span.hi() - BytePos(1));
623 let inner_indent_str = visitor.block_indent.to_string(context.config);
624 let outer_indent_str = offset.block_only().to_string(context.config);
627 result.push_str(&inner_indent_str);
628 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
630 result.push_str(&outer_indent_str);
633 if result.chars().last().unwrap() == '{' {
634 result.push_str(&sep);
644 fn is_impl_single_line(
645 context: &RewriteContext,
648 where_clause_str: &str,
651 let snippet = context.snippet(item.span);
652 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
655 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
656 && result.len() + where_clause_str.len() <= context.config.max_width()
657 && !contains_comment(&snippet[open_pos..]),
661 fn format_impl_ref_and_type(
662 context: &RewriteContext,
665 ) -> Option<String> {
666 if let ast::ItemKind::Impl(
676 let mut result = String::with_capacity(128);
678 result.push_str(&format_visibility(&item.vis));
679 result.push_str(format_defaultness(defaultness));
680 result.push_str(format_unsafety(unsafety));
681 result.push_str("impl");
683 let lo = context.codemap.span_after(item.span, "impl");
684 let hi = match *trait_ref {
685 Some(ref tr) => tr.path.span.lo(),
686 None => self_ty.span.lo(),
688 let shape = try_opt!(generics_shape_from_config(
690 Shape::indented(offset + last_line_width(&result), context.config),
693 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
694 let generics_str = try_opt!(rewrite_generics_inner(
702 let polarity_str = if polarity == ast::ImplPolarity::Negative {
708 if let Some(ref trait_ref) = *trait_ref {
709 let result_len = result.len();
710 if let Some(trait_ref_str) = rewrite_trait_ref(
719 result.push_str(&trait_ref_str);
721 let generics_str = try_opt!(rewrite_generics_inner(
728 result.push_str(&try_opt!(rewrite_trait_ref(
739 result.push_str(&generics_str);
742 // Try to put the self type in a single line.
744 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
745 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
746 // If there is no where clause adapt budget for type formatting to take space and curly
747 // brace into account.
748 match context.config.item_brace_style() {
749 BraceStyle::AlwaysNextLine => 0,
755 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
756 // 1 = space before the type.
757 let budget = context.budget(used_space + 1);
758 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
759 if !self_ty_str.contains('\n') {
760 if trait_ref.is_some() {
761 result.push_str(" for ");
765 result.push_str(&self_ty_str);
770 // Couldn't fit the self type on a single line, put it on a new line.
772 // Add indentation of one additional tab.
773 let new_line_offset = offset.block_indent(context.config);
774 result.push_str(&new_line_offset.to_string(context.config));
775 if trait_ref.is_some() {
776 result.push_str("for ");
778 let budget = context.budget(last_line_width(&result));
779 let type_offset = match context.config.where_style() {
780 Style::Legacy => new_line_offset + trait_ref_overhead,
781 Style::Rfc => new_line_offset,
783 result.push_str(&*try_opt!(
784 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
792 fn rewrite_trait_ref(
793 context: &RewriteContext,
794 trait_ref: &ast::TraitRef,
800 ) -> Option<String> {
801 // 1 = space between generics and trait_ref
802 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
803 let shape = Shape::indented(offset + used_space, context.config);
804 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
805 if !(retry && trait_ref_str.contains('\n')) {
814 // We could not make enough space for trait_ref, so put it on new line.
816 let offset = offset.block_indent(context.config);
817 let shape = Shape::indented(offset, context.config);
818 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
822 &offset.to_string(context.config),
831 pub fn format_struct(
832 context: &RewriteContext,
835 vis: &ast::Visibility,
836 struct_def: &ast::VariantData,
837 generics: Option<&ast::Generics>,
840 one_line_width: Option<usize>,
841 ) -> Option<String> {
843 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
844 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
854 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
868 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
869 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
872 let mut result = String::with_capacity(128);
873 let header = format!(
875 format_visibility(&item.vis),
876 format_unsafety(unsafety),
880 result.push_str(&header);
882 let body_lo = context.codemap.span_after(item.span, "{");
884 let shape = Shape::indented(offset + last_line_width(&result), context.config);
885 let generics_str = try_opt!(rewrite_generics(
889 mk_sp(item.span.lo(), body_lo),
891 result.push_str(&generics_str);
893 let trait_bound_str = try_opt!(rewrite_trait_bounds(
896 Shape::indented(offset, context.config),
898 // If the trait, generics, and trait bound cannot fit on the same line,
899 // put the trait bounds on an indented new line
900 if offset.width() + last_line_width(&result) + trait_bound_str.len()
901 > context.config.comment_width()
904 let trait_indent = offset.block_only().block_indent(context.config);
905 result.push_str(&trait_indent.to_string(context.config));
907 result.push_str(&trait_bound_str);
909 let has_body = !trait_items.is_empty();
911 let where_density = if (context.config.where_density() == Density::Compressed
912 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
913 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
914 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
915 && !result.contains('\n'))
922 let where_budget = context.budget(last_line_width(&result));
923 let pos_before_where = if type_param_bounds.is_empty() {
924 generics.where_clause.span.lo()
926 type_param_bounds[type_param_bounds.len() - 1].span().hi()
928 let option = WhereClauseOption::snuggled(&generics_str);
929 let where_clause_str = try_opt!(rewrite_where_clause(
931 &generics.where_clause,
932 context.config.item_brace_style(),
933 Shape::legacy(where_budget, offset.block_only()),
940 // If the where clause cannot fit on the same line,
941 // put the where clause on a new line
942 if !where_clause_str.contains('\n')
943 && last_line_width(&result) + where_clause_str.len() + offset.width()
944 > context.config.comment_width()
947 let width = offset.block_indent + context.config.tab_spaces() - 1;
948 let where_indent = Indent::new(0, width);
949 result.push_str(&where_indent.to_string(context.config));
951 result.push_str(&where_clause_str);
953 if generics.where_clause.predicates.is_empty() {
954 let item_snippet = context.snippet(item.span);
955 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
957 let comment_hi = body_lo - BytePos(1);
958 let comment_lo = item.span.lo() + BytePos(lo as u32);
959 if comment_lo < comment_hi {
960 match recover_missing_comment_in_span(
961 mk_sp(comment_lo, comment_hi),
962 Shape::indented(offset, context.config),
964 last_line_width(&result),
966 Some(ref missing_comment) if !missing_comment.is_empty() => {
967 result.push_str(missing_comment);
975 match context.config.item_brace_style() {
976 _ if last_line_contains_single_line_comment(&result) => {
978 result.push_str(&offset.to_string(context.config));
980 BraceStyle::AlwaysNextLine => {
982 result.push_str(&offset.to_string(context.config));
984 BraceStyle::PreferSameLine => result.push(' '),
985 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
986 && (!trait_items.is_empty() || result.contains('\n'))
989 result.push_str(&offset.to_string(context.config));
996 let snippet = context.snippet(item.span);
997 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
999 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1000 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1001 visitor.block_indent = offset.block_only().block_indent(context.config);
1002 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1004 for item in trait_items {
1005 visitor.visit_trait_item(item);
1008 visitor.format_missing(item.span.hi() - BytePos(1));
1010 let inner_indent_str = visitor.block_indent.to_string(context.config);
1011 let outer_indent_str = offset.block_only().to_string(context.config);
1014 result.push_str(&inner_indent_str);
1015 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1017 result.push_str(&outer_indent_str);
1018 } else if result.contains('\n') {
1029 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1030 format!("{};", format_header(item_name, ident, vis))
1033 pub fn format_struct_struct(
1034 context: &RewriteContext,
1037 vis: &ast::Visibility,
1038 fields: &[ast::StructField],
1039 generics: Option<&ast::Generics>,
1042 one_line_width: Option<usize>,
1043 ) -> Option<String> {
1044 let mut result = String::with_capacity(1024);
1046 let header_str = format_header(item_name, ident, vis);
1047 result.push_str(&header_str);
1049 let body_lo = context.codemap.span_after(span, "{");
1051 let generics_str = match generics {
1052 Some(g) => try_opt!(format_generics(
1057 context.config.item_brace_style(),
1060 mk_sp(span.lo(), body_lo),
1061 last_line_width(&result),
1064 // 3 = ` {}`, 2 = ` {`.
1065 let overhead = if fields.is_empty() { 3 } else { 2 };
1066 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1067 && !fields.is_empty())
1068 || context.config.max_width() < overhead + result.len()
1070 format!("\n{}{{", offset.block_only().to_string(context.config))
1077 let overhead = if fields.is_empty() { 1 } else { 0 };
1078 let total_width = result.len() + generics_str.len() + overhead;
1079 if !generics_str.is_empty() && !generics_str.contains('\n')
1080 && total_width > context.config.max_width()
1083 result.push_str(&offset.to_string(context.config));
1084 result.push_str(generics_str.trim_left());
1086 result.push_str(&generics_str);
1089 if fields.is_empty() {
1090 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1091 if snippet.trim().is_empty() {
1093 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1095 result.push_str(snippet.trim_right());
1097 result.push_str(&offset.to_string(context.config));
1099 result.push_str(&snippet);
1102 return Some(result);
1106 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1107 let one_line_budget =
1108 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1110 let items_str = try_opt!(rewrite_with_alignment(
1113 Shape::indented(offset, context.config),
1114 mk_sp(body_lo, span.hi()),
1118 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1119 Some(format!("{} {} }}", result, items_str))
1125 .block_indent(context.config)
1126 .to_string(context.config),
1128 offset.to_string(context.config)
1133 fn format_tuple_struct(
1134 context: &RewriteContext,
1137 vis: &ast::Visibility,
1138 fields: &[ast::StructField],
1139 generics: Option<&ast::Generics>,
1142 ) -> Option<String> {
1143 let mut result = String::with_capacity(1024);
1145 let header_str = format_header(item_name, ident, vis);
1146 result.push_str(&header_str);
1148 let body_lo = if fields.is_empty() {
1149 context.codemap.span_after(span, "(")
1153 let body_hi = if fields.is_empty() {
1154 context.codemap.span_after(span, ")")
1156 // This is a dirty hack to work around a missing `)` from the span of the last field.
1157 let last_arg_span = fields[fields.len() - 1].span;
1158 if context.snippet(last_arg_span).ends_with(')') {
1163 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1167 let where_clause_str = match generics {
1169 let budget = context.budget(last_line_width(&header_str));
1170 let shape = Shape::legacy(budget, offset);
1171 let g_span = mk_sp(span.lo(), body_lo);
1172 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1173 result.push_str(&generics_str);
1175 let where_budget = context.budget(last_line_width(&result));
1176 let option = WhereClauseOption::new(true, false);
1177 try_opt!(rewrite_where_clause(
1179 &generics.where_clause,
1180 context.config.item_brace_style(),
1181 Shape::legacy(where_budget, offset.block_only()),
1182 Density::Compressed,
1189 None => "".to_owned(),
1192 if fields.is_empty() {
1194 let used_width = last_line_used_width(&result, offset.width()) + 3;
1195 if used_width > context.config.max_width() {
1197 result.push_str(&offset
1198 .block_indent(context.config)
1199 .to_string(context.config))
1202 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1203 if snippet.is_empty() {
1205 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1206 result.push_str(snippet.trim_right());
1208 result.push_str(&offset.to_string(context.config));
1210 result.push_str(&snippet);
1215 let body = try_opt!(
1219 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1221 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1222 context.config.fn_call_width(),
1226 result.push_str(&body);
1229 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1230 && (result.contains('\n')
1231 || offset.block_indent + result.len() + where_clause_str.len() + 1
1232 > context.config.max_width())
1234 // We need to put the where clause on a new line, but we didn't
1235 // know that earlier, so the where clause will not be indented properly.
1237 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1238 .to_string(context.config));
1240 result.push_str(&where_clause_str);
1245 pub fn rewrite_type_alias(
1246 context: &RewriteContext,
1250 generics: &ast::Generics,
1251 vis: &ast::Visibility,
1253 ) -> Option<String> {
1254 let mut result = String::with_capacity(128);
1256 result.push_str(&format_visibility(vis));
1257 result.push_str("type ");
1258 result.push_str(&ident.to_string());
1261 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1262 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1263 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1264 result.push_str(&generics_str);
1266 let where_budget = context.budget(last_line_width(&result));
1267 let option = WhereClauseOption::snuggled(&result);
1268 let where_clause_str = try_opt!(rewrite_where_clause(
1270 &generics.where_clause,
1271 context.config.item_brace_style(),
1272 Shape::legacy(where_budget, indent),
1273 context.config.where_density(),
1279 result.push_str(&where_clause_str);
1280 if where_clause_str.is_empty() {
1281 result.push_str(" = ");
1283 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1286 let line_width = last_line_width(&result);
1287 // This checked_sub may fail as the extra space after '=' is not taken into account
1288 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1289 let budget = context.budget(indent.width() + line_width + ";".len());
1290 let type_indent = indent + line_width;
1291 // Try to fit the type on the same line
1292 let ty_str = try_opt!(
1293 ty.rewrite(context, Shape::legacy(budget, type_indent))
1295 // The line was too short, try to put the type on the next line
1297 // Remove the space after '='
1299 let type_indent = indent.block_indent(context.config);
1301 result.push_str(&type_indent.to_string(context.config));
1302 let budget = context.budget(type_indent.width() + ";".len());
1303 ty.rewrite(context, Shape::legacy(budget, type_indent))
1306 result.push_str(&ty_str);
1307 result.push_str(";");
1311 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1313 if config.space_before_type_annotation() {
1318 if config.space_after_type_annotation_colon() {
1326 pub fn rewrite_struct_field_prefix(
1327 context: &RewriteContext,
1328 field: &ast::StructField,
1329 ) -> Option<String> {
1330 let vis = format_visibility(&field.vis);
1331 let type_annotation_spacing = type_annotation_spacing(context.config);
1332 Some(match field.ident {
1333 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1334 None => format!("{}", vis),
1338 fn rewrite_struct_field_type(
1339 context: &RewriteContext,
1340 last_line_width: usize,
1341 field: &ast::StructField,
1344 ) -> Option<String> {
1345 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1348 .rewrite(context, ty_shape)
1349 .map(|ty| format!("{}{}", spacing, ty))
1352 impl Rewrite for ast::StructField {
1353 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1354 rewrite_struct_field(context, self, shape, 0)
1358 pub fn rewrite_struct_field(
1359 context: &RewriteContext,
1360 field: &ast::StructField,
1362 lhs_max_width: usize,
1363 ) -> Option<String> {
1364 if contains_skip(&field.attrs) {
1365 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1368 let type_annotation_spacing = type_annotation_spacing(context.config);
1369 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1371 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1372 let attrs_extendable = attrs_str.is_empty()
1373 || (context.config.attributes_on_same_line_as_field()
1374 && is_attributes_extendable(&attrs_str));
1375 let missing_span = if field.attrs.is_empty() {
1376 mk_sp(field.span.lo(), field.span.lo())
1378 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1380 let mut spacing = String::from(if field.ident.is_some() {
1381 type_annotation_spacing.1
1385 // Try to put everything on a single line.
1386 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1394 let overhead = last_line_width(&attr_prefix);
1395 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1396 for _ in 0..lhs_offset {
1399 // In this extreme case we will be missing a space betweeen an attribute and a field.
1400 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1403 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1404 if let Some(ref ty) = ty_rewritten {
1405 if !ty.contains('\n') {
1406 return Some(attr_prefix + ty);
1410 // We must use multiline.
1411 let last_line_width = last_line_width(&prefix);
1412 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1414 let type_offset = shape.indent.block_indent(context.config);
1415 let rewrite_type_in_next_line = || {
1418 .rewrite(context, Shape::indented(type_offset, context.config))
1421 let field_str = match ty_rewritten {
1422 // If we start from the next line and type fits in a single line, then do so.
1423 Some(ref ty) => match rewrite_type_in_next_line() {
1424 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1427 type_offset.to_string(context.config),
1433 let ty = try_opt!(rewrite_type_in_next_line());
1437 type_offset.to_string(context.config),
1442 combine_strs_with_missing_comments(
1452 pub fn rewrite_static(
1454 vis: &ast::Visibility,
1457 mutability: ast::Mutability,
1458 expr_opt: Option<&ptr::P<ast::Expr>>,
1461 context: &RewriteContext,
1462 ) -> Option<String> {
1463 let colon = colon_spaces(
1464 context.config.space_before_type_annotation(),
1465 context.config.space_after_type_annotation_colon(),
1467 let prefix = format!(
1469 format_visibility(vis),
1471 format_mutability(mutability),
1476 let ty_str = try_opt!(ty.rewrite(
1479 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1483 if let Some(expr) = expr_opt {
1484 let lhs = format!("{}{} =", prefix, ty_str);
1486 let remaining_width = context.budget(offset.block_indent + 1);
1491 Shape::legacy(remaining_width, offset.block_only()),
1492 ).and_then(|res| recover_comment_removed(res, span, context))
1493 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1495 Some(format!("{}{};", prefix, ty_str))
1499 pub fn rewrite_associated_type(
1501 ty_opt: Option<&ptr::P<ast::Ty>>,
1502 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1503 context: &RewriteContext,
1505 ) -> Option<String> {
1506 let prefix = format!("type {}", ident);
1508 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1510 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1511 let bounds: &[_] = ty_param_bounds;
1512 let bound_str = try_opt!(
1515 .map(|ty_bound| ty_bound.rewrite(context, shape))
1516 .collect::<Option<Vec<_>>>()
1518 if !bounds.is_empty() {
1519 format!(": {}", join_bounds(context, shape, &bound_str))
1527 if let Some(ty) = ty_opt {
1528 let ty_str = try_opt!(ty.rewrite(
1531 context.budget(indent.block_indent + prefix.len() + 2),
1532 indent.block_only(),
1535 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1537 Some(format!("{}{};", prefix, type_bounds_str))
1541 pub fn rewrite_associated_impl_type(
1543 defaultness: ast::Defaultness,
1544 ty_opt: Option<&ptr::P<ast::Ty>>,
1545 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1546 context: &RewriteContext,
1548 ) -> Option<String> {
1549 let result = try_opt!(rewrite_associated_type(
1552 ty_param_bounds_opt,
1558 ast::Defaultness::Default => Some(format!("default {}", result)),
1563 impl Rewrite for ast::FunctionRetTy {
1564 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1566 ast::FunctionRetTy::Default(_) => Some(String::new()),
1567 ast::FunctionRetTy::Ty(ref ty) => {
1568 let inner_width = try_opt!(shape.width.checked_sub(3));
1569 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1570 .map(|r| format!("-> {}", r))
1576 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1578 ast::TyKind::Infer => {
1579 let original = context.snippet(ty.span);
1586 impl Rewrite for ast::Arg {
1587 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1588 if is_named_arg(self) {
1589 let mut result = try_opt!(
1591 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1594 if !is_empty_infer(context, &*self.ty) {
1595 if context.config.space_before_type_annotation() {
1596 result.push_str(" ");
1598 result.push_str(":");
1599 if context.config.space_after_type_annotation_colon() {
1600 result.push_str(" ");
1602 let overhead = last_line_width(&result);
1603 let max_width = try_opt!(shape.width.checked_sub(overhead));
1604 let ty_str = try_opt!(
1606 .rewrite(context, Shape::legacy(max_width, shape.indent))
1608 result.push_str(&ty_str);
1613 self.ty.rewrite(context, shape)
1618 fn rewrite_explicit_self(
1619 explicit_self: &ast::ExplicitSelf,
1621 context: &RewriteContext,
1622 ) -> Option<String> {
1623 match explicit_self.node {
1624 ast::SelfKind::Region(lt, m) => {
1625 let mut_str = format_mutability(m);
1628 let lifetime_str = try_opt!(l.rewrite(
1630 Shape::legacy(context.config.max_width(), Indent::empty()),
1632 Some(format!("&{} {}self", lifetime_str, mut_str))
1634 None => Some(format!("&{}self", mut_str)),
1637 ast::SelfKind::Explicit(ref ty, _) => {
1638 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1640 let mutability = explicit_self_mutability(&args[0]);
1641 let type_str = try_opt!(ty.rewrite(
1643 Shape::legacy(context.config.max_width(), Indent::empty()),
1648 format_mutability(mutability),
1652 ast::SelfKind::Value(_) => {
1653 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1655 let mutability = explicit_self_mutability(&args[0]);
1657 Some(format!("{}self", format_mutability(mutability)))
1662 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1663 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1664 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1665 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1672 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1673 if is_named_arg(arg) {
1680 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1682 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1683 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1684 _ => arg.ty.span.hi(),
1688 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1689 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1690 ident.node != symbol::keywords::Invalid.ident()
1696 // Return type is (result, force_new_line_for_brace)
1698 context: &RewriteContext,
1702 generics: &ast::Generics,
1703 unsafety: ast::Unsafety,
1704 constness: ast::Constness,
1705 defaultness: ast::Defaultness,
1707 vis: &ast::Visibility,
1709 newline_brace: bool,
1712 ) -> Option<(String, bool)> {
1713 let mut force_new_line_for_brace = false;
1715 let where_clause = &generics.where_clause;
1717 let mut result = String::with_capacity(1024);
1718 // Vis defaultness constness unsafety abi.
1719 result.push_str(&*format_visibility(vis));
1720 result.push_str(format_defaultness(defaultness));
1721 result.push_str(format_constness(constness));
1722 result.push_str(format_unsafety(unsafety));
1723 if abi != abi::Abi::Rust {
1724 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1728 result.push_str("fn ");
1729 result.push_str(&ident.to_string());
1732 let overhead = if has_braces && !newline_brace {
1739 let used_width = last_line_used_width(&result, indent.width());
1740 let one_line_budget = context.budget(used_width + overhead);
1742 width: one_line_budget,
1746 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1747 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1748 result.push_str(&generics_str);
1750 let snuggle_angle_bracket = generics_str
1753 .map_or(false, |l| l.trim_left().len() == 1);
1755 // Note that the width and indent don't really matter, we'll re-layout the
1756 // return type later anyway.
1757 let ret_str = try_opt!(
1759 .rewrite(context, Shape::indented(indent, context.config))
1762 let multi_line_ret_str = ret_str.contains('\n');
1763 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1766 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1777 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1783 // Check if vertical layout was forced.
1784 if one_line_budget == 0 {
1785 if snuggle_angle_bracket {
1787 } else if context.config.fn_args_paren_newline() {
1789 result.push_str(&arg_indent.to_string(context.config));
1790 if context.config.fn_args_layout() == IndentStyle::Visual {
1791 arg_indent = arg_indent + 1; // extra space for `(`
1795 result.push_str("(");
1796 if context.config.fn_args_layout() == IndentStyle::Visual {
1798 result.push_str(&arg_indent.to_string(context.config));
1804 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1808 // A conservative estimation, to goal is to be over all parens in generics
1809 let args_start = generics
1812 .map_or(span.lo(), |tp| end_typaram(tp));
1813 let args_end = if fd.inputs.is_empty() {
1816 .span_after(mk_sp(args_start, span.hi()), ")")
1818 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1819 context.codemap.span_after(last_span, ")")
1821 let args_span = mk_sp(
1824 .span_after(mk_sp(args_start, span.hi()), "("),
1827 let arg_str = try_opt!(rewrite_args(
1830 fd.get_self().as_ref(),
1837 generics_str.contains('\n'),
1840 let put_args_in_block = match context.config.fn_args_layout() {
1841 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1843 } && !fd.inputs.is_empty();
1845 let mut args_last_line_contains_comment = false;
1846 if put_args_in_block {
1847 arg_indent = indent.block_indent(context.config);
1849 result.push_str(&arg_indent.to_string(context.config));
1850 result.push_str(&arg_str);
1852 result.push_str(&indent.to_string(context.config));
1855 result.push_str(&arg_str);
1856 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1857 // Put the closing brace on the next line if it overflows the max width.
1859 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1862 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1865 // If the last line of args contains comment, we cannot put the closing paren
1866 // on the same line.
1870 .map_or(false, |last_line| last_line.contains("//"))
1872 args_last_line_contains_comment = true;
1874 result.push_str(&arg_indent.to_string(context.config));
1880 if let ast::FunctionRetTy::Ty(..) = fd.output {
1881 let ret_should_indent = match context.config.fn_args_layout() {
1882 // If our args are block layout then we surely must have space.
1883 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1884 _ if args_last_line_contains_comment => false,
1885 _ if result.contains('\n') || multi_line_ret_str => true,
1887 // If the return type would push over the max width, then put the return type on
1888 // a new line. With the +1 for the signature length an additional space between
1889 // the closing parenthesis of the argument and the arrow '->' is considered.
1890 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1892 // If there is no where clause, take into account the space after the return type
1894 if where_clause.predicates.is_empty() {
1898 sig_length > context.config.max_width()
1901 let ret_indent = if ret_should_indent {
1902 let indent = match context.config.fn_return_indent() {
1903 ReturnIndent::WithWhereClause => indent + 4,
1904 // Aligning with non-existent args looks silly.
1905 _ if arg_str.is_empty() => {
1906 force_new_line_for_brace = true;
1909 // FIXME: we might want to check that using the arg indent
1910 // doesn't blow our budget, and if it does, then fallback to
1911 // the where clause indent.
1916 result.push_str(&indent.to_string(context.config));
1920 Indent::new(indent.block_indent, last_line_width(&result))
1923 if multi_line_ret_str || ret_should_indent {
1924 // Now that we know the proper indent and width, we need to
1925 // re-layout the return type.
1926 let ret_str = try_opt!(
1928 .rewrite(context, Shape::indented(ret_indent, context.config))
1930 result.push_str(&ret_str);
1932 result.push_str(&ret_str);
1935 // Comment between return type and the end of the decl.
1936 let snippet_lo = fd.output.span().hi();
1937 if where_clause.predicates.is_empty() {
1938 let snippet_hi = span.hi();
1939 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1940 // Try to preserve the layout of the original snippet.
1941 let original_starts_with_newline = snippet
1943 .map_or(false, |i| snippet[i..].starts_with('\n'));
1944 let original_ends_with_newline = snippet
1945 .rfind(|c| c != ' ')
1946 .map_or(false, |i| snippet[i..].ends_with('\n'));
1947 let snippet = snippet.trim();
1948 if !snippet.is_empty() {
1949 result.push(if original_starts_with_newline {
1954 result.push_str(snippet);
1955 if original_ends_with_newline {
1956 force_new_line_for_brace = true;
1962 let should_compress_where = match context.config.where_density() {
1963 Density::Compressed => !result.contains('\n'),
1964 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1968 let pos_before_where = match fd.output {
1969 ast::FunctionRetTy::Default(..) => args_span.hi(),
1970 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1973 if where_clause.predicates.len() == 1 && should_compress_where {
1974 let budget = context.budget(last_line_used_width(&result, indent.width()));
1975 if let Some(where_clause_str) = rewrite_where_clause(
1978 context.config.fn_brace_style(),
1979 Shape::legacy(budget, indent),
1980 Density::Compressed,
1984 WhereClauseOption::compressed(),
1986 result.push_str(&where_clause_str);
1987 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1988 return Some((result, force_new_line_for_brace));
1992 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
1993 let where_clause_str = try_opt!(rewrite_where_clause(
1996 context.config.fn_brace_style(),
1997 Shape::indented(indent, context.config),
2004 // If there are neither where clause nor return type, we may be missing comments between
2006 if where_clause_str.is_empty() {
2007 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2008 match recover_missing_comment_in_span(
2009 mk_sp(args_span.hi(), ret_span.hi()),
2012 last_line_width(&result),
2014 Some(ref missing_comment) if !missing_comment.is_empty() => {
2015 result.push_str(missing_comment);
2016 force_new_line_for_brace = true;
2023 result.push_str(&where_clause_str);
2025 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2026 Some((result, force_new_line_for_brace))
2029 #[derive(Copy, Clone)]
2030 struct WhereClauseOption {
2031 suppress_comma: bool, // Force no trailing comma
2032 snuggle: bool, // Do not insert newline before `where`
2033 compress_where: bool, // Try single line where clause instead of vertical layout
2036 impl WhereClauseOption {
2037 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2039 suppress_comma: suppress_comma,
2041 compress_where: false,
2045 pub fn compressed() -> WhereClauseOption {
2047 suppress_comma: true,
2049 compress_where: true,
2053 pub fn snuggled(current: &str) -> WhereClauseOption {
2055 suppress_comma: false,
2056 snuggle: trimmed_last_line_width(current) == 1,
2057 compress_where: false,
2063 context: &RewriteContext,
2065 explicit_self: Option<&ast::ExplicitSelf>,
2066 one_line_budget: usize,
2067 multi_line_budget: usize,
2072 generics_str_contains_newline: bool,
2073 ) -> Option<String> {
2074 let mut arg_item_strs = try_opt!(
2077 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2079 .collect::<Option<Vec<_>>>()
2082 // Account for sugary self.
2083 // FIXME: the comment for the self argument is dropped. This is blocked
2084 // on rust issue #27522.
2085 let min_args = explicit_self
2086 .and_then(|explicit_self| {
2087 rewrite_explicit_self(explicit_self, args, context)
2089 .map_or(1, |self_str| {
2090 arg_item_strs[0] = self_str;
2094 // Comments between args.
2095 let mut arg_items = Vec::new();
2097 arg_items.push(ListItem::from_str(""));
2100 // FIXME(#21): if there are no args, there might still be a comment, but
2101 // without spans for the comment or parens, there is no chance of
2102 // getting it right. You also don't get to put a comment on self, unless
2104 if args.len() >= min_args || variadic {
2105 let comment_span_start = if min_args == 2 {
2106 let second_arg_start = if arg_has_pattern(&args[1]) {
2107 args[1].pat.span.lo()
2109 args[1].ty.span.lo()
2111 let reduced_span = mk_sp(span.lo(), second_arg_start);
2113 context.codemap.span_after_last(reduced_span, ",")
2118 enum ArgumentKind<'a> {
2119 Regular(&'a ast::Arg),
2123 let variadic_arg = if variadic {
2124 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2125 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2126 Some(ArgumentKind::Variadic(variadic_start))
2131 let more_items = itemize_list(
2133 args[min_args - 1..]
2135 .map(ArgumentKind::Regular)
2136 .chain(variadic_arg),
2139 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2140 ArgumentKind::Variadic(start) => start,
2143 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2144 ArgumentKind::Variadic(start) => start + BytePos(3),
2147 ArgumentKind::Regular(..) => None,
2148 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2155 arg_items.extend(more_items);
2158 let fits_in_one_line = !generics_str_contains_newline
2159 && (arg_items.is_empty()
2160 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2162 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2163 item.item = Some(arg);
2166 let last_line_ends_with_comment = arg_items
2169 .and_then(|item| item.post_comment.as_ref())
2170 .map_or(false, |s| s.trim().starts_with("//"));
2172 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2173 IndentStyle::Block if fits_in_one_line => {
2174 (indent.block_indent(context.config), SeparatorTactic::Never)
2176 IndentStyle::Block => (
2177 indent.block_indent(context.config),
2178 context.config.trailing_comma(),
2180 IndentStyle::Visual if last_line_ends_with_comment => {
2181 (arg_indent, context.config.trailing_comma())
2183 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2186 let tactic = definitive_tactic(
2188 context.config.fn_args_density().to_list_tactic(),
2192 let budget = match tactic {
2193 DefinitiveListTactic::Horizontal => one_line_budget,
2194 _ => multi_line_budget,
2197 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2199 let fmt = ListFormatting {
2202 trailing_separator: if variadic {
2203 SeparatorTactic::Never
2207 separator_place: SeparatorPlace::Back,
2208 shape: Shape::legacy(budget, indent),
2209 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2210 preserve_newline: true,
2211 config: context.config,
2214 write_list(&arg_items, &fmt)
2217 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2218 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2219 ident.node != symbol::keywords::Invalid.ident()
2225 fn compute_budgets_for_args(
2226 context: &RewriteContext,
2230 newline_brace: bool,
2232 force_vertical_layout: bool,
2233 ) -> Option<((usize, usize, Indent))> {
2235 "compute_budgets_for_args {} {:?}, {}, {}",
2241 // Try keeping everything on the same line.
2242 if !result.contains('\n') && !force_vertical_layout {
2243 // 2 = `()`, 3 = `() `, space is before ret_string.
2244 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2245 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2255 let one_line_budget = context.budget(used_space);
2257 if one_line_budget > 0 {
2259 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2260 IndentStyle::Block => {
2261 let indent = indent.block_indent(context.config);
2262 (indent, context.budget(indent.width() + 1))
2264 IndentStyle::Visual => {
2265 let indent = indent + result.len() + 1;
2266 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2267 (indent, context.budget(multi_line_overhead))
2271 return Some((one_line_budget, multi_line_budget, indent));
2275 // Didn't work. we must force vertical layout and put args on a newline.
2276 let new_indent = indent.block_indent(context.config);
2277 let used_space = match context.config.fn_args_layout() {
2279 IndentStyle::Block => new_indent.width() + 1,
2280 // Account for `)` and possibly ` {`.
2281 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2283 Some((0, context.budget(used_space), new_indent))
2286 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2287 match (config.fn_brace_style(), config.where_density()) {
2288 (BraceStyle::AlwaysNextLine, _) => true,
2289 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2290 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2291 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2296 fn rewrite_generics(
2297 context: &RewriteContext,
2298 generics: &ast::Generics,
2301 ) -> Option<String> {
2302 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2303 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2304 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2305 rewrite_generics_inner(context, generics, g_shape, 0, span)
2309 fn rewrite_generics_inner(
2310 context: &RewriteContext,
2311 generics: &ast::Generics,
2313 one_line_width: usize,
2315 ) -> Option<String> {
2316 // FIXME: convert bounds to where clauses where they get too big or if
2317 // there is a where clause at all.
2320 enum GenericsArg<'a> {
2321 Lifetime(&'a ast::LifetimeDef),
2322 TyParam(&'a ast::TyParam),
2324 impl<'a> Rewrite for GenericsArg<'a> {
2325 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2327 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2328 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2332 impl<'a> Spanned for GenericsArg<'a> {
2333 fn span(&self) -> Span {
2335 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2336 GenericsArg::TyParam(ref ty) => ty.span(),
2341 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2342 return Some(String::new());
2345 let generics_args = generics
2348 .map(|lt| GenericsArg::Lifetime(lt))
2349 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2350 let items = itemize_list(
2354 |arg| arg.span().lo(),
2355 |arg| arg.span().hi(),
2356 |arg| arg.rewrite(context, shape),
2357 context.codemap.span_after(span, "<"),
2361 format_generics_item_list(context, items, shape, one_line_width)
2364 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2365 match config.generics_indent() {
2366 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2367 IndentStyle::Block => {
2371 .block_indent(config.tab_spaces())
2372 .with_max_width(config)
2378 pub fn format_generics_item_list<I>(
2379 context: &RewriteContext,
2382 one_line_budget: usize,
2385 I: Iterator<Item = ListItem>,
2387 let item_vec = items.collect::<Vec<_>>();
2389 let tactic = definitive_tactic(
2391 ListTactic::HorizontalVertical,
2395 let fmt = ListFormatting {
2398 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2399 SeparatorTactic::Never
2401 context.config.trailing_comma()
2403 separator_place: SeparatorPlace::Back,
2405 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2406 preserve_newline: true,
2407 config: context.config,
2410 let list_str = try_opt!(write_list(&item_vec, &fmt));
2412 Some(wrap_generics_with_angle_brackets(
2419 pub fn wrap_generics_with_angle_brackets(
2420 context: &RewriteContext,
2422 list_offset: Indent,
2424 if context.config.generics_indent() == IndentStyle::Block
2425 && (list_str.contains('\n') || list_str.ends_with(','))
2429 list_offset.to_string(context.config),
2432 .block_unindent(context.config)
2433 .to_string(context.config)
2435 } else if context.config.spaces_within_angle_brackets() {
2436 format!("< {} >", list_str)
2438 format!("<{}>", list_str)
2442 fn rewrite_trait_bounds(
2443 context: &RewriteContext,
2444 type_param_bounds: &ast::TyParamBounds,
2446 ) -> Option<String> {
2447 let bounds: &[_] = type_param_bounds;
2449 if bounds.is_empty() {
2450 return Some(String::new());
2452 let bound_str = try_opt!(
2455 .map(|ty_bound| ty_bound.rewrite(context, shape))
2456 .collect::<Option<Vec<_>>>()
2458 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2461 fn rewrite_where_clause_rfc_style(
2462 context: &RewriteContext,
2463 where_clause: &ast::WhereClause,
2466 span_end: Option<BytePos>,
2467 span_end_before_where: BytePos,
2468 where_clause_option: WhereClauseOption,
2469 ) -> Option<String> {
2470 let block_shape = shape.block().with_max_width(context.config);
2472 let (span_before, span_after) =
2473 missing_span_before_after_where(span_end_before_where, where_clause);
2474 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2481 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2484 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2487 let clause_shape = try_opt!(block_shape.block_left(context.config.tab_spaces()));
2489 let clause_shape = try_opt!(clause_shape.sub_width(1));
2490 // each clause on one line, trailing comma (except if suppress_comma)
2491 let span_start = where_clause.predicates[0].span().lo();
2492 // If we don't have the start of the next span, then use the end of the
2493 // predicates, but that means we miss comments.
2494 let len = where_clause.predicates.len();
2495 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2496 let span_end = span_end.unwrap_or(end_of_preds);
2497 let items = itemize_list(
2499 where_clause.predicates.iter(),
2501 |pred| pred.span().lo(),
2502 |pred| pred.span().hi(),
2503 |pred| pred.rewrite(context, clause_shape),
2508 let comma_tactic = if where_clause_option.suppress_comma {
2509 SeparatorTactic::Never
2511 context.config.trailing_comma()
2514 let fmt = ListFormatting {
2515 tactic: DefinitiveListTactic::Vertical,
2517 trailing_separator: comma_tactic,
2518 separator_place: SeparatorPlace::Back,
2519 shape: clause_shape,
2520 ends_with_newline: true,
2521 preserve_newline: true,
2522 config: context.config,
2524 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2526 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2529 format!("\n{}", shape.indent.to_string(context.config))
2531 let newline_before_where = comment_separator(&comment_before, shape);
2532 let newline_after_where = comment_separator(&comment_after, clause_shape);
2535 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2536 && comment_after.is_empty() && !preds_str.contains('\n')
2537 && 6 + preds_str.len() <= shape.width
2541 format!("\n{}", clause_shape.indent.to_string(context.config))
2544 "{}{}{}where{}{}{}{}",
2547 newline_before_where,
2548 newline_after_where,
2555 fn rewrite_where_clause(
2556 context: &RewriteContext,
2557 where_clause: &ast::WhereClause,
2558 brace_style: BraceStyle,
2562 span_end: Option<BytePos>,
2563 span_end_before_where: BytePos,
2564 where_clause_option: WhereClauseOption,
2565 ) -> Option<String> {
2566 if where_clause.predicates.is_empty() {
2567 return Some(String::new());
2570 if context.config.where_style() == Style::Rfc {
2571 return rewrite_where_clause_rfc_style(
2577 span_end_before_where,
2578 where_clause_option,
2582 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2584 let offset = match context.config.where_pred_indent() {
2585 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2586 // 6 = "where ".len()
2587 IndentStyle::Visual => shape.indent + extra_indent + 6,
2589 // FIXME: if where_pred_indent != Visual, then the budgets below might
2590 // be out by a char or two.
2592 let budget = context.config.max_width() - offset.width();
2593 let span_start = where_clause.predicates[0].span().lo();
2594 // If we don't have the start of the next span, then use the end of the
2595 // predicates, but that means we miss comments.
2596 let len = where_clause.predicates.len();
2597 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2598 let span_end = span_end.unwrap_or(end_of_preds);
2599 let items = itemize_list(
2601 where_clause.predicates.iter(),
2603 |pred| pred.span().lo(),
2604 |pred| pred.span().hi(),
2605 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2610 let item_vec = items.collect::<Vec<_>>();
2611 // FIXME: we don't need to collect here if the where_layout isn't
2612 // HorizontalVertical.
2613 let tactic = definitive_tactic(
2615 context.config.where_layout(),
2620 let mut comma_tactic = context.config.trailing_comma();
2621 // Kind of a hack because we don't usually have trailing commas in where clauses.
2622 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2623 comma_tactic = SeparatorTactic::Never;
2626 let fmt = ListFormatting {
2629 trailing_separator: comma_tactic,
2630 separator_place: SeparatorPlace::Back,
2631 shape: Shape::legacy(budget, offset),
2632 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2633 preserve_newline: true,
2634 config: context.config,
2636 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2638 let end_length = if terminator == "{" {
2639 // If the brace is on the next line we don't need to count it otherwise it needs two
2642 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2643 BraceStyle::PreferSameLine => 2,
2645 } else if terminator == "=" {
2650 if density == Density::Tall || preds_str.contains('\n')
2651 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2655 (shape.indent + extra_indent).to_string(context.config),
2659 Some(format!(" where {}", preds_str))
2663 fn missing_span_before_after_where(
2664 before_item_span_end: BytePos,
2665 where_clause: &ast::WhereClause,
2667 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2669 let pos_after_where = where_clause.span.lo() + BytePos(5);
2670 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2671 (missing_span_before, missing_span_after)
2674 fn rewrite_comments_before_after_where(
2675 context: &RewriteContext,
2676 span_before_where: Span,
2677 span_after_where: Span,
2679 ) -> Option<(String, String)> {
2680 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2681 let after_comment = try_opt!(rewrite_missing_comment(
2683 shape.block_indent(context.config.tab_spaces()),
2686 Some((before_comment, after_comment))
2689 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2690 format!("{}{}{}", format_visibility(vis), item_name, ident)
2694 context: &RewriteContext,
2695 generics: &ast::Generics,
2698 brace_style: BraceStyle,
2699 force_same_line_brace: bool,
2703 ) -> Option<String> {
2704 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2705 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2707 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2708 let budget = context.budget(last_line_used_width(&result, offset.width()));
2709 let option = WhereClauseOption::snuggled(&result);
2710 let where_clause_str = try_opt!(rewrite_where_clause(
2712 &generics.where_clause,
2714 Shape::legacy(budget, offset.block_only()),
2721 result.push_str(&where_clause_str);
2722 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2723 || (generics.where_clause.predicates.is_empty()
2724 && trimmed_last_line_width(&result) == 1)
2726 force_same_line_brace || trimmed_last_line_width(&result) == 1
2727 || brace_style != BraceStyle::AlwaysNextLine
2729 let total_used_width = last_line_used_width(&result, used_width);
2730 let remaining_budget = context.budget(total_used_width);
2731 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2732 // and hence we take the closer into account as well for one line budget.
2733 // We assume that the closer has the same length as the opener.
2734 let overhead = if force_same_line_brace {
2735 1 + opener.len() + opener.len()
2739 let forbid_same_line_brace = overhead > remaining_budget;
2740 if !forbid_same_line_brace && same_line_brace {
2744 result.push_str(&offset.block_only().to_string(context.config));
2746 result.push_str(opener);
2751 impl Rewrite for ast::ForeignItem {
2752 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2753 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2754 // Drop semicolon or it will be interpreted as comment.
2755 // FIXME: this may be a faulty span from libsyntax.
2756 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2758 let item_str = try_opt!(match self.node {
2759 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2766 ast::Unsafety::Normal,
2767 ast::Constness::NotConst,
2768 ast::Defaultness::Final,
2769 // These are not actually rust functions,
2770 // but we format them as such.
2777 ).map(|(s, _)| format!("{};", s))
2779 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2780 // FIXME(#21): we're dropping potential comments in between the
2781 // function keywords here.
2782 let vis = format_visibility(&self.vis);
2783 let mut_str = if is_mutable { "mut " } else { "" };
2784 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2786 let shape = try_opt!(shape.sub_width(1));
2787 ty.rewrite(context, shape).map(|ty_str| {
2788 // 1 = space between prefix and type.
2789 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2792 let nested_indent = shape.indent.block_indent(context.config);
2793 format!("\n{}", nested_indent.to_string(context.config))
2795 format!("{}{}{};", prefix, sep, ty_str)
2800 let missing_span = if self.attrs.is_empty() {
2801 mk_sp(self.span.lo(), self.span.lo())
2803 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2805 combine_strs_with_missing_comments(