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(
71 self.attrs.last().map(|a| a.span.hi()).unwrap(),
80 let pat_shape = try_opt!(shape.offset_left(4));
82 let pat_shape = try_opt!(pat_shape.sub_width(1));
83 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
84 result.push_str(&pat_str);
86 // String that is placed within the assignment pattern and expression.
88 let mut infix = String::with_capacity(32);
90 if let Some(ref ty) = self.ty {
91 let separator = type_annotation_separator(context.config);
92 let indent = shape.indent + last_line_width(&result) + separator.len();
94 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
95 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
97 infix.push_str(separator);
98 infix.push_str(&rewrite);
101 if self.init.is_some() {
102 infix.push_str(" =");
108 result.push_str(&infix);
110 if let Some(ref ex) = self.init {
111 // 1 = trailing semicolon;
112 let nested_shape = try_opt!(shape.sub_width(1));
114 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
122 // TODO convert to using rewrite style rather than visitor
123 // TODO format modules in this style
126 keyword: &'static str,
128 vis: Option<&'a ast::Visibility>,
129 body: Vec<BodyElement<'a>>,
134 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
135 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
138 format!("extern {}", fm.abi)
146 .map(|i| BodyElement::ForeignItem(i))
153 enum BodyElement<'a> {
154 // Stmt(&'a ast::Stmt),
155 // Field(&'a ast::Field),
156 // Variant(&'a ast::Variant),
157 // Item(&'a ast::Item),
158 ForeignItem(&'a ast::ForeignItem),
161 impl<'a> FmtVisitor<'a> {
162 fn format_item(&mut self, item: Item) {
163 self.buffer.push_str(&item.abi);
164 self.buffer.push_str(" ");
166 let snippet = self.snippet(item.span);
167 let brace_pos = snippet.find_uncommented("{").unwrap();
169 self.buffer.push_str("{");
170 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
171 // FIXME: this skips comments between the extern keyword and the opening
173 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
174 self.block_indent = self.block_indent.block_indent(self.config);
176 if item.body.is_empty() {
177 self.format_missing_no_indent(item.span.hi() - BytePos(1));
178 self.block_indent = self.block_indent.block_unindent(self.config);
181 .push_str(&self.block_indent.to_string(self.config));
183 for item in &item.body {
184 self.format_body_element(item);
187 self.block_indent = self.block_indent.block_unindent(self.config);
188 self.format_missing_with_indent(item.span.hi() - BytePos(1));
192 self.buffer.push_str("}");
193 self.last_pos = item.span.hi();
196 fn format_body_element(&mut self, element: &BodyElement) {
198 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
202 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
203 let item = Item::from_foreign_mod(fm, span, self.config);
204 self.format_item(item);
208 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
209 let rewrite = item.rewrite(&self.get_context(), self.shape());
210 self.push_rewrite(item.span(), rewrite);
211 self.last_pos = item.span.hi();
219 generics: &ast::Generics,
220 unsafety: ast::Unsafety,
221 constness: ast::Constness,
222 defaultness: ast::Defaultness,
224 vis: &ast::Visibility,
227 ) -> Option<String> {
228 let context = self.get_context();
230 let block_snippet = self.snippet(mk_sp(block.span.lo(), block.span.hi()));
231 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
232 !context.config.fn_empty_single_line();
233 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
235 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
252 if force_newline_brace {
253 newline_brace = true;
254 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
255 !result.contains('\n')
257 newline_brace = false;
260 // Prepare for the function body by possibly adding a newline and
262 // FIXME we'll miss anything between the end of the signature and the
263 // start of the body, but we need more spans from the compiler to solve
267 result.push_str(&indent.to_string(self.config));
272 self.single_line_fn(&result, block).or_else(|| Some(result))
275 pub fn rewrite_required_fn(
279 sig: &ast::MethodSig,
281 ) -> Option<String> {
282 // Drop semicolon or it will be interpreted as comment.
283 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
284 let context = self.get_context();
286 let (mut result, _) = try_opt!(rewrite_fn_base(
294 ast::Defaultness::Final,
296 &ast::Visibility::Inherited,
303 // Re-attach semicolon
309 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
310 if fn_str.contains('\n') {
314 let codemap = self.get_context().codemap;
316 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
317 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
319 return Some(format!("{}{{}}", fn_str));
322 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
324 if let Some(ref stmt) = block.stmts.first() {
325 match stmt_expr(stmt) {
327 let suffix = if semicolon_for_expr(&self.get_context(), e) {
333 format_expr(&e, ExprType::Statement, &self.get_context(), self.shape())
335 .or_else(|| Some(self.snippet(e.span)))
337 None => stmt.rewrite(&self.get_context(), self.shape()),
344 if let Some(res) = rewrite {
345 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
346 if !res.contains('\n') && width <= self.config.max_width() {
347 return Some(format!("{}{{ {} }}", fn_str, res));
358 vis: &ast::Visibility,
359 enum_def: &ast::EnumDef,
360 generics: &ast::Generics,
363 let enum_header = format_header("enum ", ident, vis);
364 self.buffer.push_str(&enum_header);
366 let enum_snippet = self.snippet(span);
367 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
368 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
369 let generics_str = format_generics(
374 self.config.item_brace_style(),
375 enum_def.variants.is_empty(),
377 mk_sp(span.lo(), body_start),
378 last_line_width(&enum_header),
380 self.buffer.push_str(&generics_str);
382 self.last_pos = body_start;
384 self.block_indent = self.block_indent.block_indent(self.config);
385 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
387 Some(ref body_str) => self.buffer.push_str(body_str),
388 None => if contains_comment(&enum_snippet[brace_pos..]) {
389 self.format_missing_no_indent(span.hi() - BytePos(1))
391 self.format_missing(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()
541 .checked_sub(last_line_width(&result))
544 let option = WhereClauseOption::snuggled(&ref_and_type);
545 let where_clause_str = try_opt!(rewrite_where_clause(
547 &generics.where_clause,
548 context.config.item_brace_style(),
549 Shape::legacy(where_budget, offset.block_only()),
550 context.config.where_density(),
557 // If there is no where clause, we may have missing comments between the trait name and
558 // the opening brace.
559 if generics.where_clause.predicates.is_empty() {
560 if let Some(hi) = where_span_end {
561 match recover_missing_comment_in_span(
562 mk_sp(self_ty.span.hi(), hi),
563 Shape::indented(offset, context.config),
565 last_line_width(&result),
567 Some(ref missing_comment) if !missing_comment.is_empty() => {
568 result.push_str(missing_comment);
575 if try_opt!(is_impl_single_line(
582 result.push_str(&where_clause_str);
583 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
584 result.push_str(&format!("{}{{{}}}", &sep, &sep));
586 result.push_str(" {}");
591 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
593 let width = offset.block_indent + context.config.tab_spaces() - 1;
594 let where_indent = Indent::new(0, width);
595 result.push_str(&where_indent.to_string(context.config));
597 result.push_str(&where_clause_str);
599 match context.config.item_brace_style() {
600 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
601 BraceStyle::AlwaysNextLine => result.push_str(&sep),
602 BraceStyle::PreferSameLine => result.push(' '),
603 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
604 result.push_str(&sep);
612 let snippet = context.snippet(item.span);
613 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
615 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
616 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
617 visitor.block_indent = offset.block_only().block_indent(context.config);
618 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
620 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
622 visitor.visit_impl_item(item);
625 visitor.format_missing(item.span.hi() - BytePos(1));
627 let inner_indent_str = visitor.block_indent.to_string(context.config);
628 let outer_indent_str = offset.block_only().to_string(context.config);
631 result.push_str(&inner_indent_str);
632 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
634 result.push_str(&outer_indent_str);
637 if result.chars().last().unwrap() == '{' {
638 result.push_str(&sep);
648 fn is_impl_single_line(
649 context: &RewriteContext,
652 where_clause_str: &str,
655 let snippet = context.snippet(item.span);
656 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
659 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n') &&
660 result.len() + where_clause_str.len() <= context.config.max_width() &&
661 !contains_comment(&snippet[open_pos..]),
665 fn format_impl_ref_and_type(
666 context: &RewriteContext,
669 ) -> Option<String> {
670 if let ast::ItemKind::Impl(
680 let mut result = String::with_capacity(128);
682 result.push_str(&format_visibility(&item.vis));
683 result.push_str(&format_defaultness(defaultness));
684 result.push_str(format_unsafety(unsafety));
685 result.push_str("impl");
687 let lo = context.codemap.span_after(item.span, "impl");
688 let hi = match *trait_ref {
689 Some(ref tr) => tr.path.span.lo(),
690 None => self_ty.span.lo(),
692 let shape = try_opt!(generics_shape_from_config(
694 Shape::indented(offset + last_line_width(&result), context.config),
697 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
698 let generics_str = try_opt!(rewrite_generics_inner(
706 let polarity_str = if polarity == ast::ImplPolarity::Negative {
712 if let Some(ref trait_ref) = *trait_ref {
713 let result_len = result.len();
714 if let Some(trait_ref_str) = rewrite_trait_ref(
723 result.push_str(&trait_ref_str);
725 let generics_str = try_opt!(rewrite_generics_inner(
732 result.push_str(&try_opt!(rewrite_trait_ref(
743 result.push_str(&generics_str);
746 // Try to put the self type in a single line.
748 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
749 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
750 // If there is no where clause adapt budget for type formatting to take space and curly
751 // brace into account.
752 match context.config.item_brace_style() {
753 BraceStyle::AlwaysNextLine => 0,
759 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
760 // 1 = space before the type.
764 .checked_sub(used_space + 1)
766 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
767 if !self_ty_str.contains('\n') {
768 if trait_ref.is_some() {
769 result.push_str(" for ");
773 result.push_str(&self_ty_str);
778 // Couldn't fit the self type on a single line, put it on a new line.
780 // Add indentation of one additional tab.
781 let new_line_offset = offset.block_indent(context.config);
782 result.push_str(&new_line_offset.to_string(context.config));
783 if trait_ref.is_some() {
784 result.push_str("for ");
786 let budget = context.config.max_width() - last_line_width(&result);
787 let type_offset = match context.config.where_style() {
788 Style::Legacy => new_line_offset + trait_ref_overhead,
789 Style::Rfc => new_line_offset,
791 result.push_str(&*try_opt!(
792 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
800 fn rewrite_trait_ref(
801 context: &RewriteContext,
802 trait_ref: &ast::TraitRef,
808 ) -> Option<String> {
809 // 1 = space between generics and trait_ref
810 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
811 let shape = Shape::indented(offset + used_space, context.config);
812 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
813 if !(retry && trait_ref_str.contains('\n')) {
822 // We could not make enough space for trait_ref, so put it on new line.
824 let offset = offset.block_indent(context.config);
825 let shape = Shape::indented(offset, context.config);
826 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
830 &offset.to_string(context.config),
839 pub fn format_struct(
840 context: &RewriteContext,
843 vis: &ast::Visibility,
844 struct_def: &ast::VariantData,
845 generics: Option<&ast::Generics>,
848 one_line_width: Option<usize>,
849 ) -> Option<String> {
851 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
852 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
862 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
876 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
877 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
880 let mut result = String::with_capacity(128);
881 let header = format!(
883 format_visibility(&item.vis),
884 format_unsafety(unsafety),
888 result.push_str(&header);
890 let body_lo = context.codemap.span_after(item.span, "{");
892 let shape = Shape::indented(offset + last_line_width(&result), context.config);
893 let generics_str = try_opt!(rewrite_generics(
897 mk_sp(item.span.lo(), body_lo),
899 result.push_str(&generics_str);
901 let trait_bound_str = try_opt!(rewrite_trait_bounds(
904 Shape::indented(offset, context.config),
906 // If the trait, generics, and trait bound cannot fit on the same line,
907 // put the trait bounds on an indented new line
908 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
909 context.config.comment_width()
912 let trait_indent = offset.block_only().block_indent(context.config);
913 result.push_str(&trait_indent.to_string(context.config));
915 result.push_str(&trait_bound_str);
917 let has_body = !trait_items.is_empty();
919 let where_density = if (context.config.where_density() == Density::Compressed &&
920 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
921 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
922 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
923 !result.contains('\n'))
930 let where_budget = try_opt!(
934 .checked_sub(last_line_width(&result))
936 let pos_before_where = if type_param_bounds.is_empty() {
937 generics.where_clause.span.lo()
939 type_param_bounds[type_param_bounds.len() - 1].span().hi()
941 let option = WhereClauseOption::snuggled(&generics_str);
942 let where_clause_str = try_opt!(rewrite_where_clause(
944 &generics.where_clause,
945 context.config.item_brace_style(),
946 Shape::legacy(where_budget, offset.block_only()),
953 // If the where clause cannot fit on the same line,
954 // put the where clause on a new line
955 if !where_clause_str.contains('\n') &&
956 last_line_width(&result) + where_clause_str.len() + offset.width() >
957 context.config.comment_width()
960 let width = offset.block_indent + context.config.tab_spaces() - 1;
961 let where_indent = Indent::new(0, width);
962 result.push_str(&where_indent.to_string(context.config));
964 result.push_str(&where_clause_str);
966 if generics.where_clause.predicates.is_empty() {
967 let item_snippet = context.snippet(item.span);
968 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
970 let comment_hi = body_lo - BytePos(1);
971 let comment_lo = item.span.lo() + BytePos(lo as u32);
972 if comment_lo < comment_hi {
973 match recover_missing_comment_in_span(
974 mk_sp(comment_lo, comment_hi),
975 Shape::indented(offset, context.config),
977 last_line_width(&result),
979 Some(ref missing_comment) if !missing_comment.is_empty() => {
980 result.push_str(missing_comment);
988 match context.config.item_brace_style() {
989 _ if last_line_contains_single_line_comment(&result) => {
991 result.push_str(&offset.to_string(context.config));
993 BraceStyle::AlwaysNextLine => {
995 result.push_str(&offset.to_string(context.config));
997 BraceStyle::PreferSameLine => result.push(' '),
998 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
999 (!trait_items.is_empty() || result.contains('\n'))
1002 result.push_str(&offset.to_string(context.config));
1009 let snippet = context.snippet(item.span);
1010 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1012 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1013 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1014 visitor.block_indent = offset.block_only().block_indent(context.config);
1015 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1017 for item in trait_items {
1018 visitor.visit_trait_item(item);
1021 visitor.format_missing(item.span.hi() - BytePos(1));
1023 let inner_indent_str = visitor.block_indent.to_string(context.config);
1024 let outer_indent_str = offset.block_only().to_string(context.config);
1027 result.push_str(&inner_indent_str);
1028 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1030 result.push_str(&outer_indent_str);
1031 } else if result.contains('\n') {
1042 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1043 format!("{};", format_header(item_name, ident, vis))
1046 pub fn format_struct_struct(
1047 context: &RewriteContext,
1050 vis: &ast::Visibility,
1051 fields: &[ast::StructField],
1052 generics: Option<&ast::Generics>,
1055 one_line_width: Option<usize>,
1056 ) -> Option<String> {
1057 let mut result = String::with_capacity(1024);
1059 let header_str = format_header(item_name, ident, vis);
1060 result.push_str(&header_str);
1062 let body_lo = context.codemap.span_after(span, "{");
1064 let generics_str = match generics {
1065 Some(g) => try_opt!(format_generics(
1070 context.config.item_brace_style(),
1073 mk_sp(span.lo(), body_lo),
1074 last_line_width(&result),
1077 // 3 = ` {}`, 2 = ` {`.
1078 let overhead = if fields.is_empty() { 3 } else { 2 };
1079 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1080 !fields.is_empty()) ||
1084 .checked_sub(result.len())
1085 .unwrap_or(0) < overhead
1087 format!("\n{}{{", offset.block_only().to_string(context.config))
1094 let overhead = if fields.is_empty() { 1 } else { 0 };
1095 let max_len = context
1098 .checked_sub(offset.width())
1100 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1102 result.push_str(&offset.to_string(context.config));
1103 result.push_str(&generics_str.trim_left());
1105 result.push_str(&generics_str);
1108 if fields.is_empty() {
1109 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1110 if snippet.trim().is_empty() {
1112 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1114 result.push_str(&snippet.trim_right());
1116 result.push_str(&offset.to_string(context.config));
1118 result.push_str(&snippet);
1121 return Some(result);
1125 let one_line_budget = context
1128 .checked_sub(result.len() + 3 + offset.width())
1130 let one_line_budget =
1131 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1133 let items_str = try_opt!(rewrite_with_alignment(
1136 Shape::indented(offset, context.config),
1137 mk_sp(body_lo, span.hi()),
1141 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1142 Some(format!("{} {} }}", result, items_str))
1148 .block_indent(context.config)
1149 .to_string(context.config),
1151 offset.to_string(context.config)
1156 fn format_tuple_struct(
1157 context: &RewriteContext,
1160 vis: &ast::Visibility,
1161 fields: &[ast::StructField],
1162 generics: Option<&ast::Generics>,
1165 ) -> Option<String> {
1166 let mut result = String::with_capacity(1024);
1168 let header_str = format_header(item_name, ident, vis);
1169 result.push_str(&header_str);
1171 let body_lo = if fields.is_empty() {
1172 context.codemap.span_after(span, "(")
1176 let body_hi = if fields.is_empty() {
1177 context.codemap.span_after(span, ")")
1179 // This is a dirty hack to work around a missing `)` from the span of the last field.
1180 let last_arg_span = fields[fields.len() - 1].span;
1181 if context.snippet(last_arg_span).ends_with(")") {
1186 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1190 let where_clause_str = match generics {
1192 let budget = context.budget(last_line_width(&header_str));
1193 let shape = Shape::legacy(budget, offset);
1194 let g_span = mk_sp(span.lo(), body_lo);
1195 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1196 result.push_str(&generics_str);
1198 let where_budget = context.budget(last_line_width(&result));
1199 let option = WhereClauseOption::new(true, false);
1200 try_opt!(rewrite_where_clause(
1202 &generics.where_clause,
1203 context.config.item_brace_style(),
1204 Shape::legacy(where_budget, offset.block_only()),
1205 Density::Compressed,
1212 None => "".to_owned(),
1215 if fields.is_empty() {
1217 let used_width = last_line_used_width(&result, offset.width()) + 3;
1218 if used_width > context.config.max_width() {
1220 result.push_str(&offset
1221 .block_indent(context.config)
1222 .to_string(context.config))
1225 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1226 if snippet.is_empty() {
1228 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1229 result.push_str(&snippet.trim_right());
1231 result.push_str(&offset.to_string(context.config));
1233 result.push_str(&snippet);
1238 let body = try_opt!(
1242 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1244 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1245 context.config.fn_call_width(),
1249 result.push_str(&body);
1252 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1253 (result.contains('\n') ||
1254 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1255 context.config.max_width())
1257 // We need to put the where clause on a new line, but we didn't
1258 // know that earlier, so the where clause will not be indented properly.
1260 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1261 .to_string(context.config));
1263 result.push_str(&where_clause_str);
1268 pub fn rewrite_type_alias(
1269 context: &RewriteContext,
1273 generics: &ast::Generics,
1274 vis: &ast::Visibility,
1276 ) -> Option<String> {
1277 let mut result = String::with_capacity(128);
1279 result.push_str(&format_visibility(vis));
1280 result.push_str("type ");
1281 result.push_str(&ident.to_string());
1284 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1285 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1286 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1287 result.push_str(&generics_str);
1289 let where_budget = try_opt!(
1293 .checked_sub(last_line_width(&result))
1295 let option = WhereClauseOption::snuggled(&result);
1296 let where_clause_str = try_opt!(rewrite_where_clause(
1298 &generics.where_clause,
1299 context.config.item_brace_style(),
1300 Shape::legacy(where_budget, indent),
1301 context.config.where_density(),
1307 result.push_str(&where_clause_str);
1308 if where_clause_str.is_empty() {
1309 result.push_str(" = ");
1311 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1314 let line_width = last_line_width(&result);
1315 // This checked_sub may fail as the extra space after '=' is not taken into account
1316 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1317 let budget = context
1320 .checked_sub(indent.width() + line_width + ";".len())
1322 let type_indent = indent + line_width;
1323 // Try to fit the type on the same line
1324 let ty_str = try_opt!(
1325 ty.rewrite(context, Shape::legacy(budget, type_indent))
1327 // The line was too short, try to put the type on the next line
1329 // Remove the space after '='
1331 let type_indent = indent.block_indent(context.config);
1333 result.push_str(&type_indent.to_string(context.config));
1334 let budget = try_opt!(
1338 .checked_sub(type_indent.width() + ";".len())
1340 ty.rewrite(context, Shape::legacy(budget, type_indent))
1343 result.push_str(&ty_str);
1344 result.push_str(";");
1348 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1350 if config.space_before_type_annotation() {
1355 if config.space_after_type_annotation_colon() {
1363 pub fn rewrite_struct_field_prefix(
1364 context: &RewriteContext,
1365 field: &ast::StructField,
1366 ) -> Option<String> {
1367 let vis = format_visibility(&field.vis);
1368 let type_annotation_spacing = type_annotation_spacing(context.config);
1369 Some(match field.ident {
1370 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1371 None => format!("{}", vis),
1375 fn rewrite_struct_field_type(
1376 context: &RewriteContext,
1377 last_line_width: usize,
1378 field: &ast::StructField,
1381 ) -> Option<String> {
1382 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1385 .rewrite(context, ty_shape)
1386 .map(|ty| format!("{}{}", spacing, ty))
1389 impl Rewrite for ast::StructField {
1390 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1391 rewrite_struct_field(context, self, shape, 0)
1395 pub fn rewrite_struct_field(
1396 context: &RewriteContext,
1397 field: &ast::StructField,
1399 lhs_max_width: usize,
1400 ) -> Option<String> {
1401 if contains_skip(&field.attrs) {
1402 let span = context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi()));
1403 return wrap_str(span, context.config.max_width(), shape);
1406 let type_annotation_spacing = type_annotation_spacing(context.config);
1407 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1409 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1410 let attrs_extendable = attrs_str.is_empty() ||
1411 (context.config.attributes_on_same_line_as_field() && is_attributes_extendable(&attrs_str));
1412 let missing_span = if field.attrs.is_empty() {
1413 mk_sp(field.span.lo(), field.span.lo())
1415 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1417 let mut spacing = String::from(if field.ident.is_some() {
1418 type_annotation_spacing.1
1422 // Try to put everything on a single line.
1423 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1431 let overhead = last_line_width(&attr_prefix);
1432 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1433 for _ in 0..lhs_offset {
1436 // In this extreme case we will be missing a space betweeen an attribute and a field.
1437 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1440 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1441 if let Some(ref ty) = ty_rewritten {
1442 if !ty.contains('\n') {
1443 return Some(attr_prefix + &ty);
1447 // We must use multiline.
1448 let last_line_width = last_line_width(&prefix);
1449 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1451 let type_offset = shape.indent.block_indent(context.config);
1452 let rewrite_type_in_next_line = || {
1455 .rewrite(context, Shape::indented(type_offset, context.config))
1458 let field_str = match ty_rewritten {
1459 // If we start from the next line and type fits in a single line, then do so.
1460 Some(ref ty) => match rewrite_type_in_next_line() {
1461 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1464 type_offset.to_string(&context.config),
1470 let ty = try_opt!(rewrite_type_in_next_line());
1474 type_offset.to_string(&context.config),
1479 combine_strs_with_missing_comments(
1489 pub fn rewrite_static(
1491 vis: &ast::Visibility,
1494 mutability: ast::Mutability,
1495 expr_opt: Option<&ptr::P<ast::Expr>>,
1498 context: &RewriteContext,
1499 ) -> Option<String> {
1500 let colon = colon_spaces(
1501 context.config.space_before_type_annotation(),
1502 context.config.space_after_type_annotation_colon(),
1504 let prefix = format!(
1506 format_visibility(vis),
1508 format_mutability(mutability),
1513 let ty_str = try_opt!(ty.rewrite(
1516 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1520 if let Some(expr) = expr_opt {
1521 let lhs = format!("{}{} =", prefix, ty_str);
1523 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1528 Shape::legacy(remaining_width, offset.block_only()),
1530 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1532 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1534 Some(format!("{}{};", prefix, ty_str))
1538 pub fn rewrite_associated_type(
1540 ty_opt: Option<&ptr::P<ast::Ty>>,
1541 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1542 context: &RewriteContext,
1544 ) -> Option<String> {
1545 let prefix = format!("type {}", ident);
1547 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1549 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1550 let bounds: &[_] = ty_param_bounds;
1551 let bound_str = try_opt!(
1554 .map(|ty_bound| ty_bound.rewrite(context, shape))
1555 .collect::<Option<Vec<_>>>()
1557 if bounds.len() > 0 {
1558 format!(": {}", join_bounds(context, shape, &bound_str))
1566 if let Some(ty) = ty_opt {
1567 let ty_str = try_opt!(ty.rewrite(
1570 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1571 indent.block_only(),
1574 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1576 Some(format!("{}{};", prefix, type_bounds_str))
1580 pub fn rewrite_associated_impl_type(
1582 defaultness: ast::Defaultness,
1583 ty_opt: Option<&ptr::P<ast::Ty>>,
1584 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1585 context: &RewriteContext,
1587 ) -> Option<String> {
1588 let result = try_opt!(rewrite_associated_type(
1591 ty_param_bounds_opt,
1597 ast::Defaultness::Default => Some(format!("default {}", result)),
1602 impl Rewrite for ast::FunctionRetTy {
1603 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1605 ast::FunctionRetTy::Default(_) => Some(String::new()),
1606 ast::FunctionRetTy::Ty(ref ty) => {
1607 let inner_width = try_opt!(shape.width.checked_sub(3));
1608 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1609 .map(|r| format!("-> {}", r))
1615 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1617 ast::TyKind::Infer => {
1618 let original = context.snippet(ty.span);
1625 impl Rewrite for ast::Arg {
1626 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1627 if is_named_arg(self) {
1628 let mut result = try_opt!(
1630 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1633 if !is_empty_infer(context, &*self.ty) {
1634 if context.config.space_before_type_annotation() {
1635 result.push_str(" ");
1637 result.push_str(":");
1638 if context.config.space_after_type_annotation_colon() {
1639 result.push_str(" ");
1641 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1642 let ty_str = try_opt!(self.ty.rewrite(
1644 Shape::legacy(max_width, shape.indent + result.len()),
1646 result.push_str(&ty_str);
1651 self.ty.rewrite(context, shape)
1656 fn rewrite_explicit_self(
1657 explicit_self: &ast::ExplicitSelf,
1659 context: &RewriteContext,
1660 ) -> Option<String> {
1661 match explicit_self.node {
1662 ast::SelfKind::Region(lt, m) => {
1663 let mut_str = format_mutability(m);
1666 let lifetime_str = try_opt!(l.rewrite(
1668 Shape::legacy(context.config.max_width(), Indent::empty()),
1670 Some(format!("&{} {}self", lifetime_str, mut_str))
1672 None => Some(format!("&{}self", mut_str)),
1675 ast::SelfKind::Explicit(ref ty, _) => {
1676 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1678 let mutability = explicit_self_mutability(&args[0]);
1679 let type_str = try_opt!(ty.rewrite(
1681 Shape::legacy(context.config.max_width(), Indent::empty()),
1686 format_mutability(mutability),
1690 ast::SelfKind::Value(_) => {
1691 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1693 let mutability = explicit_self_mutability(&args[0]);
1695 Some(format!("{}self", format_mutability(mutability)))
1700 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1701 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1702 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1703 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1710 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1711 if is_named_arg(arg) {
1718 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1720 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1721 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1722 _ => arg.ty.span.hi(),
1726 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1727 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1728 ident.node != symbol::keywords::Invalid.ident()
1734 // Return type is (result, force_new_line_for_brace)
1736 context: &RewriteContext,
1740 generics: &ast::Generics,
1741 unsafety: ast::Unsafety,
1742 constness: ast::Constness,
1743 defaultness: ast::Defaultness,
1745 vis: &ast::Visibility,
1747 newline_brace: bool,
1750 ) -> Option<(String, bool)> {
1751 let mut force_new_line_for_brace = false;
1753 let where_clause = &generics.where_clause;
1755 let mut result = String::with_capacity(1024);
1756 // Vis defaultness constness unsafety abi.
1757 result.push_str(&*format_visibility(vis));
1758 result.push_str(format_defaultness(defaultness));
1759 result.push_str(format_constness(constness));
1760 result.push_str(format_unsafety(unsafety));
1761 if abi != abi::Abi::Rust {
1762 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1766 result.push_str("fn ");
1767 result.push_str(&ident.to_string());
1770 let overhead = if has_braces && !newline_brace {
1777 let used_width = last_line_used_width(&result, indent.width());
1778 let one_line_budget = context
1781 .checked_sub(used_width + overhead)
1784 width: one_line_budget,
1788 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1789 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1790 result.push_str(&generics_str);
1792 let snuggle_angle_bracket = generics_str
1795 .map_or(false, |l| l.trim_left().len() == 1);
1797 // Note that the width and indent don't really matter, we'll re-layout the
1798 // return type later anyway.
1799 let ret_str = try_opt!(
1801 .rewrite(&context, Shape::indented(indent, context.config))
1804 let multi_line_ret_str = ret_str.contains('\n');
1805 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1808 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1819 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1825 // Check if vertical layout was forced.
1826 if one_line_budget == 0 {
1827 if snuggle_angle_bracket {
1830 if context.config.fn_args_paren_newline() {
1832 result.push_str(&arg_indent.to_string(context.config));
1833 if context.config.fn_args_layout() == IndentStyle::Visual {
1834 arg_indent = arg_indent + 1; // extra space for `(`
1838 result.push_str("(");
1839 if context.config.fn_args_layout() == IndentStyle::Visual {
1841 result.push_str(&arg_indent.to_string(context.config));
1848 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1852 // A conservative estimation, to goal is to be over all parens in generics
1853 let args_start = generics
1856 .map_or(span.lo(), |tp| end_typaram(tp));
1857 let args_end = if fd.inputs.is_empty() {
1860 .span_after(mk_sp(args_start, span.hi()), ")")
1862 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1863 context.codemap.span_after(last_span, ")")
1865 let args_span = mk_sp(
1868 .span_after(mk_sp(args_start, span.hi()), "("),
1871 let arg_str = try_opt!(rewrite_args(
1874 fd.get_self().as_ref(),
1881 generics_str.contains('\n'),
1884 let put_args_in_block = match context.config.fn_args_layout() {
1885 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1887 } && !fd.inputs.is_empty();
1889 let mut args_last_line_contains_comment = false;
1890 if put_args_in_block {
1891 arg_indent = indent.block_indent(context.config);
1893 result.push_str(&arg_indent.to_string(context.config));
1894 result.push_str(&arg_str);
1896 result.push_str(&indent.to_string(context.config));
1899 result.push_str(&arg_str);
1900 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1901 // Put the closing brace on the next line if it overflows the max width.
1903 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1906 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1909 // If the last line of args contains comment, we cannot put the closing paren
1910 // on the same line.
1914 .map_or(false, |last_line| last_line.contains("//"))
1916 args_last_line_contains_comment = true;
1918 result.push_str(&arg_indent.to_string(context.config));
1924 if let ast::FunctionRetTy::Ty(..) = fd.output {
1925 let ret_should_indent = match context.config.fn_args_layout() {
1926 // If our args are block layout then we surely must have space.
1927 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1928 _ if args_last_line_contains_comment => false,
1929 _ if result.contains('\n') || multi_line_ret_str => true,
1931 // If the return type would push over the max width, then put the return type on
1932 // a new line. With the +1 for the signature length an additional space between
1933 // the closing parenthesis of the argument and the arrow '->' is considered.
1934 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1936 // If there is no where clause, take into account the space after the return type
1938 if where_clause.predicates.is_empty() {
1942 sig_length > context.config.max_width()
1945 let ret_indent = if ret_should_indent {
1946 let indent = match context.config.fn_return_indent() {
1947 ReturnIndent::WithWhereClause => indent + 4,
1948 // Aligning with non-existent args looks silly.
1949 _ if arg_str.is_empty() => {
1950 force_new_line_for_brace = true;
1953 // FIXME: we might want to check that using the arg indent
1954 // doesn't blow our budget, and if it does, then fallback to
1955 // the where clause indent.
1960 result.push_str(&indent.to_string(context.config));
1964 Indent::new(indent.block_indent, last_line_width(&result))
1967 if multi_line_ret_str || ret_should_indent {
1968 // Now that we know the proper indent and width, we need to
1969 // re-layout the return type.
1970 let ret_str = try_opt!(
1972 .rewrite(context, Shape::indented(ret_indent, context.config))
1974 result.push_str(&ret_str);
1976 result.push_str(&ret_str);
1979 // Comment between return type and the end of the decl.
1980 let snippet_lo = fd.output.span().hi();
1981 if where_clause.predicates.is_empty() {
1982 let snippet_hi = span.hi();
1983 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1984 // Try to preserve the layout of the original snippet.
1985 let original_starts_with_newline = snippet
1987 .map_or(false, |i| snippet[i..].starts_with('\n'));
1988 let original_ends_with_newline = snippet
1989 .rfind(|c| c != ' ')
1990 .map_or(false, |i| snippet[i..].ends_with('\n'));
1991 let snippet = snippet.trim();
1992 if !snippet.is_empty() {
1993 result.push(if original_starts_with_newline {
1998 result.push_str(snippet);
1999 if original_ends_with_newline {
2000 force_new_line_for_brace = true;
2006 let should_compress_where = match context.config.where_density() {
2007 Density::Compressed => !result.contains('\n'),
2008 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2012 let pos_before_where = match fd.output {
2013 ast::FunctionRetTy::Default(..) => args_span.hi(),
2014 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2017 if where_clause.predicates.len() == 1 && should_compress_where {
2018 let budget = context
2021 .checked_sub(last_line_used_width(&result, indent.width()))
2023 if let Some(where_clause_str) = rewrite_where_clause(
2026 context.config.fn_brace_style(),
2027 Shape::legacy(budget, indent),
2028 Density::Compressed,
2032 WhereClauseOption::compressed(),
2034 result.push_str(&where_clause_str);
2035 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2036 return Some((result, force_new_line_for_brace));
2040 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2041 let where_clause_str = try_opt!(rewrite_where_clause(
2044 context.config.fn_brace_style(),
2045 Shape::indented(indent, context.config),
2052 // If there are neither where clause nor return type, we may be missing comments between
2054 if where_clause_str.is_empty() {
2055 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2056 match recover_missing_comment_in_span(
2057 mk_sp(args_span.hi(), ret_span.hi()),
2060 last_line_width(&result),
2062 Some(ref missing_comment) if !missing_comment.is_empty() => {
2063 result.push_str(missing_comment);
2064 force_new_line_for_brace = true;
2071 result.push_str(&where_clause_str);
2073 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2074 return Some((result, force_new_line_for_brace));
2077 struct WhereClauseOption {
2078 suppress_comma: bool, // Force no trailing comma
2079 snuggle: bool, // Do not insert newline before `where`
2080 compress_where: bool, // Try single line where clause instead of vertical layout
2083 impl WhereClauseOption {
2084 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2086 suppress_comma: suppress_comma,
2088 compress_where: false,
2092 pub fn compressed() -> WhereClauseOption {
2094 suppress_comma: true,
2096 compress_where: true,
2100 pub fn snuggled(current: &str) -> WhereClauseOption {
2102 suppress_comma: false,
2103 snuggle: trimmed_last_line_width(current) == 1,
2104 compress_where: false,
2110 context: &RewriteContext,
2112 explicit_self: Option<&ast::ExplicitSelf>,
2113 one_line_budget: usize,
2114 multi_line_budget: usize,
2119 generics_str_contains_newline: bool,
2120 ) -> Option<String> {
2121 let mut arg_item_strs = try_opt!(
2124 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2126 .collect::<Option<Vec<_>>>()
2129 // Account for sugary self.
2130 // FIXME: the comment for the self argument is dropped. This is blocked
2131 // on rust issue #27522.
2132 let min_args = explicit_self
2133 .and_then(|explicit_self| {
2134 rewrite_explicit_self(explicit_self, args, context)
2136 .map_or(1, |self_str| {
2137 arg_item_strs[0] = self_str;
2141 // Comments between args.
2142 let mut arg_items = Vec::new();
2144 arg_items.push(ListItem::from_str(""));
2147 // FIXME(#21): if there are no args, there might still be a comment, but
2148 // without spans for the comment or parens, there is no chance of
2149 // getting it right. You also don't get to put a comment on self, unless
2151 if args.len() >= min_args || variadic {
2152 let comment_span_start = if min_args == 2 {
2153 let second_arg_start = if arg_has_pattern(&args[1]) {
2154 args[1].pat.span.lo()
2156 args[1].ty.span.lo()
2158 let reduced_span = mk_sp(span.lo(), second_arg_start);
2160 context.codemap.span_after_last(reduced_span, ",")
2165 enum ArgumentKind<'a> {
2166 Regular(&'a ast::Arg),
2170 let variadic_arg = if variadic {
2171 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2172 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2173 Some(ArgumentKind::Variadic(variadic_start))
2178 let more_items = itemize_list(
2180 args[min_args - 1..]
2182 .map(ArgumentKind::Regular)
2183 .chain(variadic_arg),
2186 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2187 ArgumentKind::Variadic(start) => start,
2190 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2191 ArgumentKind::Variadic(start) => start + BytePos(3),
2194 ArgumentKind::Regular(..) => None,
2195 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2202 arg_items.extend(more_items);
2205 let fits_in_one_line = !generics_str_contains_newline &&
2206 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2208 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2209 item.item = Some(arg);
2212 let last_line_ends_with_comment = arg_items
2215 .and_then(|item| item.post_comment.as_ref())
2216 .map_or(false, |s| s.trim().starts_with("//"));
2218 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2219 IndentStyle::Block if fits_in_one_line => {
2220 (indent.block_indent(context.config), SeparatorTactic::Never)
2222 IndentStyle::Block => (
2223 indent.block_indent(context.config),
2224 context.config.trailing_comma(),
2226 IndentStyle::Visual if last_line_ends_with_comment => {
2227 (arg_indent, context.config.trailing_comma())
2229 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2232 let tactic = definitive_tactic(
2234 context.config.fn_args_density().to_list_tactic(),
2238 let budget = match tactic {
2239 DefinitiveListTactic::Horizontal => one_line_budget,
2240 _ => multi_line_budget,
2243 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2245 let fmt = ListFormatting {
2248 trailing_separator: if variadic {
2249 SeparatorTactic::Never
2253 separator_place: SeparatorPlace::Back,
2254 shape: Shape::legacy(budget, indent),
2255 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2256 preserve_newline: true,
2257 config: context.config,
2260 write_list(&arg_items, &fmt)
2263 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2264 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2265 ident.node != symbol::keywords::Invalid.ident()
2271 fn compute_budgets_for_args(
2272 context: &RewriteContext,
2276 newline_brace: bool,
2278 force_vertical_layout: bool,
2279 ) -> Option<((usize, usize, Indent))> {
2281 "compute_budgets_for_args {} {:?}, {}, {}",
2287 // Try keeping everything on the same line.
2288 if !result.contains('\n') && !force_vertical_layout {
2289 // 2 = `()`, 3 = `() `, space is before ret_string.
2290 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2291 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2301 let one_line_budget = context
2304 .checked_sub(used_space)
2307 if one_line_budget > 0 {
2309 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2310 IndentStyle::Block => {
2311 let indent = indent.block_indent(context.config);
2313 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2316 IndentStyle::Visual => {
2317 let indent = indent + result.len() + 1;
2318 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2320 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2325 return Some((one_line_budget, multi_line_budget, indent));
2329 // Didn't work. we must force vertical layout and put args on a newline.
2330 let new_indent = indent.block_indent(context.config);
2331 let used_space = match context.config.fn_args_layout() {
2333 IndentStyle::Block => new_indent.width() + 1,
2334 // Account for `)` and possibly ` {`.
2335 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2337 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2338 Some((0, max_space, new_indent))
2341 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2342 match (config.fn_brace_style(), config.where_density()) {
2343 (BraceStyle::AlwaysNextLine, _) => true,
2344 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2345 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2346 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2351 fn rewrite_generics(
2352 context: &RewriteContext,
2353 generics: &ast::Generics,
2356 ) -> Option<String> {
2357 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2358 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2359 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2360 rewrite_generics_inner(context, generics, g_shape, 0, span)
2364 fn rewrite_generics_inner(
2365 context: &RewriteContext,
2366 generics: &ast::Generics,
2368 one_line_width: usize,
2370 ) -> Option<String> {
2371 // FIXME: convert bounds to where clauses where they get too big or if
2372 // there is a where clause at all.
2373 let lifetimes: &[_] = &generics.lifetimes;
2374 let tys: &[_] = &generics.ty_params;
2375 if lifetimes.is_empty() && tys.is_empty() {
2376 return Some(String::new());
2379 // Strings for the generics.
2380 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2381 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2383 // Extract comments between generics.
2384 let lt_spans = lifetimes.iter().map(|l| {
2385 let hi = if l.bounds.is_empty() {
2386 l.lifetime.span.hi()
2388 l.bounds[l.bounds.len() - 1].span.hi()
2390 mk_sp(l.lifetime.span.lo(), hi)
2392 let ty_spans = tys.iter().map(|ty| ty.span());
2394 let items = itemize_list(
2396 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2400 // FIXME: don't clone
2401 |&(_, ref str)| str.clone(),
2402 context.codemap.span_after(span, "<"),
2406 format_generics_item_list(context, items, shape, one_line_width)
2409 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2410 match config.generics_indent() {
2411 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2412 IndentStyle::Block => {
2416 .block_indent(config.tab_spaces())
2417 .with_max_width(config)
2423 pub fn format_generics_item_list<I>(
2424 context: &RewriteContext,
2427 one_line_budget: usize,
2430 I: Iterator<Item = ListItem>,
2432 let item_vec = items.collect::<Vec<_>>();
2434 let tactic = definitive_tactic(
2436 ListTactic::HorizontalVertical,
2440 let fmt = ListFormatting {
2443 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2444 SeparatorTactic::Never
2446 context.config.trailing_comma()
2448 separator_place: SeparatorPlace::Back,
2450 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2451 preserve_newline: true,
2452 config: context.config,
2455 let list_str = try_opt!(write_list(&item_vec, &fmt));
2457 Some(wrap_generics_with_angle_brackets(
2464 pub fn wrap_generics_with_angle_brackets(
2465 context: &RewriteContext,
2467 list_offset: Indent,
2469 if context.config.generics_indent() == IndentStyle::Block &&
2470 (list_str.contains('\n') || list_str.ends_with(','))
2474 list_offset.to_string(context.config),
2477 .block_unindent(context.config)
2478 .to_string(context.config)
2480 } else if context.config.spaces_within_angle_brackets() {
2481 format!("< {} >", list_str)
2483 format!("<{}>", list_str)
2487 fn rewrite_trait_bounds(
2488 context: &RewriteContext,
2489 type_param_bounds: &ast::TyParamBounds,
2491 ) -> Option<String> {
2492 let bounds: &[_] = type_param_bounds;
2494 if bounds.is_empty() {
2495 return Some(String::new());
2497 let bound_str = try_opt!(
2500 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2501 .collect::<Option<Vec<_>>>()
2503 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2506 fn rewrite_where_clause_rfc_style(
2507 context: &RewriteContext,
2508 where_clause: &ast::WhereClause,
2511 span_end: Option<BytePos>,
2512 span_end_before_where: BytePos,
2513 where_clause_option: WhereClauseOption,
2514 ) -> Option<String> {
2515 let block_shape = shape.block().with_max_width(context.config);
2517 let (span_before, span_after) =
2518 missing_span_before_after_where(span_end_before_where, where_clause);
2519 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2526 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2529 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2532 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2533 // each clause on one line, trailing comma (except if suppress_comma)
2534 let span_start = where_clause.predicates[0].span().lo();
2535 // If we don't have the start of the next span, then use the end of the
2536 // predicates, but that means we miss comments.
2537 let len = where_clause.predicates.len();
2538 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2539 let span_end = span_end.unwrap_or(end_of_preds);
2540 let items = itemize_list(
2542 where_clause.predicates.iter(),
2544 |pred| pred.span().lo(),
2545 |pred| pred.span().hi(),
2546 |pred| pred.rewrite(context, block_shape),
2551 let comma_tactic = if where_clause_option.suppress_comma {
2552 SeparatorTactic::Never
2554 context.config.trailing_comma()
2557 let fmt = ListFormatting {
2558 tactic: DefinitiveListTactic::Vertical,
2560 trailing_separator: comma_tactic,
2561 separator_place: SeparatorPlace::Back,
2562 shape: clause_shape,
2563 ends_with_newline: true,
2564 preserve_newline: true,
2565 config: context.config,
2567 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2569 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2572 format!("\n{}", shape.indent.to_string(context.config))
2574 let newline_before_where = comment_separator(&comment_before, shape);
2575 let newline_after_where = comment_separator(&comment_after, clause_shape);
2578 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2579 comment_after.is_empty() && !preds_str.contains('\n') &&
2580 6 + preds_str.len() <= shape.width
2584 format!("\n{}", clause_shape.indent.to_string(context.config))
2587 "{}{}{}where{}{}{}{}",
2590 newline_before_where,
2591 newline_after_where,
2598 fn rewrite_where_clause(
2599 context: &RewriteContext,
2600 where_clause: &ast::WhereClause,
2601 brace_style: BraceStyle,
2605 span_end: Option<BytePos>,
2606 span_end_before_where: BytePos,
2607 where_clause_option: WhereClauseOption,
2608 ) -> Option<String> {
2609 if where_clause.predicates.is_empty() {
2610 return Some(String::new());
2613 if context.config.where_style() == Style::Rfc {
2614 return rewrite_where_clause_rfc_style(
2620 span_end_before_where,
2621 where_clause_option,
2625 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2627 let offset = match context.config.where_pred_indent() {
2628 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2629 // 6 = "where ".len()
2630 IndentStyle::Visual => shape.indent + extra_indent + 6,
2632 // FIXME: if where_pred_indent != Visual, then the budgets below might
2633 // be out by a char or two.
2635 let budget = context.config.max_width() - offset.width();
2636 let span_start = where_clause.predicates[0].span().lo();
2637 // If we don't have the start of the next span, then use the end of the
2638 // predicates, but that means we miss comments.
2639 let len = where_clause.predicates.len();
2640 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2641 let span_end = span_end.unwrap_or(end_of_preds);
2642 let items = itemize_list(
2644 where_clause.predicates.iter(),
2646 |pred| pred.span().lo(),
2647 |pred| pred.span().hi(),
2648 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2653 let item_vec = items.collect::<Vec<_>>();
2654 // FIXME: we don't need to collect here if the where_layout isn't
2655 // HorizontalVertical.
2656 let tactic = definitive_tactic(
2658 context.config.where_layout(),
2663 let mut comma_tactic = context.config.trailing_comma();
2664 // Kind of a hack because we don't usually have trailing commas in where clauses.
2665 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2666 comma_tactic = SeparatorTactic::Never;
2669 let fmt = ListFormatting {
2672 trailing_separator: comma_tactic,
2673 separator_place: SeparatorPlace::Back,
2674 shape: Shape::legacy(budget, offset),
2675 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2676 preserve_newline: true,
2677 config: context.config,
2679 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2681 let end_length = if terminator == "{" {
2682 // If the brace is on the next line we don't need to count it otherwise it needs two
2685 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2686 BraceStyle::PreferSameLine => 2,
2688 } else if terminator == "=" {
2693 if density == Density::Tall || preds_str.contains('\n') ||
2694 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2698 (shape.indent + extra_indent).to_string(context.config),
2702 Some(format!(" where {}", preds_str))
2706 fn missing_span_before_after_where(
2707 before_item_span_end: BytePos,
2708 where_clause: &ast::WhereClause,
2710 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2712 let pos_after_where = where_clause.span.lo() + BytePos(5);
2713 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2714 (missing_span_before, missing_span_after)
2717 fn rewrite_comments_before_after_where(
2718 context: &RewriteContext,
2719 span_before_where: Span,
2720 span_after_where: Span,
2722 ) -> Option<(String, String)> {
2723 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2724 let after_comment = try_opt!(rewrite_missing_comment(
2726 shape.block_indent(context.config.tab_spaces()),
2729 Some((before_comment, after_comment))
2732 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2733 format!("{}{}{}", format_visibility(vis), item_name, ident)
2737 context: &RewriteContext,
2738 generics: &ast::Generics,
2741 brace_style: BraceStyle,
2742 force_same_line_brace: bool,
2746 ) -> Option<String> {
2747 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2748 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2750 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2751 let budget = context
2754 .checked_sub(last_line_used_width(&result, offset.width()))
2756 let option = WhereClauseOption::snuggled(&result);
2757 let where_clause_str = try_opt!(rewrite_where_clause(
2759 &generics.where_clause,
2761 Shape::legacy(budget, offset.block_only()),
2768 result.push_str(&where_clause_str);
2769 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2770 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2772 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2773 brace_style != BraceStyle::AlwaysNextLine
2775 let total_used_width = last_line_used_width(&result, used_width);
2776 let remaining_budget = context
2779 .checked_sub(total_used_width)
2781 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2782 // and hence we take the closer into account as well for one line budget.
2783 // We assume that the closer has the same length as the opener.
2784 let overhead = if force_same_line_brace {
2785 1 + opener.len() + opener.len()
2789 let forbid_same_line_brace = overhead > remaining_budget;
2790 if !forbid_same_line_brace && same_line_brace {
2794 result.push_str(&offset.block_only().to_string(context.config));
2796 result.push_str(opener);
2801 impl Rewrite for ast::ForeignItem {
2802 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2803 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2804 // Drop semicolon or it will be interpreted as comment.
2805 // FIXME: this may be a faulty span from libsyntax.
2806 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2808 let item_str = try_opt!(match self.node {
2809 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2816 ast::Unsafety::Normal,
2817 ast::Constness::NotConst,
2818 ast::Defaultness::Final,
2819 // These are not actually rust functions,
2820 // but we format them as such.
2827 ).map(|(s, _)| format!("{};", s))
2829 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2830 // FIXME(#21): we're dropping potential comments in between the
2831 // function keywords here.
2832 let vis = format_visibility(&self.vis);
2833 let mut_str = if is_mutable { "mut " } else { "" };
2834 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2836 let shape = try_opt!(shape.sub_width(1));
2837 ty.rewrite(context, shape).map(|ty_str| {
2838 // 1 = space between prefix and type.
2839 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2842 let nested_indent = shape.indent.block_indent(context.config);
2843 format!("\n{}", nested_indent.to_string(context.config))
2845 format!("{}{}{};", prefix, sep, ty_str)
2850 let missing_span = if self.attrs.is_empty() {
2851 mk_sp(self.span.lo(), self.span.lo())
2853 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2855 combine_strs_with_missing_comments(