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};
19 use {Indent, Shape, Spanned};
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 types::join_bounds;
30 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
31 format_constness, format_defaultness, format_mutability, format_unsafety,
32 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
33 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, stmt_expr,
34 trim_newlines, trimmed_last_line_width, wrap_str};
35 use vertical::rewrite_with_alignment;
36 use visitor::FmtVisitor;
38 fn type_annotation_separator(config: &Config) -> &str {
40 config.space_before_type_annotation(),
41 config.space_after_type_annotation_colon(),
45 // Statements of the form
46 // let pat: ty = init;
47 impl Rewrite for ast::Local {
48 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
50 "Local::rewrite {:?} {} {:?}",
56 skip_out_of_file_lines_range!(context, self.span);
58 if contains_skip(&self.attrs) {
62 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
63 let mut result = if attrs_str.is_empty() {
66 try_opt!(combine_strs_with_missing_comments(
70 mk_sp(self.attrs.last().map(|a| a.span.hi).unwrap(), self.span.lo),
77 let pat_shape = try_opt!(shape.offset_left(4));
79 let pat_shape = try_opt!(pat_shape.sub_width(1));
80 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
81 result.push_str(&pat_str);
83 // String that is placed within the assignment pattern and expression.
85 let mut infix = String::with_capacity(32);
87 if let Some(ref ty) = self.ty {
88 let separator = type_annotation_separator(context.config);
89 let indent = shape.indent + last_line_width(&result) + separator.len();
91 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
92 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
94 infix.push_str(separator);
95 infix.push_str(&rewrite);
98 if self.init.is_some() {
105 result.push_str(&infix);
107 if let Some(ref ex) = self.init {
108 // 1 = trailing semicolon;
109 let nested_shape = try_opt!(shape.sub_width(1));
111 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
119 // TODO convert to using rewrite style rather than visitor
120 // TODO format modules in this style
123 keyword: &'static str,
125 vis: Option<&'a ast::Visibility>,
126 body: Vec<BodyElement<'a>>,
131 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
132 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
135 format!("extern {}", fm.abi)
143 .map(|i| BodyElement::ForeignItem(i))
150 enum BodyElement<'a> {
151 // Stmt(&'a ast::Stmt),
152 // Field(&'a ast::Field),
153 // Variant(&'a ast::Variant),
154 // Item(&'a ast::Item),
155 ForeignItem(&'a ast::ForeignItem),
158 impl<'a> FmtVisitor<'a> {
159 fn format_item(&mut self, item: Item) {
160 self.buffer.push_str(&item.abi);
161 self.buffer.push_str(" ");
163 let snippet = self.snippet(item.span);
164 let brace_pos = snippet.find_uncommented("{").unwrap();
166 self.buffer.push_str("{");
167 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
168 // FIXME: this skips comments between the extern keyword and the opening
170 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
171 self.block_indent = self.block_indent.block_indent(self.config);
173 if item.body.is_empty() {
174 self.format_missing_no_indent(item.span.hi - BytePos(1));
175 self.block_indent = self.block_indent.block_unindent(self.config);
178 .push_str(&self.block_indent.to_string(self.config));
180 for item in &item.body {
181 self.format_body_element(item);
184 self.block_indent = self.block_indent.block_unindent(self.config);
185 self.format_missing_with_indent(item.span.hi - BytePos(1));
189 self.buffer.push_str("}");
190 self.last_pos = item.span.hi;
193 fn format_body_element(&mut self, element: &BodyElement) {
195 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
199 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
200 let item = Item::from_foreign_mod(fm, span, self.config);
201 self.format_item(item);
205 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
206 let rewrite = item.rewrite(&self.get_context(), self.shape());
207 self.push_rewrite(item.span(), rewrite);
208 self.last_pos = item.span.hi;
216 generics: &ast::Generics,
217 unsafety: ast::Unsafety,
218 constness: ast::Constness,
219 defaultness: ast::Defaultness,
221 vis: &ast::Visibility,
224 ) -> Option<String> {
225 let context = self.get_context();
227 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
228 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
229 !context.config.fn_empty_single_line();
230 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
232 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
249 if force_newline_brace {
250 newline_brace = true;
251 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
252 !result.contains('\n')
254 newline_brace = false;
257 // Prepare for the function body by possibly adding a newline and
259 // FIXME we'll miss anything between the end of the signature and the
260 // start of the body, but we need more spans from the compiler to solve
264 result.push_str(&indent.to_string(self.config));
269 self.single_line_fn(&result, block).or_else(|| Some(result))
272 pub fn rewrite_required_fn(
276 sig: &ast::MethodSig,
278 ) -> Option<String> {
279 // Drop semicolon or it will be interpreted as comment.
280 let span = mk_sp(span.lo, span.hi - BytePos(1));
281 let context = self.get_context();
283 let (mut result, _) = try_opt!(rewrite_fn_base(
291 ast::Defaultness::Final,
293 &ast::Visibility::Inherited,
300 // Re-attach semicolon
306 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
307 if fn_str.contains('\n') {
311 let codemap = self.get_context().codemap;
313 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
314 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
316 return Some(format!("{}{{}}", fn_str));
319 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
321 if let Some(ref stmt) = block.stmts.first() {
322 match stmt_expr(stmt) {
324 let suffix = if semicolon_for_expr(&self.get_context(), e) {
330 format_expr(&e, ExprType::Statement, &self.get_context(), self.shape())
332 .or_else(|| Some(self.snippet(e.span)))
334 None => stmt.rewrite(&self.get_context(), self.shape()),
341 if let Some(res) = rewrite {
342 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
343 if !res.contains('\n') && width <= self.config.max_width() {
344 return Some(format!("{}{{ {} }}", fn_str, res));
355 vis: &ast::Visibility,
356 enum_def: &ast::EnumDef,
357 generics: &ast::Generics,
360 let enum_header = format_header("enum ", ident, vis);
361 self.buffer.push_str(&enum_header);
363 let enum_snippet = self.snippet(span);
364 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
365 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
366 let generics_str = format_generics(
371 self.config.item_brace_style(),
372 enum_def.variants.is_empty(),
374 mk_sp(span.lo, body_start),
375 last_line_width(&enum_header),
377 self.buffer.push_str(&generics_str);
379 self.last_pos = body_start;
381 self.block_indent = self.block_indent.block_indent(self.config);
382 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
384 Some(ref body_str) => self.buffer.push_str(body_str),
385 None => if contains_comment(&enum_snippet[brace_pos..]) {
386 self.format_missing_no_indent(span.hi - BytePos(1))
388 self.format_missing(span.hi - BytePos(1))
391 self.block_indent = self.block_indent.block_unindent(self.config);
393 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
395 .push_str(&self.block_indent.to_string(self.config));
397 self.buffer.push_str("}");
398 self.last_pos = span.hi;
401 // Format the body of an enum definition
402 fn format_variant_list(
404 enum_def: &ast::EnumDef,
407 ) -> Option<String> {
408 if enum_def.variants.is_empty() {
411 let mut result = String::with_capacity(1024);
413 let indentation = self.block_indent.to_string(self.config);
414 result.push_str(&indentation);
416 let items = itemize_list(
418 enum_def.variants.iter(),
420 |f| if !f.node.attrs.is_empty() {
421 f.node.attrs[0].span.lo
426 |f| self.format_variant(f),
432 let shape = self.shape().sub_width(2).unwrap();
433 let fmt = ListFormatting {
434 tactic: DefinitiveListTactic::Vertical,
436 trailing_separator: self.config.trailing_comma(),
437 separator_place: SeparatorPlace::Back,
439 ends_with_newline: true,
440 preserve_newline: true,
444 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
445 result.push_str(&list);
450 // Variant of an enum.
451 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
452 if contains_skip(&field.node.attrs) {
453 let lo = field.node.attrs[0].span.lo;
454 let span = mk_sp(lo, field.span.hi);
455 return Some(self.snippet(span));
458 let context = self.get_context();
459 let indent = self.block_indent;
460 let shape = self.shape();
461 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
466 .map_or(field.span.lo, |attr| attr.span.hi);
467 let span = mk_sp(lo, field.span.lo);
469 let variant_body = match field.node.data {
470 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
471 // FIXME: Should limit the width, as we have a trailing comma
472 try_opt!(format_struct(
476 &ast::Visibility::Inherited,
481 Some(self.config.struct_variant_width()),
484 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
486 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
487 if one_line_width <= shape.width {
488 format!("{} = {}", field.node.name, self.snippet(expr.span))
495 .block_indent(self.config)
496 .to_string(self.config),
497 self.snippet(expr.span)
501 String::from(field.node.name.to_string())
505 let attrs_extendable = attrs_str.is_empty() ||
506 (context.config.attributes_on_same_line_as_variant() &&
507 is_attributes_extendable(&attrs_str));
508 combine_strs_with_missing_comments(
520 context: &RewriteContext,
523 where_span_end: Option<BytePos>,
524 ) -> Option<String> {
525 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
526 let mut result = String::with_capacity(128);
527 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
528 let indent_str = offset.to_string(context.config);
529 let sep = format!("\n{}", &indent_str);
530 result.push_str(&ref_and_type);
532 let where_budget = if result.contains('\n') {
533 context.config.max_width()
538 .checked_sub(last_line_width(&result))
541 let option = WhereClauseOption::snuggled(&ref_and_type);
542 let where_clause_str = try_opt!(rewrite_where_clause(
544 &generics.where_clause,
545 context.config.item_brace_style(),
546 Shape::legacy(where_budget, offset.block_only()),
547 context.config.where_density(),
554 // If there is no where clause, we may have missing comments between the trait name and
555 // the opening brace.
556 if generics.where_clause.predicates.is_empty() {
557 if let Some(hi) = where_span_end {
558 match recover_missing_comment_in_span(
559 mk_sp(self_ty.span.hi, hi),
560 Shape::indented(offset, context.config),
562 last_line_width(&result),
564 Some(ref missing_comment) if !missing_comment.is_empty() => {
565 result.push_str(missing_comment);
572 if try_opt!(is_impl_single_line(
579 result.push_str(&where_clause_str);
580 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
581 result.push_str(&format!("{}{{{}}}", &sep, &sep));
583 result.push_str(" {}");
588 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
590 let width = offset.block_indent + context.config.tab_spaces() - 1;
591 let where_indent = Indent::new(0, width);
592 result.push_str(&where_indent.to_string(context.config));
594 result.push_str(&where_clause_str);
596 match context.config.item_brace_style() {
597 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
598 BraceStyle::AlwaysNextLine => result.push_str(&sep),
599 BraceStyle::PreferSameLine => result.push(' '),
600 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
601 result.push_str(&sep);
609 let snippet = context.snippet(item.span);
610 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
612 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
613 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
614 visitor.block_indent = offset.block_only().block_indent(context.config);
615 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
617 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
619 visitor.visit_impl_item(item);
622 visitor.format_missing(item.span.hi - BytePos(1));
624 let inner_indent_str = visitor.block_indent.to_string(context.config);
625 let outer_indent_str = offset.block_only().to_string(context.config);
628 result.push_str(&inner_indent_str);
629 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
631 result.push_str(&outer_indent_str);
634 if result.chars().last().unwrap() == '{' {
635 result.push_str(&sep);
645 fn is_impl_single_line(
646 context: &RewriteContext,
649 where_clause_str: &str,
652 let snippet = context.snippet(item.span);
653 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
656 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n') &&
657 result.len() + where_clause_str.len() <= context.config.max_width() &&
658 !contains_comment(&snippet[open_pos..]),
662 fn format_impl_ref_and_type(
663 context: &RewriteContext,
666 ) -> Option<String> {
667 if let ast::ItemKind::Impl(
677 let mut result = String::with_capacity(128);
679 result.push_str(&format_visibility(&item.vis));
680 result.push_str(&format_defaultness(defaultness));
681 result.push_str(format_unsafety(unsafety));
682 result.push_str("impl");
684 let lo = context.codemap.span_after(item.span, "impl");
685 let hi = match *trait_ref {
686 Some(ref tr) => tr.path.span.lo,
687 None => self_ty.span.lo,
689 let shape = try_opt!(generics_shape_from_config(
691 Shape::indented(offset + last_line_width(&result), context.config),
694 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
695 let generics_str = try_opt!(rewrite_generics_inner(
703 let polarity_str = if polarity == ast::ImplPolarity::Negative {
709 if let Some(ref trait_ref) = *trait_ref {
710 let result_len = result.len();
711 if let Some(trait_ref_str) = rewrite_trait_ref(
720 result.push_str(&trait_ref_str);
722 let generics_str = try_opt!(rewrite_generics_inner(
729 result.push_str(&try_opt!(rewrite_trait_ref(
740 result.push_str(&generics_str);
743 // Try to put the self type in a single line.
745 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
746 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
747 // If there is no where clause adapt budget for type formatting to take space and curly
748 // brace into account.
749 match context.config.item_brace_style() {
750 BraceStyle::AlwaysNextLine => 0,
756 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
757 // 1 = space before the type.
761 .checked_sub(used_space + 1)
763 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
764 if !self_ty_str.contains('\n') {
765 if trait_ref.is_some() {
766 result.push_str(" for ");
770 result.push_str(&self_ty_str);
775 // Couldn't fit the self type on a single line, put it on a new line.
777 // Add indentation of one additional tab.
778 let new_line_offset = offset.block_indent(context.config);
779 result.push_str(&new_line_offset.to_string(context.config));
780 if trait_ref.is_some() {
781 result.push_str("for ");
783 let budget = context.config.max_width() - last_line_width(&result);
784 let type_offset = match context.config.where_style() {
785 Style::Legacy => new_line_offset + trait_ref_overhead,
786 Style::Rfc => new_line_offset,
788 result.push_str(&*try_opt!(
789 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
797 fn rewrite_trait_ref(
798 context: &RewriteContext,
799 trait_ref: &ast::TraitRef,
805 ) -> Option<String> {
806 // 1 = space between generics and trait_ref
807 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
808 let shape = Shape::indented(offset + used_space, context.config);
809 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
810 if !(retry && trait_ref_str.contains('\n')) {
819 // We could not make enough space for trait_ref, so put it on new line.
821 let offset = offset.block_indent(context.config);
822 let shape = Shape::indented(offset, context.config);
823 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
827 &offset.to_string(context.config),
836 pub fn format_struct(
837 context: &RewriteContext,
840 vis: &ast::Visibility,
841 struct_def: &ast::VariantData,
842 generics: Option<&ast::Generics>,
845 one_line_width: Option<usize>,
846 ) -> Option<String> {
848 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
849 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
859 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
873 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
874 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
877 let mut result = String::with_capacity(128);
878 let header = format!(
880 format_visibility(&item.vis),
881 format_unsafety(unsafety),
885 result.push_str(&header);
887 let body_lo = context.codemap.span_after(item.span, "{");
889 let shape = Shape::indented(offset + last_line_width(&result), context.config);
890 let generics_str = try_opt!(rewrite_generics(
894 mk_sp(item.span.lo, body_lo),
896 result.push_str(&generics_str);
898 let trait_bound_str = try_opt!(rewrite_trait_bounds(
901 Shape::indented(offset, context.config),
903 // If the trait, generics, and trait bound cannot fit on the same line,
904 // put the trait bounds on an indented new line
905 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
906 context.config.comment_width()
909 let trait_indent = offset.block_only().block_indent(context.config);
910 result.push_str(&trait_indent.to_string(context.config));
912 result.push_str(&trait_bound_str);
914 let has_body = !trait_items.is_empty();
916 let where_density = if (context.config.where_density() == Density::Compressed &&
917 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
918 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
919 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
920 !result.contains('\n'))
927 let where_budget = try_opt!(
931 .checked_sub(last_line_width(&result))
933 let pos_before_where = if type_param_bounds.is_empty() {
934 generics.where_clause.span.lo
936 type_param_bounds[type_param_bounds.len() - 1].span().hi
938 let option = WhereClauseOption::snuggled(&generics_str);
939 let where_clause_str = try_opt!(rewrite_where_clause(
941 &generics.where_clause,
942 context.config.item_brace_style(),
943 Shape::legacy(where_budget, offset.block_only()),
950 // If the where clause cannot fit on the same line,
951 // put the where clause on a new line
952 if !where_clause_str.contains('\n') &&
953 last_line_width(&result) + where_clause_str.len() + offset.width() >
954 context.config.comment_width()
957 let width = offset.block_indent + context.config.tab_spaces() - 1;
958 let where_indent = Indent::new(0, width);
959 result.push_str(&where_indent.to_string(context.config));
961 result.push_str(&where_clause_str);
963 if generics.where_clause.predicates.is_empty() {
964 let item_snippet = context.snippet(item.span);
965 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
967 let comment_hi = body_lo - BytePos(1);
968 let comment_lo = item.span.lo + BytePos(lo as u32);
969 if comment_lo < comment_hi {
970 match recover_missing_comment_in_span(
971 mk_sp(comment_lo, comment_hi),
972 Shape::indented(offset, context.config),
974 last_line_width(&result),
976 Some(ref missing_comment) if !missing_comment.is_empty() => {
977 result.push_str(missing_comment);
985 match context.config.item_brace_style() {
986 _ if last_line_contains_single_line_comment(&result) => {
988 result.push_str(&offset.to_string(context.config));
990 BraceStyle::AlwaysNextLine => {
992 result.push_str(&offset.to_string(context.config));
994 BraceStyle::PreferSameLine => result.push(' '),
995 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
996 (!trait_items.is_empty() || result.contains('\n'))
999 result.push_str(&offset.to_string(context.config));
1006 let snippet = context.snippet(item.span);
1007 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1009 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1010 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1011 visitor.block_indent = offset.block_only().block_indent(context.config);
1012 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1014 for item in trait_items {
1015 visitor.visit_trait_item(item);
1018 visitor.format_missing(item.span.hi - BytePos(1));
1020 let inner_indent_str = visitor.block_indent.to_string(context.config);
1021 let outer_indent_str = offset.block_only().to_string(context.config);
1024 result.push_str(&inner_indent_str);
1025 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1027 result.push_str(&outer_indent_str);
1028 } else if result.contains('\n') {
1039 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1040 format!("{};", format_header(item_name, ident, vis))
1043 pub fn format_struct_struct(
1044 context: &RewriteContext,
1047 vis: &ast::Visibility,
1048 fields: &[ast::StructField],
1049 generics: Option<&ast::Generics>,
1052 one_line_width: Option<usize>,
1053 ) -> Option<String> {
1054 let mut result = String::with_capacity(1024);
1056 let header_str = format_header(item_name, ident, vis);
1057 result.push_str(&header_str);
1059 let body_lo = context.codemap.span_after(span, "{");
1061 let generics_str = match generics {
1062 Some(g) => try_opt!(format_generics(
1067 context.config.item_brace_style(),
1070 mk_sp(span.lo, body_lo),
1071 last_line_width(&result),
1074 // 3 = ` {}`, 2 = ` {`.
1075 let overhead = if fields.is_empty() { 3 } else { 2 };
1076 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1077 !fields.is_empty()) ||
1081 .checked_sub(result.len())
1082 .unwrap_or(0) < overhead
1084 format!("\n{}{{", offset.block_only().to_string(context.config))
1091 let overhead = if fields.is_empty() { 1 } else { 0 };
1092 let max_len = context
1095 .checked_sub(offset.width())
1097 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1099 result.push_str(&offset.to_string(context.config));
1100 result.push_str(&generics_str.trim_left());
1102 result.push_str(&generics_str);
1105 if fields.is_empty() {
1106 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1107 if snippet.trim().is_empty() {
1109 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1111 result.push_str(&snippet.trim_right());
1113 result.push_str(&offset.to_string(context.config));
1115 result.push_str(&snippet);
1118 return Some(result);
1122 let one_line_budget = context
1125 .checked_sub(result.len() + 3 + offset.width())
1127 let one_line_budget =
1128 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1130 let items_str = try_opt!(rewrite_with_alignment(
1133 Shape::indented(offset, context.config),
1134 mk_sp(body_lo, span.hi),
1138 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1139 Some(format!("{} {} }}", result, items_str))
1145 .block_indent(context.config)
1146 .to_string(context.config),
1148 offset.to_string(context.config)
1153 fn format_tuple_struct(
1154 context: &RewriteContext,
1157 vis: &ast::Visibility,
1158 fields: &[ast::StructField],
1159 generics: Option<&ast::Generics>,
1162 ) -> Option<String> {
1163 let mut result = String::with_capacity(1024);
1165 let header_str = format_header(item_name, ident, vis);
1166 result.push_str(&header_str);
1168 let body_lo = if fields.is_empty() {
1169 context.codemap.span_after(span, "(")
1173 let body_hi = if fields.is_empty() {
1174 context.codemap.span_after(span, ")")
1176 // This is a dirty hack to work around a missing `)` from the span of the last field.
1177 let last_arg_span = fields[fields.len() - 1].span;
1178 if context.snippet(last_arg_span).ends_with(")") {
1183 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1187 let where_clause_str = match generics {
1189 let budget = context.budget(last_line_width(&header_str));
1190 let shape = Shape::legacy(budget, offset);
1191 let g_span = mk_sp(span.lo, body_lo);
1192 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1193 result.push_str(&generics_str);
1195 let where_budget = context.budget(last_line_width(&result));
1196 let option = WhereClauseOption::new(true, false);
1197 try_opt!(rewrite_where_clause(
1199 &generics.where_clause,
1200 context.config.item_brace_style(),
1201 Shape::legacy(where_budget, offset.block_only()),
1202 Density::Compressed,
1209 None => "".to_owned(),
1212 if fields.is_empty() {
1214 let used_width = last_line_used_width(&result, offset.width()) + 3;
1215 if used_width > context.config.max_width() {
1217 result.push_str(&offset
1218 .block_indent(context.config)
1219 .to_string(context.config))
1222 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1223 if snippet.is_empty() {
1225 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1226 result.push_str(&snippet.trim_right());
1228 result.push_str(&offset.to_string(context.config));
1230 result.push_str(&snippet);
1235 let body = try_opt!(
1239 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1241 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1242 context.config.fn_call_width(),
1246 result.push_str(&body);
1249 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1250 (result.contains('\n') ||
1251 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1252 context.config.max_width())
1254 // We need to put the where clause on a new line, but we didn't
1255 // know that earlier, so the where clause will not be indented properly.
1257 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1258 .to_string(context.config));
1260 result.push_str(&where_clause_str);
1265 pub fn rewrite_type_alias(
1266 context: &RewriteContext,
1270 generics: &ast::Generics,
1271 vis: &ast::Visibility,
1273 ) -> Option<String> {
1274 let mut result = String::with_capacity(128);
1276 result.push_str(&format_visibility(vis));
1277 result.push_str("type ");
1278 result.push_str(&ident.to_string());
1281 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1282 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1283 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1284 result.push_str(&generics_str);
1286 let where_budget = try_opt!(
1290 .checked_sub(last_line_width(&result))
1292 let option = WhereClauseOption::snuggled(&result);
1293 let where_clause_str = try_opt!(rewrite_where_clause(
1295 &generics.where_clause,
1296 context.config.item_brace_style(),
1297 Shape::legacy(where_budget, indent),
1298 context.config.where_density(),
1304 result.push_str(&where_clause_str);
1305 if where_clause_str.is_empty() {
1306 result.push_str(" = ");
1308 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1311 let line_width = last_line_width(&result);
1312 // This checked_sub may fail as the extra space after '=' is not taken into account
1313 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1314 let budget = context
1317 .checked_sub(indent.width() + line_width + ";".len())
1319 let type_indent = indent + line_width;
1320 // Try to fit the type on the same line
1321 let ty_str = try_opt!(
1322 ty.rewrite(context, Shape::legacy(budget, type_indent))
1324 // The line was too short, try to put the type on the next line
1326 // Remove the space after '='
1328 let type_indent = indent.block_indent(context.config);
1330 result.push_str(&type_indent.to_string(context.config));
1331 let budget = try_opt!(
1335 .checked_sub(type_indent.width() + ";".len())
1337 ty.rewrite(context, Shape::legacy(budget, type_indent))
1340 result.push_str(&ty_str);
1341 result.push_str(";");
1345 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1347 if config.space_before_type_annotation() {
1352 if config.space_after_type_annotation_colon() {
1360 pub fn rewrite_struct_field_prefix(
1361 context: &RewriteContext,
1362 field: &ast::StructField,
1363 ) -> Option<String> {
1364 let vis = format_visibility(&field.vis);
1365 let type_annotation_spacing = type_annotation_spacing(context.config);
1366 Some(match field.ident {
1367 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1368 None => format!("{}", vis),
1372 fn rewrite_struct_field_type(
1373 context: &RewriteContext,
1374 last_line_width: usize,
1375 field: &ast::StructField,
1378 ) -> Option<String> {
1379 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1382 .rewrite(context, ty_shape)
1383 .map(|ty| format!("{}{}", spacing, ty))
1386 impl Rewrite for ast::StructField {
1387 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1388 rewrite_struct_field(context, self, shape, 0)
1392 pub fn rewrite_struct_field(
1393 context: &RewriteContext,
1394 field: &ast::StructField,
1396 lhs_max_width: usize,
1397 ) -> Option<String> {
1398 if contains_skip(&field.attrs) {
1399 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1400 return wrap_str(span, context.config.max_width(), shape);
1403 let type_annotation_spacing = type_annotation_spacing(context.config);
1404 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1406 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1407 let attrs_extendable = attrs_str.is_empty() ||
1408 (context.config.attributes_on_same_line_as_field() && is_attributes_extendable(&attrs_str));
1409 let missing_span = if field.attrs.is_empty() {
1410 mk_sp(field.span.lo, field.span.lo)
1412 mk_sp(field.attrs.last().unwrap().span.hi, field.span.lo)
1414 let mut spacing = String::from(if field.ident.is_some() {
1415 type_annotation_spacing.1
1419 // Try to put everything on a single line.
1420 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1428 let overhead = last_line_width(&attr_prefix);
1429 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1430 for _ in 0..lhs_offset {
1433 // In this extreme case we will be missing a space betweeen an attribute and a field.
1434 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1437 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1438 if let Some(ref ty) = ty_rewritten {
1439 if !ty.contains('\n') {
1440 return Some(attr_prefix + &ty);
1444 // We must use multiline.
1445 let last_line_width = last_line_width(&prefix);
1446 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1448 let type_offset = shape.indent.block_indent(context.config);
1449 let rewrite_type_in_next_line = || {
1452 .rewrite(context, Shape::indented(type_offset, context.config))
1455 let field_str = match ty_rewritten {
1456 // If we start from the next line and type fits in a single line, then do so.
1457 Some(ref ty) => match rewrite_type_in_next_line() {
1458 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1461 type_offset.to_string(&context.config),
1467 let ty = try_opt!(rewrite_type_in_next_line());
1471 type_offset.to_string(&context.config),
1476 combine_strs_with_missing_comments(
1486 pub fn rewrite_static(
1488 vis: &ast::Visibility,
1491 mutability: ast::Mutability,
1492 expr_opt: Option<&ptr::P<ast::Expr>>,
1495 context: &RewriteContext,
1496 ) -> Option<String> {
1497 let colon = colon_spaces(
1498 context.config.space_before_type_annotation(),
1499 context.config.space_after_type_annotation_colon(),
1501 let prefix = format!(
1503 format_visibility(vis),
1505 format_mutability(mutability),
1510 let ty_str = try_opt!(ty.rewrite(
1513 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1517 if let Some(expr) = expr_opt {
1518 let lhs = format!("{}{} =", prefix, ty_str);
1520 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1525 Shape::legacy(remaining_width, offset.block_only()),
1527 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1529 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1531 Some(format!("{}{};", prefix, ty_str))
1535 pub fn rewrite_associated_type(
1537 ty_opt: Option<&ptr::P<ast::Ty>>,
1538 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1539 context: &RewriteContext,
1541 ) -> Option<String> {
1542 let prefix = format!("type {}", ident);
1544 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1546 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1547 let bounds: &[_] = ty_param_bounds;
1548 let bound_str = try_opt!(
1551 .map(|ty_bound| ty_bound.rewrite(context, shape))
1552 .collect::<Option<Vec<_>>>()
1554 if bounds.len() > 0 {
1555 format!(": {}", join_bounds(context, shape, &bound_str))
1563 if let Some(ty) = ty_opt {
1564 let ty_str = try_opt!(ty.rewrite(
1567 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1568 indent.block_only(),
1571 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1573 Some(format!("{}{};", prefix, type_bounds_str))
1577 pub fn rewrite_associated_impl_type(
1579 defaultness: ast::Defaultness,
1580 ty_opt: Option<&ptr::P<ast::Ty>>,
1581 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1582 context: &RewriteContext,
1584 ) -> Option<String> {
1585 let result = try_opt!(rewrite_associated_type(
1588 ty_param_bounds_opt,
1594 ast::Defaultness::Default => Some(format!("default {}", result)),
1599 impl Rewrite for ast::FunctionRetTy {
1600 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1602 ast::FunctionRetTy::Default(_) => Some(String::new()),
1603 ast::FunctionRetTy::Ty(ref ty) => {
1604 let inner_width = try_opt!(shape.width.checked_sub(3));
1605 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1606 .map(|r| format!("-> {}", r))
1612 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1614 ast::TyKind::Infer => {
1615 let original = context.snippet(ty.span);
1622 impl Rewrite for ast::Arg {
1623 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1624 if is_named_arg(self) {
1625 let mut result = try_opt!(
1627 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1630 if !is_empty_infer(context, &*self.ty) {
1631 if context.config.space_before_type_annotation() {
1632 result.push_str(" ");
1634 result.push_str(":");
1635 if context.config.space_after_type_annotation_colon() {
1636 result.push_str(" ");
1638 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1639 let ty_str = try_opt!(self.ty.rewrite(
1641 Shape::legacy(max_width, shape.indent + result.len()),
1643 result.push_str(&ty_str);
1648 self.ty.rewrite(context, shape)
1653 fn rewrite_explicit_self(
1654 explicit_self: &ast::ExplicitSelf,
1656 context: &RewriteContext,
1657 ) -> Option<String> {
1658 match explicit_self.node {
1659 ast::SelfKind::Region(lt, m) => {
1660 let mut_str = format_mutability(m);
1663 let lifetime_str = try_opt!(l.rewrite(
1665 Shape::legacy(context.config.max_width(), Indent::empty()),
1667 Some(format!("&{} {}self", lifetime_str, mut_str))
1669 None => Some(format!("&{}self", mut_str)),
1672 ast::SelfKind::Explicit(ref ty, _) => {
1673 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1675 let mutability = explicit_self_mutability(&args[0]);
1676 let type_str = try_opt!(ty.rewrite(
1678 Shape::legacy(context.config.max_width(), Indent::empty()),
1683 format_mutability(mutability),
1687 ast::SelfKind::Value(_) => {
1688 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1690 let mutability = explicit_self_mutability(&args[0]);
1692 Some(format!("{}self", format_mutability(mutability)))
1697 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1698 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1699 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1700 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1707 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1708 if is_named_arg(arg) {
1715 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1717 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1718 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1719 _ => arg.ty.span.hi,
1723 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1724 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1725 ident.node != symbol::keywords::Invalid.ident()
1731 // Return type is (result, force_new_line_for_brace)
1733 context: &RewriteContext,
1737 generics: &ast::Generics,
1738 unsafety: ast::Unsafety,
1739 constness: ast::Constness,
1740 defaultness: ast::Defaultness,
1742 vis: &ast::Visibility,
1744 newline_brace: bool,
1747 ) -> Option<(String, bool)> {
1748 let mut force_new_line_for_brace = false;
1750 let where_clause = &generics.where_clause;
1752 let mut result = String::with_capacity(1024);
1753 // Vis defaultness constness unsafety abi.
1754 result.push_str(&*format_visibility(vis));
1755 result.push_str(format_defaultness(defaultness));
1756 result.push_str(format_constness(constness));
1757 result.push_str(format_unsafety(unsafety));
1758 if abi != abi::Abi::Rust {
1759 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1763 result.push_str("fn ");
1764 result.push_str(&ident.to_string());
1767 let overhead = if has_braces && !newline_brace {
1774 let used_width = last_line_used_width(&result, indent.width());
1775 let one_line_budget = context
1778 .checked_sub(used_width + overhead)
1781 width: one_line_budget,
1785 let g_span = mk_sp(span.lo, fd.output.span().lo);
1786 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1787 result.push_str(&generics_str);
1789 let snuggle_angle_bracket = generics_str
1792 .map_or(false, |l| l.trim_left().len() == 1);
1794 // Note that the width and indent don't really matter, we'll re-layout the
1795 // return type later anyway.
1796 let ret_str = try_opt!(
1798 .rewrite(&context, Shape::indented(indent, context.config))
1801 let multi_line_ret_str = ret_str.contains('\n');
1802 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1805 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1816 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1822 // Check if vertical layout was forced.
1823 if one_line_budget == 0 {
1824 if snuggle_angle_bracket {
1827 if context.config.fn_args_paren_newline() {
1829 result.push_str(&arg_indent.to_string(context.config));
1830 if context.config.fn_args_layout() == IndentStyle::Visual {
1831 arg_indent = arg_indent + 1; // extra space for `(`
1835 result.push_str("(");
1836 if context.config.fn_args_layout() == IndentStyle::Visual {
1838 result.push_str(&arg_indent.to_string(context.config));
1845 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1849 // A conservative estimation, to goal is to be over all parens in generics
1850 let args_start = generics
1853 .map_or(span.lo, |tp| end_typaram(tp));
1854 let args_end = if fd.inputs.is_empty() {
1855 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1857 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1858 context.codemap.span_after(last_span, ")")
1860 let args_span = mk_sp(
1861 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1864 let arg_str = try_opt!(rewrite_args(
1867 fd.get_self().as_ref(),
1874 generics_str.contains('\n'),
1877 let put_args_in_block = match context.config.fn_args_layout() {
1878 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1880 } && !fd.inputs.is_empty();
1882 let mut args_last_line_contains_comment = false;
1883 if put_args_in_block {
1884 arg_indent = indent.block_indent(context.config);
1886 result.push_str(&arg_indent.to_string(context.config));
1887 result.push_str(&arg_str);
1889 result.push_str(&indent.to_string(context.config));
1892 result.push_str(&arg_str);
1893 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1894 // Put the closing brace on the next line if it overflows the max width.
1896 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1899 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1902 // If the last line of args contains comment, we cannot put the closing paren
1903 // on the same line.
1907 .map_or(false, |last_line| last_line.contains("//"))
1909 args_last_line_contains_comment = true;
1911 result.push_str(&arg_indent.to_string(context.config));
1917 if let ast::FunctionRetTy::Ty(..) = fd.output {
1918 let ret_should_indent = match context.config.fn_args_layout() {
1919 // If our args are block layout then we surely must have space.
1920 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1921 _ if args_last_line_contains_comment => false,
1922 _ if result.contains('\n') || multi_line_ret_str => true,
1924 // If the return type would push over the max width, then put the return type on
1925 // a new line. With the +1 for the signature length an additional space between
1926 // the closing parenthesis of the argument and the arrow '->' is considered.
1927 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1929 // If there is no where clause, take into account the space after the return type
1931 if where_clause.predicates.is_empty() {
1935 sig_length > context.config.max_width()
1938 let ret_indent = if ret_should_indent {
1939 let indent = match context.config.fn_return_indent() {
1940 ReturnIndent::WithWhereClause => indent + 4,
1941 // Aligning with non-existent args looks silly.
1942 _ if arg_str.is_empty() => {
1943 force_new_line_for_brace = true;
1946 // FIXME: we might want to check that using the arg indent
1947 // doesn't blow our budget, and if it does, then fallback to
1948 // the where clause indent.
1953 result.push_str(&indent.to_string(context.config));
1957 Indent::new(indent.block_indent, last_line_width(&result))
1960 if multi_line_ret_str || ret_should_indent {
1961 // Now that we know the proper indent and width, we need to
1962 // re-layout the return type.
1963 let ret_str = try_opt!(
1965 .rewrite(context, Shape::indented(ret_indent, context.config))
1967 result.push_str(&ret_str);
1969 result.push_str(&ret_str);
1972 // Comment between return type and the end of the decl.
1973 let snippet_lo = fd.output.span().hi;
1974 if where_clause.predicates.is_empty() {
1975 let snippet_hi = span.hi;
1976 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1977 // Try to preserve the layout of the original snippet.
1978 let original_starts_with_newline = snippet
1980 .map_or(false, |i| snippet[i..].starts_with('\n'));
1981 let original_ends_with_newline = snippet
1982 .rfind(|c| c != ' ')
1983 .map_or(false, |i| snippet[i..].ends_with('\n'));
1984 let snippet = snippet.trim();
1985 if !snippet.is_empty() {
1986 result.push(if original_starts_with_newline {
1991 result.push_str(snippet);
1992 if original_ends_with_newline {
1993 force_new_line_for_brace = true;
1999 let should_compress_where = match context.config.where_density() {
2000 Density::Compressed => !result.contains('\n'),
2001 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2005 let pos_before_where = match fd.output {
2006 ast::FunctionRetTy::Default(..) => args_span.hi,
2007 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2010 if where_clause.predicates.len() == 1 && should_compress_where {
2011 let budget = context
2014 .checked_sub(last_line_used_width(&result, indent.width()))
2016 if let Some(where_clause_str) = rewrite_where_clause(
2019 context.config.fn_brace_style(),
2020 Shape::legacy(budget, indent),
2021 Density::Compressed,
2025 WhereClauseOption::compressed(),
2027 result.push_str(&where_clause_str);
2028 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2029 return Some((result, force_new_line_for_brace));
2033 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2034 let where_clause_str = try_opt!(rewrite_where_clause(
2037 context.config.fn_brace_style(),
2038 Shape::indented(indent, context.config),
2045 // If there are neither where clause nor return type, we may be missing comments between
2047 if where_clause_str.is_empty() {
2048 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2049 match recover_missing_comment_in_span(
2050 mk_sp(args_span.hi, ret_span.hi),
2053 last_line_width(&result),
2055 Some(ref missing_comment) if !missing_comment.is_empty() => {
2056 result.push_str(missing_comment);
2057 force_new_line_for_brace = true;
2064 result.push_str(&where_clause_str);
2066 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2067 return Some((result, force_new_line_for_brace));
2070 struct WhereClauseOption {
2071 suppress_comma: bool, // Force no trailing comma
2072 snuggle: bool, // Do not insert newline before `where`
2073 compress_where: bool, // Try single line where clause instead of vertical layout
2076 impl WhereClauseOption {
2077 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2079 suppress_comma: suppress_comma,
2081 compress_where: false,
2085 pub fn compressed() -> WhereClauseOption {
2087 suppress_comma: true,
2089 compress_where: true,
2093 pub fn snuggled(current: &str) -> WhereClauseOption {
2095 suppress_comma: false,
2096 snuggle: trimmed_last_line_width(current) == 1,
2097 compress_where: false,
2103 context: &RewriteContext,
2105 explicit_self: Option<&ast::ExplicitSelf>,
2106 one_line_budget: usize,
2107 multi_line_budget: usize,
2112 generics_str_contains_newline: bool,
2113 ) -> Option<String> {
2114 let mut arg_item_strs = try_opt!(
2117 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2119 .collect::<Option<Vec<_>>>()
2122 // Account for sugary self.
2123 // FIXME: the comment for the self argument is dropped. This is blocked
2124 // on rust issue #27522.
2125 let min_args = explicit_self
2126 .and_then(|explicit_self| {
2127 rewrite_explicit_self(explicit_self, args, context)
2129 .map_or(1, |self_str| {
2130 arg_item_strs[0] = self_str;
2134 // Comments between args.
2135 let mut arg_items = Vec::new();
2137 arg_items.push(ListItem::from_str(""));
2140 // FIXME(#21): if there are no args, there might still be a comment, but
2141 // without spans for the comment or parens, there is no chance of
2142 // getting it right. You also don't get to put a comment on self, unless
2144 if args.len() >= min_args || variadic {
2145 let comment_span_start = if min_args == 2 {
2146 let second_arg_start = if arg_has_pattern(&args[1]) {
2151 let reduced_span = mk_sp(span.lo, second_arg_start);
2153 context.codemap.span_after_last(reduced_span, ",")
2158 enum ArgumentKind<'a> {
2159 Regular(&'a ast::Arg),
2163 let variadic_arg = if variadic {
2164 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2165 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2166 Some(ArgumentKind::Variadic(variadic_start))
2171 let more_items = itemize_list(
2173 args[min_args - 1..]
2175 .map(ArgumentKind::Regular)
2176 .chain(variadic_arg),
2179 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2180 ArgumentKind::Variadic(start) => start,
2183 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2184 ArgumentKind::Variadic(start) => start + BytePos(3),
2187 ArgumentKind::Regular(..) => None,
2188 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2195 arg_items.extend(more_items);
2198 let fits_in_one_line = !generics_str_contains_newline &&
2199 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2201 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2202 item.item = Some(arg);
2205 let last_line_ends_with_comment = arg_items
2208 .and_then(|item| item.post_comment.as_ref())
2209 .map_or(false, |s| s.trim().starts_with("//"));
2211 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2212 IndentStyle::Block if fits_in_one_line => {
2213 (indent.block_indent(context.config), SeparatorTactic::Never)
2215 IndentStyle::Block => (
2216 indent.block_indent(context.config),
2217 context.config.trailing_comma(),
2219 IndentStyle::Visual if last_line_ends_with_comment => {
2220 (arg_indent, context.config.trailing_comma())
2222 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2225 let tactic = definitive_tactic(
2227 context.config.fn_args_density().to_list_tactic(),
2231 let budget = match tactic {
2232 DefinitiveListTactic::Horizontal => one_line_budget,
2233 _ => multi_line_budget,
2236 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2238 let fmt = ListFormatting {
2241 trailing_separator: if variadic {
2242 SeparatorTactic::Never
2246 separator_place: SeparatorPlace::Back,
2247 shape: Shape::legacy(budget, indent),
2248 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2249 preserve_newline: true,
2250 config: context.config,
2253 write_list(&arg_items, &fmt)
2256 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2257 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2258 ident.node != symbol::keywords::Invalid.ident()
2264 fn compute_budgets_for_args(
2265 context: &RewriteContext,
2269 newline_brace: bool,
2271 force_vertical_layout: bool,
2272 ) -> Option<((usize, usize, Indent))> {
2274 "compute_budgets_for_args {} {:?}, {}, {}",
2280 // Try keeping everything on the same line.
2281 if !result.contains('\n') && !force_vertical_layout {
2282 // 2 = `()`, 3 = `() `, space is before ret_string.
2283 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2284 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2294 let one_line_budget = context
2297 .checked_sub(used_space)
2300 if one_line_budget > 0 {
2302 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2303 IndentStyle::Block => {
2304 let indent = indent.block_indent(context.config);
2306 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2309 IndentStyle::Visual => {
2310 let indent = indent + result.len() + 1;
2311 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2313 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2318 return Some((one_line_budget, multi_line_budget, indent));
2322 // Didn't work. we must force vertical layout and put args on a newline.
2323 let new_indent = indent.block_indent(context.config);
2324 let used_space = match context.config.fn_args_layout() {
2326 IndentStyle::Block => new_indent.width() + 1,
2327 // Account for `)` and possibly ` {`.
2328 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2330 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2331 Some((0, max_space, new_indent))
2334 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2335 match (config.fn_brace_style(), config.where_density()) {
2336 (BraceStyle::AlwaysNextLine, _) => true,
2337 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2338 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2339 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2344 fn rewrite_generics(
2345 context: &RewriteContext,
2346 generics: &ast::Generics,
2349 ) -> Option<String> {
2350 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2351 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2352 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2353 rewrite_generics_inner(context, generics, g_shape, 0, span)
2357 fn rewrite_generics_inner(
2358 context: &RewriteContext,
2359 generics: &ast::Generics,
2361 one_line_width: usize,
2363 ) -> Option<String> {
2364 // FIXME: convert bounds to where clauses where they get too big or if
2365 // there is a where clause at all.
2366 let lifetimes: &[_] = &generics.lifetimes;
2367 let tys: &[_] = &generics.ty_params;
2368 if lifetimes.is_empty() && tys.is_empty() {
2369 return Some(String::new());
2372 // Strings for the generics.
2373 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2374 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2376 // Extract comments between generics.
2377 let lt_spans = lifetimes.iter().map(|l| {
2378 let hi = if l.bounds.is_empty() {
2381 l.bounds[l.bounds.len() - 1].span.hi
2383 mk_sp(l.lifetime.span.lo, hi)
2385 let ty_spans = tys.iter().map(|ty| ty.span());
2387 let items = itemize_list(
2389 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2393 // FIXME: don't clone
2394 |&(_, ref str)| str.clone(),
2395 context.codemap.span_after(span, "<"),
2399 format_generics_item_list(context, items, shape, one_line_width)
2402 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2403 match config.generics_indent() {
2404 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2405 IndentStyle::Block => {
2409 .block_indent(config.tab_spaces())
2410 .with_max_width(config)
2416 pub fn format_generics_item_list<I>(
2417 context: &RewriteContext,
2420 one_line_budget: usize,
2423 I: Iterator<Item = ListItem>,
2425 let item_vec = items.collect::<Vec<_>>();
2427 let tactic = definitive_tactic(
2429 ListTactic::HorizontalVertical,
2433 let fmt = ListFormatting {
2436 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2437 SeparatorTactic::Never
2439 context.config.trailing_comma()
2441 separator_place: SeparatorPlace::Back,
2443 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2444 preserve_newline: true,
2445 config: context.config,
2448 let list_str = try_opt!(write_list(&item_vec, &fmt));
2450 Some(wrap_generics_with_angle_brackets(
2457 pub fn wrap_generics_with_angle_brackets(
2458 context: &RewriteContext,
2460 list_offset: Indent,
2462 if context.config.generics_indent() == IndentStyle::Block &&
2463 (list_str.contains('\n') || list_str.ends_with(','))
2467 list_offset.to_string(context.config),
2470 .block_unindent(context.config)
2471 .to_string(context.config)
2473 } else if context.config.spaces_within_angle_brackets() {
2474 format!("< {} >", list_str)
2476 format!("<{}>", list_str)
2480 fn rewrite_trait_bounds(
2481 context: &RewriteContext,
2482 type_param_bounds: &ast::TyParamBounds,
2484 ) -> Option<String> {
2485 let bounds: &[_] = type_param_bounds;
2487 if bounds.is_empty() {
2488 return Some(String::new());
2490 let bound_str = try_opt!(
2493 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2494 .collect::<Option<Vec<_>>>()
2496 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2499 fn rewrite_where_clause_rfc_style(
2500 context: &RewriteContext,
2501 where_clause: &ast::WhereClause,
2504 span_end: Option<BytePos>,
2505 span_end_before_where: BytePos,
2506 where_clause_option: WhereClauseOption,
2507 ) -> Option<String> {
2508 let block_shape = shape.block().with_max_width(context.config);
2510 let (span_before, span_after) =
2511 missing_span_before_after_where(span_end_before_where, where_clause);
2512 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2519 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2522 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2525 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2526 // each clause on one line, trailing comma (except if suppress_comma)
2527 let span_start = where_clause.predicates[0].span().lo;
2528 // If we don't have the start of the next span, then use the end of the
2529 // predicates, but that means we miss comments.
2530 let len = where_clause.predicates.len();
2531 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2532 let span_end = span_end.unwrap_or(end_of_preds);
2533 let items = itemize_list(
2535 where_clause.predicates.iter(),
2537 |pred| pred.span().lo,
2538 |pred| pred.span().hi,
2539 |pred| pred.rewrite(context, block_shape),
2544 let comma_tactic = if where_clause_option.suppress_comma {
2545 SeparatorTactic::Never
2547 context.config.trailing_comma()
2550 let fmt = ListFormatting {
2551 tactic: DefinitiveListTactic::Vertical,
2553 trailing_separator: comma_tactic,
2554 separator_place: SeparatorPlace::Back,
2555 shape: clause_shape,
2556 ends_with_newline: true,
2557 preserve_newline: true,
2558 config: context.config,
2560 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2562 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2565 format!("\n{}", shape.indent.to_string(context.config))
2567 let newline_before_where = comment_separator(&comment_before, shape);
2568 let newline_after_where = comment_separator(&comment_after, clause_shape);
2571 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2572 comment_after.is_empty() && !preds_str.contains('\n') &&
2573 6 + preds_str.len() <= shape.width
2577 format!("\n{}", clause_shape.indent.to_string(context.config))
2580 "{}{}{}where{}{}{}{}",
2583 newline_before_where,
2584 newline_after_where,
2591 fn rewrite_where_clause(
2592 context: &RewriteContext,
2593 where_clause: &ast::WhereClause,
2594 brace_style: BraceStyle,
2598 span_end: Option<BytePos>,
2599 span_end_before_where: BytePos,
2600 where_clause_option: WhereClauseOption,
2601 ) -> Option<String> {
2602 if where_clause.predicates.is_empty() {
2603 return Some(String::new());
2606 if context.config.where_style() == Style::Rfc {
2607 return rewrite_where_clause_rfc_style(
2613 span_end_before_where,
2614 where_clause_option,
2618 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2620 let offset = match context.config.where_pred_indent() {
2621 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2622 // 6 = "where ".len()
2623 IndentStyle::Visual => shape.indent + extra_indent + 6,
2625 // FIXME: if where_pred_indent != Visual, then the budgets below might
2626 // be out by a char or two.
2628 let budget = context.config.max_width() - offset.width();
2629 let span_start = where_clause.predicates[0].span().lo;
2630 // If we don't have the start of the next span, then use the end of the
2631 // predicates, but that means we miss comments.
2632 let len = where_clause.predicates.len();
2633 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2634 let span_end = span_end.unwrap_or(end_of_preds);
2635 let items = itemize_list(
2637 where_clause.predicates.iter(),
2639 |pred| pred.span().lo,
2640 |pred| pred.span().hi,
2641 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2646 let item_vec = items.collect::<Vec<_>>();
2647 // FIXME: we don't need to collect here if the where_layout isn't
2648 // HorizontalVertical.
2649 let tactic = definitive_tactic(
2651 context.config.where_layout(),
2656 let mut comma_tactic = context.config.trailing_comma();
2657 // Kind of a hack because we don't usually have trailing commas in where clauses.
2658 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2659 comma_tactic = SeparatorTactic::Never;
2662 let fmt = ListFormatting {
2665 trailing_separator: comma_tactic,
2666 separator_place: SeparatorPlace::Back,
2667 shape: Shape::legacy(budget, offset),
2668 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2669 preserve_newline: true,
2670 config: context.config,
2672 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2674 let end_length = if terminator == "{" {
2675 // If the brace is on the next line we don't need to count it otherwise it needs two
2678 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2679 BraceStyle::PreferSameLine => 2,
2681 } else if terminator == "=" {
2686 if density == Density::Tall || preds_str.contains('\n') ||
2687 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2691 (shape.indent + extra_indent).to_string(context.config),
2695 Some(format!(" where {}", preds_str))
2699 fn missing_span_before_after_where(
2700 before_item_span_end: BytePos,
2701 where_clause: &ast::WhereClause,
2703 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo);
2705 let pos_after_where = where_clause.span.lo + BytePos(5);
2706 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2707 (missing_span_before, missing_span_after)
2710 fn rewrite_comments_before_after_where(
2711 context: &RewriteContext,
2712 span_before_where: Span,
2713 span_after_where: Span,
2715 ) -> Option<(String, String)> {
2716 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2717 let after_comment = try_opt!(rewrite_missing_comment(
2719 shape.block_indent(context.config.tab_spaces()),
2722 Some((before_comment, after_comment))
2725 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2726 format!("{}{}{}", format_visibility(vis), item_name, ident)
2730 context: &RewriteContext,
2731 generics: &ast::Generics,
2734 brace_style: BraceStyle,
2735 force_same_line_brace: bool,
2739 ) -> Option<String> {
2740 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2741 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2743 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2744 let budget = context
2747 .checked_sub(last_line_used_width(&result, offset.width()))
2749 let option = WhereClauseOption::snuggled(&result);
2750 let where_clause_str = try_opt!(rewrite_where_clause(
2752 &generics.where_clause,
2754 Shape::legacy(budget, offset.block_only()),
2761 result.push_str(&where_clause_str);
2762 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2763 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2765 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2766 brace_style != BraceStyle::AlwaysNextLine
2768 let total_used_width = last_line_used_width(&result, used_width);
2769 let remaining_budget = context
2772 .checked_sub(total_used_width)
2774 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2775 // and hence we take the closer into account as well for one line budget.
2776 // We assume that the closer has the same length as the opener.
2777 let overhead = if force_same_line_brace {
2778 1 + opener.len() + opener.len()
2782 let forbid_same_line_brace = overhead > remaining_budget;
2783 if !forbid_same_line_brace && same_line_brace {
2787 result.push_str(&offset.block_only().to_string(context.config));
2789 result.push_str(opener);
2794 impl Rewrite for ast::ForeignItem {
2795 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2796 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2797 // Drop semicolon or it will be interpreted as comment.
2798 // FIXME: this may be a faulty span from libsyntax.
2799 let span = mk_sp(self.span.lo, self.span.hi - BytePos(1));
2801 let item_str = try_opt!(match self.node {
2802 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2809 ast::Unsafety::Normal,
2810 ast::Constness::NotConst,
2811 ast::Defaultness::Final,
2812 // These are not actually rust functions,
2813 // but we format them as such.
2820 ).map(|(s, _)| format!("{};", s))
2822 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2823 // FIXME(#21): we're dropping potential comments in between the
2824 // function keywords here.
2825 let vis = format_visibility(&self.vis);
2826 let mut_str = if is_mutable { "mut " } else { "" };
2827 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2829 let shape = try_opt!(shape.sub_width(1));
2830 ty.rewrite(context, shape).map(|ty_str| {
2831 // 1 = space between prefix and type.
2832 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2835 let nested_indent = shape.indent.block_indent(context.config);
2836 format!("\n{}", nested_indent.to_string(context.config))
2838 format!("{}{}{};", prefix, sep, ty_str)
2843 let missing_span = if self.attrs.is_empty() {
2844 mk_sp(self.span.lo, self.span.lo)
2846 mk_sp(self.attrs[self.attrs.len() - 1].span.hi, self.span.lo)
2848 combine_strs_with_missing_comments(