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(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(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))
392 self.block_indent = self.block_indent.block_unindent(self.config);
394 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
396 .push_str(&self.block_indent.to_string(self.config));
398 self.buffer.push_str("}");
399 self.last_pos = span.hi();
402 // Format the body of an enum definition
403 fn format_variant_list(
405 enum_def: &ast::EnumDef,
408 ) -> Option<String> {
409 if enum_def.variants.is_empty() {
412 let mut result = String::with_capacity(1024);
414 let indentation = self.block_indent.to_string(self.config);
415 result.push_str(&indentation);
417 let items = itemize_list(
419 enum_def.variants.iter(),
421 |f| if !f.node.attrs.is_empty() {
422 f.node.attrs[0].span.lo()
427 |f| self.format_variant(f),
433 let shape = self.shape().sub_width(2).unwrap();
434 let fmt = ListFormatting {
435 tactic: DefinitiveListTactic::Vertical,
437 trailing_separator: self.config.trailing_comma(),
438 separator_place: SeparatorPlace::Back,
440 ends_with_newline: true,
441 preserve_newline: true,
445 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
446 result.push_str(&list);
451 // Variant of an enum.
452 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
453 if contains_skip(&field.node.attrs) {
454 let lo = field.node.attrs[0].span.lo();
455 let span = mk_sp(lo, field.span.hi());
456 return Some(self.snippet(span));
459 let context = self.get_context();
460 let indent = self.block_indent;
461 let shape = self.shape();
462 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
467 .map_or(field.span.lo(), |attr| attr.span.hi());
468 let span = mk_sp(lo, field.span.lo());
470 let variant_body = match field.node.data {
471 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
472 // FIXME: Should limit the width, as we have a trailing comma
473 try_opt!(format_struct(
477 &ast::Visibility::Inherited,
482 Some(self.config.struct_variant_width()),
485 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
487 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
488 if one_line_width <= shape.width {
489 format!("{} = {}", field.node.name, self.snippet(expr.span))
496 .block_indent(self.config)
497 .to_string(self.config),
498 self.snippet(expr.span)
502 String::from(field.node.name.to_string())
506 let attrs_extendable = attrs_str.is_empty() ||
507 (context.config.attributes_on_same_line_as_variant() &&
508 is_attributes_extendable(&attrs_str));
509 combine_strs_with_missing_comments(
521 context: &RewriteContext,
524 where_span_end: Option<BytePos>,
525 ) -> Option<String> {
526 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
527 let mut result = String::with_capacity(128);
528 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
529 let indent_str = offset.to_string(context.config);
530 let sep = format!("\n{}", &indent_str);
531 result.push_str(&ref_and_type);
533 let where_budget = if result.contains('\n') {
534 context.config.max_width()
536 context.budget(last_line_width(&result))
538 let option = WhereClauseOption::snuggled(&ref_and_type);
539 let where_clause_str = try_opt!(rewrite_where_clause(
541 &generics.where_clause,
542 context.config.item_brace_style(),
543 Shape::legacy(where_budget, offset.block_only()),
544 context.config.where_density(),
551 // If there is no where clause, we may have missing comments between the trait name and
552 // the opening brace.
553 if generics.where_clause.predicates.is_empty() {
554 if let Some(hi) = where_span_end {
555 match recover_missing_comment_in_span(
556 mk_sp(self_ty.span.hi(), hi),
557 Shape::indented(offset, context.config),
559 last_line_width(&result),
561 Some(ref missing_comment) if !missing_comment.is_empty() => {
562 result.push_str(missing_comment);
569 if try_opt!(is_impl_single_line(
576 result.push_str(&where_clause_str);
577 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
578 result.push_str(&format!("{}{{{}}}", &sep, &sep));
580 result.push_str(" {}");
585 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
587 let width = offset.block_indent + context.config.tab_spaces() - 1;
588 let where_indent = Indent::new(0, width);
589 result.push_str(&where_indent.to_string(context.config));
591 result.push_str(&where_clause_str);
593 match context.config.item_brace_style() {
594 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
595 BraceStyle::AlwaysNextLine => result.push_str(&sep),
596 BraceStyle::PreferSameLine => result.push(' '),
597 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
598 result.push_str(&sep);
606 let snippet = context.snippet(item.span);
607 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
609 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
610 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
611 visitor.block_indent = offset.block_only().block_indent(context.config);
612 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
614 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
616 visitor.visit_impl_item(item);
619 visitor.format_missing(item.span.hi() - BytePos(1));
621 let inner_indent_str = visitor.block_indent.to_string(context.config);
622 let outer_indent_str = offset.block_only().to_string(context.config);
625 result.push_str(&inner_indent_str);
626 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
628 result.push_str(&outer_indent_str);
631 if result.chars().last().unwrap() == '{' {
632 result.push_str(&sep);
642 fn is_impl_single_line(
643 context: &RewriteContext,
646 where_clause_str: &str,
649 let snippet = context.snippet(item.span);
650 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
653 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n') &&
654 result.len() + where_clause_str.len() <= context.config.max_width() &&
655 !contains_comment(&snippet[open_pos..]),
659 fn format_impl_ref_and_type(
660 context: &RewriteContext,
663 ) -> Option<String> {
664 if let ast::ItemKind::Impl(
674 let mut result = String::with_capacity(128);
676 result.push_str(&format_visibility(&item.vis));
677 result.push_str(format_defaultness(defaultness));
678 result.push_str(format_unsafety(unsafety));
679 result.push_str("impl");
681 let lo = context.codemap.span_after(item.span, "impl");
682 let hi = match *trait_ref {
683 Some(ref tr) => tr.path.span.lo(),
684 None => self_ty.span.lo(),
686 let shape = try_opt!(generics_shape_from_config(
688 Shape::indented(offset + last_line_width(&result), context.config),
691 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
692 let generics_str = try_opt!(rewrite_generics_inner(
700 let polarity_str = if polarity == ast::ImplPolarity::Negative {
706 if let Some(ref trait_ref) = *trait_ref {
707 let result_len = result.len();
708 if let Some(trait_ref_str) = rewrite_trait_ref(
717 result.push_str(&trait_ref_str);
719 let generics_str = try_opt!(rewrite_generics_inner(
726 result.push_str(&try_opt!(rewrite_trait_ref(
737 result.push_str(&generics_str);
740 // Try to put the self type in a single line.
742 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
743 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
744 // If there is no where clause adapt budget for type formatting to take space and curly
745 // brace into account.
746 match context.config.item_brace_style() {
747 BraceStyle::AlwaysNextLine => 0,
753 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
754 // 1 = space before the type.
755 let budget = context.budget(used_space + 1);
756 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
757 if !self_ty_str.contains('\n') {
758 if trait_ref.is_some() {
759 result.push_str(" for ");
763 result.push_str(&self_ty_str);
768 // Couldn't fit the self type on a single line, put it on a new line.
770 // Add indentation of one additional tab.
771 let new_line_offset = offset.block_indent(context.config);
772 result.push_str(&new_line_offset.to_string(context.config));
773 if trait_ref.is_some() {
774 result.push_str("for ");
776 let budget = context.budget(last_line_width(&result));
777 let type_offset = match context.config.where_style() {
778 Style::Legacy => new_line_offset + trait_ref_overhead,
779 Style::Rfc => new_line_offset,
781 result.push_str(&*try_opt!(
782 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
790 fn rewrite_trait_ref(
791 context: &RewriteContext,
792 trait_ref: &ast::TraitRef,
798 ) -> Option<String> {
799 // 1 = space between generics and trait_ref
800 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
801 let shape = Shape::indented(offset + used_space, context.config);
802 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
803 if !(retry && trait_ref_str.contains('\n')) {
812 // We could not make enough space for trait_ref, so put it on new line.
814 let offset = offset.block_indent(context.config);
815 let shape = Shape::indented(offset, context.config);
816 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
820 &offset.to_string(context.config),
829 pub fn format_struct(
830 context: &RewriteContext,
833 vis: &ast::Visibility,
834 struct_def: &ast::VariantData,
835 generics: Option<&ast::Generics>,
838 one_line_width: Option<usize>,
839 ) -> Option<String> {
841 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
842 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
852 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
866 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
867 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
870 let mut result = String::with_capacity(128);
871 let header = format!(
873 format_visibility(&item.vis),
874 format_unsafety(unsafety),
878 result.push_str(&header);
880 let body_lo = context.codemap.span_after(item.span, "{");
882 let shape = Shape::indented(offset + last_line_width(&result), context.config);
883 let generics_str = try_opt!(rewrite_generics(
887 mk_sp(item.span.lo(), body_lo),
889 result.push_str(&generics_str);
891 let trait_bound_str = try_opt!(rewrite_trait_bounds(
894 Shape::indented(offset, context.config),
896 // If the trait, generics, and trait bound cannot fit on the same line,
897 // put the trait bounds on an indented new line
898 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
899 context.config.comment_width()
902 let trait_indent = offset.block_only().block_indent(context.config);
903 result.push_str(&trait_indent.to_string(context.config));
905 result.push_str(&trait_bound_str);
907 let has_body = !trait_items.is_empty();
909 let where_density = if (context.config.where_density() == Density::Compressed &&
910 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
911 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
912 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
913 !result.contains('\n'))
920 let where_budget = context.budget(last_line_width(&result));
921 let pos_before_where = if type_param_bounds.is_empty() {
922 generics.where_clause.span.lo()
924 type_param_bounds[type_param_bounds.len() - 1].span().hi()
926 let option = WhereClauseOption::snuggled(&generics_str);
927 let where_clause_str = try_opt!(rewrite_where_clause(
929 &generics.where_clause,
930 context.config.item_brace_style(),
931 Shape::legacy(where_budget, offset.block_only()),
938 // If the where clause cannot fit on the same line,
939 // put the where clause on a new line
940 if !where_clause_str.contains('\n') &&
941 last_line_width(&result) + where_clause_str.len() + offset.width() >
942 context.config.comment_width()
945 let width = offset.block_indent + context.config.tab_spaces() - 1;
946 let where_indent = Indent::new(0, width);
947 result.push_str(&where_indent.to_string(context.config));
949 result.push_str(&where_clause_str);
951 if generics.where_clause.predicates.is_empty() {
952 let item_snippet = context.snippet(item.span);
953 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
955 let comment_hi = body_lo - BytePos(1);
956 let comment_lo = item.span.lo() + BytePos(lo as u32);
957 if comment_lo < comment_hi {
958 match recover_missing_comment_in_span(
959 mk_sp(comment_lo, comment_hi),
960 Shape::indented(offset, context.config),
962 last_line_width(&result),
964 Some(ref missing_comment) if !missing_comment.is_empty() => {
965 result.push_str(missing_comment);
973 match context.config.item_brace_style() {
974 _ if last_line_contains_single_line_comment(&result) => {
976 result.push_str(&offset.to_string(context.config));
978 BraceStyle::AlwaysNextLine => {
980 result.push_str(&offset.to_string(context.config));
982 BraceStyle::PreferSameLine => result.push(' '),
983 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
984 (!trait_items.is_empty() || result.contains('\n'))
987 result.push_str(&offset.to_string(context.config));
994 let snippet = context.snippet(item.span);
995 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
997 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
998 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
999 visitor.block_indent = offset.block_only().block_indent(context.config);
1000 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1002 for item in trait_items {
1003 visitor.visit_trait_item(item);
1006 visitor.format_missing(item.span.hi() - BytePos(1));
1008 let inner_indent_str = visitor.block_indent.to_string(context.config);
1009 let outer_indent_str = offset.block_only().to_string(context.config);
1012 result.push_str(&inner_indent_str);
1013 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1015 result.push_str(&outer_indent_str);
1016 } else if result.contains('\n') {
1027 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1028 format!("{};", format_header(item_name, ident, vis))
1031 pub fn format_struct_struct(
1032 context: &RewriteContext,
1035 vis: &ast::Visibility,
1036 fields: &[ast::StructField],
1037 generics: Option<&ast::Generics>,
1040 one_line_width: Option<usize>,
1041 ) -> Option<String> {
1042 let mut result = String::with_capacity(1024);
1044 let header_str = format_header(item_name, ident, vis);
1045 result.push_str(&header_str);
1047 let body_lo = context.codemap.span_after(span, "{");
1049 let generics_str = match generics {
1050 Some(g) => try_opt!(format_generics(
1055 context.config.item_brace_style(),
1058 mk_sp(span.lo(), body_lo),
1059 last_line_width(&result),
1062 // 3 = ` {}`, 2 = ` {`.
1063 let overhead = if fields.is_empty() { 3 } else { 2 };
1064 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1065 !fields.is_empty()) ||
1066 context.config.max_width() < overhead + result.len()
1068 format!("\n{}{{", offset.block_only().to_string(context.config))
1075 let overhead = if fields.is_empty() { 1 } else { 0 };
1076 let total_width = result.len() + generics_str.len() + overhead;
1077 if !generics_str.is_empty() && !generics_str.contains('\n') &&
1078 total_width > context.config.max_width()
1081 result.push_str(&offset.to_string(context.config));
1082 result.push_str(generics_str.trim_left());
1084 result.push_str(&generics_str);
1087 if fields.is_empty() {
1088 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1089 if snippet.trim().is_empty() {
1091 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1093 result.push_str(snippet.trim_right());
1095 result.push_str(&offset.to_string(context.config));
1097 result.push_str(&snippet);
1100 return Some(result);
1104 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1105 let one_line_budget =
1106 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1108 let items_str = try_opt!(rewrite_with_alignment(
1111 Shape::indented(offset, context.config),
1112 mk_sp(body_lo, span.hi()),
1116 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1117 Some(format!("{} {} }}", result, items_str))
1123 .block_indent(context.config)
1124 .to_string(context.config),
1126 offset.to_string(context.config)
1131 fn format_tuple_struct(
1132 context: &RewriteContext,
1135 vis: &ast::Visibility,
1136 fields: &[ast::StructField],
1137 generics: Option<&ast::Generics>,
1140 ) -> Option<String> {
1141 let mut result = String::with_capacity(1024);
1143 let header_str = format_header(item_name, ident, vis);
1144 result.push_str(&header_str);
1146 let body_lo = if fields.is_empty() {
1147 context.codemap.span_after(span, "(")
1151 let body_hi = if fields.is_empty() {
1152 context.codemap.span_after(span, ")")
1154 // This is a dirty hack to work around a missing `)` from the span of the last field.
1155 let last_arg_span = fields[fields.len() - 1].span;
1156 if context.snippet(last_arg_span).ends_with(')') {
1161 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1165 let where_clause_str = match generics {
1167 let budget = context.budget(last_line_width(&header_str));
1168 let shape = Shape::legacy(budget, offset);
1169 let g_span = mk_sp(span.lo(), body_lo);
1170 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1171 result.push_str(&generics_str);
1173 let where_budget = context.budget(last_line_width(&result));
1174 let option = WhereClauseOption::new(true, false);
1175 try_opt!(rewrite_where_clause(
1177 &generics.where_clause,
1178 context.config.item_brace_style(),
1179 Shape::legacy(where_budget, offset.block_only()),
1180 Density::Compressed,
1187 None => "".to_owned(),
1190 if fields.is_empty() {
1192 let used_width = last_line_used_width(&result, offset.width()) + 3;
1193 if used_width > context.config.max_width() {
1195 result.push_str(&offset
1196 .block_indent(context.config)
1197 .to_string(context.config))
1200 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1201 if snippet.is_empty() {
1203 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1204 result.push_str(snippet.trim_right());
1206 result.push_str(&offset.to_string(context.config));
1208 result.push_str(&snippet);
1213 let body = try_opt!(
1217 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1219 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1220 context.config.fn_call_width(),
1224 result.push_str(&body);
1227 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1228 (result.contains('\n') ||
1229 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1230 context.config.max_width())
1232 // We need to put the where clause on a new line, but we didn't
1233 // know that earlier, so the where clause will not be indented properly.
1235 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1236 .to_string(context.config));
1238 result.push_str(&where_clause_str);
1243 pub fn rewrite_type_alias(
1244 context: &RewriteContext,
1248 generics: &ast::Generics,
1249 vis: &ast::Visibility,
1251 ) -> Option<String> {
1252 let mut result = String::with_capacity(128);
1254 result.push_str(&format_visibility(vis));
1255 result.push_str("type ");
1256 result.push_str(&ident.to_string());
1259 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1260 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1261 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1262 result.push_str(&generics_str);
1264 let where_budget = context.budget(last_line_width(&result));
1265 let option = WhereClauseOption::snuggled(&result);
1266 let where_clause_str = try_opt!(rewrite_where_clause(
1268 &generics.where_clause,
1269 context.config.item_brace_style(),
1270 Shape::legacy(where_budget, indent),
1271 context.config.where_density(),
1277 result.push_str(&where_clause_str);
1278 if where_clause_str.is_empty() {
1279 result.push_str(" = ");
1281 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1284 let line_width = last_line_width(&result);
1285 // This checked_sub may fail as the extra space after '=' is not taken into account
1286 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1287 let budget = context.budget(indent.width() + line_width + ";".len());
1288 let type_indent = indent + line_width;
1289 // Try to fit the type on the same line
1290 let ty_str = try_opt!(
1291 ty.rewrite(context, Shape::legacy(budget, type_indent))
1293 // The line was too short, try to put the type on the next line
1295 // Remove the space after '='
1297 let type_indent = indent.block_indent(context.config);
1299 result.push_str(&type_indent.to_string(context.config));
1300 let budget = context.budget(type_indent.width() + ";".len());
1301 ty.rewrite(context, Shape::legacy(budget, type_indent))
1304 result.push_str(&ty_str);
1305 result.push_str(";");
1309 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1311 if config.space_before_type_annotation() {
1316 if config.space_after_type_annotation_colon() {
1324 pub fn rewrite_struct_field_prefix(
1325 context: &RewriteContext,
1326 field: &ast::StructField,
1327 ) -> Option<String> {
1328 let vis = format_visibility(&field.vis);
1329 let type_annotation_spacing = type_annotation_spacing(context.config);
1330 Some(match field.ident {
1331 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1332 None => format!("{}", vis),
1336 fn rewrite_struct_field_type(
1337 context: &RewriteContext,
1338 last_line_width: usize,
1339 field: &ast::StructField,
1342 ) -> Option<String> {
1343 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1346 .rewrite(context, ty_shape)
1347 .map(|ty| format!("{}{}", spacing, ty))
1350 impl Rewrite for ast::StructField {
1351 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1352 rewrite_struct_field(context, self, shape, 0)
1356 pub fn rewrite_struct_field(
1357 context: &RewriteContext,
1358 field: &ast::StructField,
1360 lhs_max_width: usize,
1361 ) -> Option<String> {
1362 if contains_skip(&field.attrs) {
1363 let span = context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi()));
1364 return wrap_str(span, context.config.max_width(), shape);
1367 let type_annotation_spacing = type_annotation_spacing(context.config);
1368 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1370 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1371 let attrs_extendable = attrs_str.is_empty() ||
1372 (context.config.attributes_on_same_line_as_field() && is_attributes_extendable(&attrs_str));
1373 let missing_span = if field.attrs.is_empty() {
1374 mk_sp(field.span.lo(), field.span.lo())
1376 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1378 let mut spacing = String::from(if field.ident.is_some() {
1379 type_annotation_spacing.1
1383 // Try to put everything on a single line.
1384 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1392 let overhead = last_line_width(&attr_prefix);
1393 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1394 for _ in 0..lhs_offset {
1397 // In this extreme case we will be missing a space betweeen an attribute and a field.
1398 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1401 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1402 if let Some(ref ty) = ty_rewritten {
1403 if !ty.contains('\n') {
1404 return Some(attr_prefix + ty);
1408 // We must use multiline.
1409 let last_line_width = last_line_width(&prefix);
1410 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1412 let type_offset = shape.indent.block_indent(context.config);
1413 let rewrite_type_in_next_line = || {
1416 .rewrite(context, Shape::indented(type_offset, context.config))
1419 let field_str = match ty_rewritten {
1420 // If we start from the next line and type fits in a single line, then do so.
1421 Some(ref ty) => match rewrite_type_in_next_line() {
1422 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1425 type_offset.to_string(context.config),
1431 let ty = try_opt!(rewrite_type_in_next_line());
1435 type_offset.to_string(context.config),
1440 combine_strs_with_missing_comments(
1450 pub fn rewrite_static(
1452 vis: &ast::Visibility,
1455 mutability: ast::Mutability,
1456 expr_opt: Option<&ptr::P<ast::Expr>>,
1459 context: &RewriteContext,
1460 ) -> Option<String> {
1461 let colon = colon_spaces(
1462 context.config.space_before_type_annotation(),
1463 context.config.space_after_type_annotation_colon(),
1465 let prefix = format!(
1467 format_visibility(vis),
1469 format_mutability(mutability),
1474 let ty_str = try_opt!(ty.rewrite(
1477 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1481 if let Some(expr) = expr_opt {
1482 let lhs = format!("{}{} =", prefix, ty_str);
1484 let remaining_width = context.budget(offset.block_indent + 1);
1489 Shape::legacy(remaining_width, offset.block_only()),
1491 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1493 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1495 Some(format!("{}{};", prefix, ty_str))
1499 pub fn rewrite_associated_type(
1501 ty_opt: Option<&ptr::P<ast::Ty>>,
1502 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1503 context: &RewriteContext,
1505 ) -> Option<String> {
1506 let prefix = format!("type {}", ident);
1508 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1510 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1511 let bounds: &[_] = ty_param_bounds;
1512 let bound_str = try_opt!(
1515 .map(|ty_bound| ty_bound.rewrite(context, shape))
1516 .collect::<Option<Vec<_>>>()
1518 if !bounds.is_empty() {
1519 format!(": {}", join_bounds(context, shape, &bound_str))
1527 if let Some(ty) = ty_opt {
1528 let ty_str = try_opt!(ty.rewrite(
1531 context.budget(indent.block_indent + prefix.len() + 2),
1532 indent.block_only(),
1535 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1537 Some(format!("{}{};", prefix, type_bounds_str))
1541 pub fn rewrite_associated_impl_type(
1543 defaultness: ast::Defaultness,
1544 ty_opt: Option<&ptr::P<ast::Ty>>,
1545 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1546 context: &RewriteContext,
1548 ) -> Option<String> {
1549 let result = try_opt!(rewrite_associated_type(
1552 ty_param_bounds_opt,
1558 ast::Defaultness::Default => Some(format!("default {}", result)),
1563 impl Rewrite for ast::FunctionRetTy {
1564 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1566 ast::FunctionRetTy::Default(_) => Some(String::new()),
1567 ast::FunctionRetTy::Ty(ref ty) => {
1568 let inner_width = try_opt!(shape.width.checked_sub(3));
1569 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1570 .map(|r| format!("-> {}", r))
1576 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1578 ast::TyKind::Infer => {
1579 let original = context.snippet(ty.span);
1586 impl Rewrite for ast::Arg {
1587 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1588 if is_named_arg(self) {
1589 let mut result = try_opt!(
1591 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1594 if !is_empty_infer(context, &*self.ty) {
1595 if context.config.space_before_type_annotation() {
1596 result.push_str(" ");
1598 result.push_str(":");
1599 if context.config.space_after_type_annotation_colon() {
1600 result.push_str(" ");
1602 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1603 let ty_str = try_opt!(self.ty.rewrite(
1605 Shape::legacy(max_width, shape.indent + result.len()),
1607 result.push_str(&ty_str);
1612 self.ty.rewrite(context, shape)
1617 fn rewrite_explicit_self(
1618 explicit_self: &ast::ExplicitSelf,
1620 context: &RewriteContext,
1621 ) -> Option<String> {
1622 match explicit_self.node {
1623 ast::SelfKind::Region(lt, m) => {
1624 let mut_str = format_mutability(m);
1627 let lifetime_str = try_opt!(l.rewrite(
1629 Shape::legacy(context.config.max_width(), Indent::empty()),
1631 Some(format!("&{} {}self", lifetime_str, mut_str))
1633 None => Some(format!("&{}self", mut_str)),
1636 ast::SelfKind::Explicit(ref ty, _) => {
1637 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1639 let mutability = explicit_self_mutability(&args[0]);
1640 let type_str = try_opt!(ty.rewrite(
1642 Shape::legacy(context.config.max_width(), Indent::empty()),
1647 format_mutability(mutability),
1651 ast::SelfKind::Value(_) => {
1652 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1654 let mutability = explicit_self_mutability(&args[0]);
1656 Some(format!("{}self", format_mutability(mutability)))
1661 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1662 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1663 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1664 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1671 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1672 if is_named_arg(arg) {
1679 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1681 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1682 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1683 _ => arg.ty.span.hi(),
1687 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1688 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1689 ident.node != symbol::keywords::Invalid.ident()
1695 // Return type is (result, force_new_line_for_brace)
1697 context: &RewriteContext,
1701 generics: &ast::Generics,
1702 unsafety: ast::Unsafety,
1703 constness: ast::Constness,
1704 defaultness: ast::Defaultness,
1706 vis: &ast::Visibility,
1708 newline_brace: bool,
1711 ) -> Option<(String, bool)> {
1712 let mut force_new_line_for_brace = false;
1714 let where_clause = &generics.where_clause;
1716 let mut result = String::with_capacity(1024);
1717 // Vis defaultness constness unsafety abi.
1718 result.push_str(&*format_visibility(vis));
1719 result.push_str(format_defaultness(defaultness));
1720 result.push_str(format_constness(constness));
1721 result.push_str(format_unsafety(unsafety));
1722 if abi != abi::Abi::Rust {
1723 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1727 result.push_str("fn ");
1728 result.push_str(&ident.to_string());
1731 let overhead = if has_braces && !newline_brace {
1738 let used_width = last_line_used_width(&result, indent.width());
1739 let one_line_budget = context.budget(used_width + overhead);
1741 width: one_line_budget,
1745 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1746 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1747 result.push_str(&generics_str);
1749 let snuggle_angle_bracket = generics_str
1752 .map_or(false, |l| l.trim_left().len() == 1);
1754 // Note that the width and indent don't really matter, we'll re-layout the
1755 // return type later anyway.
1756 let ret_str = try_opt!(
1758 .rewrite(context, Shape::indented(indent, context.config))
1761 let multi_line_ret_str = ret_str.contains('\n');
1762 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1765 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1776 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1782 // Check if vertical layout was forced.
1783 if one_line_budget == 0 {
1784 if snuggle_angle_bracket {
1786 } else if context.config.fn_args_paren_newline() {
1788 result.push_str(&arg_indent.to_string(context.config));
1789 if context.config.fn_args_layout() == IndentStyle::Visual {
1790 arg_indent = arg_indent + 1; // extra space for `(`
1794 result.push_str("(");
1795 if context.config.fn_args_layout() == IndentStyle::Visual {
1797 result.push_str(&arg_indent.to_string(context.config));
1803 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1807 // A conservative estimation, to goal is to be over all parens in generics
1808 let args_start = generics
1811 .map_or(span.lo(), |tp| end_typaram(tp));
1812 let args_end = if fd.inputs.is_empty() {
1815 .span_after(mk_sp(args_start, span.hi()), ")")
1817 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1818 context.codemap.span_after(last_span, ")")
1820 let args_span = mk_sp(
1823 .span_after(mk_sp(args_start, span.hi()), "("),
1826 let arg_str = try_opt!(rewrite_args(
1829 fd.get_self().as_ref(),
1836 generics_str.contains('\n'),
1839 let put_args_in_block = match context.config.fn_args_layout() {
1840 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1842 } && !fd.inputs.is_empty();
1844 let mut args_last_line_contains_comment = false;
1845 if put_args_in_block {
1846 arg_indent = indent.block_indent(context.config);
1848 result.push_str(&arg_indent.to_string(context.config));
1849 result.push_str(&arg_str);
1851 result.push_str(&indent.to_string(context.config));
1854 result.push_str(&arg_str);
1855 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1856 // Put the closing brace on the next line if it overflows the max width.
1858 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1861 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1864 // If the last line of args contains comment, we cannot put the closing paren
1865 // on the same line.
1869 .map_or(false, |last_line| last_line.contains("//"))
1871 args_last_line_contains_comment = true;
1873 result.push_str(&arg_indent.to_string(context.config));
1879 if let ast::FunctionRetTy::Ty(..) = fd.output {
1880 let ret_should_indent = match context.config.fn_args_layout() {
1881 // If our args are block layout then we surely must have space.
1882 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1883 _ if args_last_line_contains_comment => false,
1884 _ if result.contains('\n') || multi_line_ret_str => true,
1886 // If the return type would push over the max width, then put the return type on
1887 // a new line. With the +1 for the signature length an additional space between
1888 // the closing parenthesis of the argument and the arrow '->' is considered.
1889 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1891 // If there is no where clause, take into account the space after the return type
1893 if where_clause.predicates.is_empty() {
1897 sig_length > context.config.max_width()
1900 let ret_indent = if ret_should_indent {
1901 let indent = match context.config.fn_return_indent() {
1902 ReturnIndent::WithWhereClause => indent + 4,
1903 // Aligning with non-existent args looks silly.
1904 _ if arg_str.is_empty() => {
1905 force_new_line_for_brace = true;
1908 // FIXME: we might want to check that using the arg indent
1909 // doesn't blow our budget, and if it does, then fallback to
1910 // the where clause indent.
1915 result.push_str(&indent.to_string(context.config));
1919 Indent::new(indent.block_indent, last_line_width(&result))
1922 if multi_line_ret_str || ret_should_indent {
1923 // Now that we know the proper indent and width, we need to
1924 // re-layout the return type.
1925 let ret_str = try_opt!(
1927 .rewrite(context, Shape::indented(ret_indent, context.config))
1929 result.push_str(&ret_str);
1931 result.push_str(&ret_str);
1934 // Comment between return type and the end of the decl.
1935 let snippet_lo = fd.output.span().hi();
1936 if where_clause.predicates.is_empty() {
1937 let snippet_hi = span.hi();
1938 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1939 // Try to preserve the layout of the original snippet.
1940 let original_starts_with_newline = snippet
1942 .map_or(false, |i| snippet[i..].starts_with('\n'));
1943 let original_ends_with_newline = snippet
1944 .rfind(|c| c != ' ')
1945 .map_or(false, |i| snippet[i..].ends_with('\n'));
1946 let snippet = snippet.trim();
1947 if !snippet.is_empty() {
1948 result.push(if original_starts_with_newline {
1953 result.push_str(snippet);
1954 if original_ends_with_newline {
1955 force_new_line_for_brace = true;
1961 let should_compress_where = match context.config.where_density() {
1962 Density::Compressed => !result.contains('\n'),
1963 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1967 let pos_before_where = match fd.output {
1968 ast::FunctionRetTy::Default(..) => args_span.hi(),
1969 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1972 if where_clause.predicates.len() == 1 && should_compress_where {
1973 let budget = context.budget(last_line_used_width(&result, indent.width()));
1974 if let Some(where_clause_str) = rewrite_where_clause(
1977 context.config.fn_brace_style(),
1978 Shape::legacy(budget, indent),
1979 Density::Compressed,
1983 WhereClauseOption::compressed(),
1985 result.push_str(&where_clause_str);
1986 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1987 return Some((result, force_new_line_for_brace));
1991 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
1992 let where_clause_str = try_opt!(rewrite_where_clause(
1995 context.config.fn_brace_style(),
1996 Shape::indented(indent, context.config),
2003 // If there are neither where clause nor return type, we may be missing comments between
2005 if where_clause_str.is_empty() {
2006 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2007 match recover_missing_comment_in_span(
2008 mk_sp(args_span.hi(), ret_span.hi()),
2011 last_line_width(&result),
2013 Some(ref missing_comment) if !missing_comment.is_empty() => {
2014 result.push_str(missing_comment);
2015 force_new_line_for_brace = true;
2022 result.push_str(&where_clause_str);
2024 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2025 Some((result, force_new_line_for_brace))
2028 #[derive(Copy, Clone)]
2029 struct WhereClauseOption {
2030 suppress_comma: bool, // Force no trailing comma
2031 snuggle: bool, // Do not insert newline before `where`
2032 compress_where: bool, // Try single line where clause instead of vertical layout
2035 impl WhereClauseOption {
2036 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2038 suppress_comma: suppress_comma,
2040 compress_where: false,
2044 pub fn compressed() -> WhereClauseOption {
2046 suppress_comma: true,
2048 compress_where: true,
2052 pub fn snuggled(current: &str) -> WhereClauseOption {
2054 suppress_comma: false,
2055 snuggle: trimmed_last_line_width(current) == 1,
2056 compress_where: false,
2062 context: &RewriteContext,
2064 explicit_self: Option<&ast::ExplicitSelf>,
2065 one_line_budget: usize,
2066 multi_line_budget: usize,
2071 generics_str_contains_newline: bool,
2072 ) -> Option<String> {
2073 let mut arg_item_strs = try_opt!(
2076 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2078 .collect::<Option<Vec<_>>>()
2081 // Account for sugary self.
2082 // FIXME: the comment for the self argument is dropped. This is blocked
2083 // on rust issue #27522.
2084 let min_args = explicit_self
2085 .and_then(|explicit_self| {
2086 rewrite_explicit_self(explicit_self, args, context)
2088 .map_or(1, |self_str| {
2089 arg_item_strs[0] = self_str;
2093 // Comments between args.
2094 let mut arg_items = Vec::new();
2096 arg_items.push(ListItem::from_str(""));
2099 // FIXME(#21): if there are no args, there might still be a comment, but
2100 // without spans for the comment or parens, there is no chance of
2101 // getting it right. You also don't get to put a comment on self, unless
2103 if args.len() >= min_args || variadic {
2104 let comment_span_start = if min_args == 2 {
2105 let second_arg_start = if arg_has_pattern(&args[1]) {
2106 args[1].pat.span.lo()
2108 args[1].ty.span.lo()
2110 let reduced_span = mk_sp(span.lo(), second_arg_start);
2112 context.codemap.span_after_last(reduced_span, ",")
2117 enum ArgumentKind<'a> {
2118 Regular(&'a ast::Arg),
2122 let variadic_arg = if variadic {
2123 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2124 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2125 Some(ArgumentKind::Variadic(variadic_start))
2130 let more_items = itemize_list(
2132 args[min_args - 1..]
2134 .map(ArgumentKind::Regular)
2135 .chain(variadic_arg),
2138 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2139 ArgumentKind::Variadic(start) => start,
2142 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2143 ArgumentKind::Variadic(start) => start + BytePos(3),
2146 ArgumentKind::Regular(..) => None,
2147 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2154 arg_items.extend(more_items);
2157 let fits_in_one_line = !generics_str_contains_newline &&
2158 (arg_items.is_empty() || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2160 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2161 item.item = Some(arg);
2164 let last_line_ends_with_comment = arg_items
2167 .and_then(|item| item.post_comment.as_ref())
2168 .map_or(false, |s| s.trim().starts_with("//"));
2170 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2171 IndentStyle::Block if fits_in_one_line => {
2172 (indent.block_indent(context.config), SeparatorTactic::Never)
2174 IndentStyle::Block => (
2175 indent.block_indent(context.config),
2176 context.config.trailing_comma(),
2178 IndentStyle::Visual if last_line_ends_with_comment => {
2179 (arg_indent, context.config.trailing_comma())
2181 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2184 let tactic = definitive_tactic(
2186 context.config.fn_args_density().to_list_tactic(),
2190 let budget = match tactic {
2191 DefinitiveListTactic::Horizontal => one_line_budget,
2192 _ => multi_line_budget,
2195 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2197 let fmt = ListFormatting {
2200 trailing_separator: if variadic {
2201 SeparatorTactic::Never
2205 separator_place: SeparatorPlace::Back,
2206 shape: Shape::legacy(budget, indent),
2207 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2208 preserve_newline: true,
2209 config: context.config,
2212 write_list(&arg_items, &fmt)
2215 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2216 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2217 ident.node != symbol::keywords::Invalid.ident()
2223 fn compute_budgets_for_args(
2224 context: &RewriteContext,
2228 newline_brace: bool,
2230 force_vertical_layout: bool,
2231 ) -> Option<((usize, usize, Indent))> {
2233 "compute_budgets_for_args {} {:?}, {}, {}",
2239 // Try keeping everything on the same line.
2240 if !result.contains('\n') && !force_vertical_layout {
2241 // 2 = `()`, 3 = `() `, space is before ret_string.
2242 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2243 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2253 let one_line_budget = context.budget(used_space);
2255 if one_line_budget > 0 {
2257 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2258 IndentStyle::Block => {
2259 let indent = indent.block_indent(context.config);
2260 (indent, context.budget(indent.width() + 1))
2262 IndentStyle::Visual => {
2263 let indent = indent + result.len() + 1;
2264 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2265 (indent, context.budget(multi_line_overhead))
2269 return Some((one_line_budget, multi_line_budget, indent));
2273 // Didn't work. we must force vertical layout and put args on a newline.
2274 let new_indent = indent.block_indent(context.config);
2275 let used_space = match context.config.fn_args_layout() {
2277 IndentStyle::Block => new_indent.width() + 1,
2278 // Account for `)` and possibly ` {`.
2279 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2281 Some((0, context.budget(used_space), new_indent))
2284 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2285 match (config.fn_brace_style(), config.where_density()) {
2286 (BraceStyle::AlwaysNextLine, _) => true,
2287 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2288 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2289 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2294 fn rewrite_generics(
2295 context: &RewriteContext,
2296 generics: &ast::Generics,
2299 ) -> Option<String> {
2300 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2301 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2302 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2303 rewrite_generics_inner(context, generics, g_shape, 0, span)
2307 fn rewrite_generics_inner(
2308 context: &RewriteContext,
2309 generics: &ast::Generics,
2311 one_line_width: usize,
2313 ) -> Option<String> {
2314 // FIXME: convert bounds to where clauses where they get too big or if
2315 // there is a where clause at all.
2318 enum GenericsArg<'a> {
2319 Lifetime(&'a ast::LifetimeDef),
2320 TyParam(&'a ast::TyParam),
2322 impl<'a> Rewrite for GenericsArg<'a> {
2323 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2325 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2326 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2330 impl<'a> Spanned for GenericsArg<'a> {
2331 fn span(&self) -> Span {
2333 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2334 GenericsArg::TyParam(ref ty) => ty.span(),
2339 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2340 return Some(String::new());
2343 let generics_args = generics
2346 .map(|lt| GenericsArg::Lifetime(lt))
2347 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2348 let items = itemize_list(
2352 |arg| arg.span().lo(),
2353 |arg| arg.span().hi(),
2354 |arg| arg.rewrite(context, shape),
2355 context.codemap.span_after(span, "<"),
2359 format_generics_item_list(context, items, shape, one_line_width)
2362 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2363 match config.generics_indent() {
2364 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2365 IndentStyle::Block => {
2369 .block_indent(config.tab_spaces())
2370 .with_max_width(config)
2376 pub fn format_generics_item_list<I>(
2377 context: &RewriteContext,
2380 one_line_budget: usize,
2383 I: Iterator<Item = ListItem>,
2385 let item_vec = items.collect::<Vec<_>>();
2387 let tactic = definitive_tactic(
2389 ListTactic::HorizontalVertical,
2393 let fmt = ListFormatting {
2396 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2397 SeparatorTactic::Never
2399 context.config.trailing_comma()
2401 separator_place: SeparatorPlace::Back,
2403 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2404 preserve_newline: true,
2405 config: context.config,
2408 let list_str = try_opt!(write_list(&item_vec, &fmt));
2410 Some(wrap_generics_with_angle_brackets(
2417 pub fn wrap_generics_with_angle_brackets(
2418 context: &RewriteContext,
2420 list_offset: Indent,
2422 if context.config.generics_indent() == IndentStyle::Block &&
2423 (list_str.contains('\n') || list_str.ends_with(','))
2427 list_offset.to_string(context.config),
2430 .block_unindent(context.config)
2431 .to_string(context.config)
2433 } else if context.config.spaces_within_angle_brackets() {
2434 format!("< {} >", list_str)
2436 format!("<{}>", list_str)
2440 fn rewrite_trait_bounds(
2441 context: &RewriteContext,
2442 type_param_bounds: &ast::TyParamBounds,
2444 ) -> Option<String> {
2445 let bounds: &[_] = type_param_bounds;
2447 if bounds.is_empty() {
2448 return Some(String::new());
2450 let bound_str = try_opt!(
2453 .map(|ty_bound| ty_bound.rewrite(context, shape))
2454 .collect::<Option<Vec<_>>>()
2456 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2459 fn rewrite_where_clause_rfc_style(
2460 context: &RewriteContext,
2461 where_clause: &ast::WhereClause,
2464 span_end: Option<BytePos>,
2465 span_end_before_where: BytePos,
2466 where_clause_option: WhereClauseOption,
2467 ) -> Option<String> {
2468 let block_shape = shape.block().with_max_width(context.config);
2470 let (span_before, span_after) =
2471 missing_span_before_after_where(span_end_before_where, where_clause);
2472 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2479 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2482 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2485 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2486 // each clause on one line, trailing comma (except if suppress_comma)
2487 let span_start = where_clause.predicates[0].span().lo();
2488 // If we don't have the start of the next span, then use the end of the
2489 // predicates, but that means we miss comments.
2490 let len = where_clause.predicates.len();
2491 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2492 let span_end = span_end.unwrap_or(end_of_preds);
2493 let items = itemize_list(
2495 where_clause.predicates.iter(),
2497 |pred| pred.span().lo(),
2498 |pred| pred.span().hi(),
2499 |pred| pred.rewrite(context, block_shape),
2504 let comma_tactic = if where_clause_option.suppress_comma {
2505 SeparatorTactic::Never
2507 context.config.trailing_comma()
2510 let fmt = ListFormatting {
2511 tactic: DefinitiveListTactic::Vertical,
2513 trailing_separator: comma_tactic,
2514 separator_place: SeparatorPlace::Back,
2515 shape: clause_shape,
2516 ends_with_newline: true,
2517 preserve_newline: true,
2518 config: context.config,
2520 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2522 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2525 format!("\n{}", shape.indent.to_string(context.config))
2527 let newline_before_where = comment_separator(&comment_before, shape);
2528 let newline_after_where = comment_separator(&comment_after, clause_shape);
2531 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2532 comment_after.is_empty() && !preds_str.contains('\n') &&
2533 6 + preds_str.len() <= shape.width
2537 format!("\n{}", clause_shape.indent.to_string(context.config))
2540 "{}{}{}where{}{}{}{}",
2543 newline_before_where,
2544 newline_after_where,
2551 fn rewrite_where_clause(
2552 context: &RewriteContext,
2553 where_clause: &ast::WhereClause,
2554 brace_style: BraceStyle,
2558 span_end: Option<BytePos>,
2559 span_end_before_where: BytePos,
2560 where_clause_option: WhereClauseOption,
2561 ) -> Option<String> {
2562 if where_clause.predicates.is_empty() {
2563 return Some(String::new());
2566 if context.config.where_style() == Style::Rfc {
2567 return rewrite_where_clause_rfc_style(
2573 span_end_before_where,
2574 where_clause_option,
2578 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2580 let offset = match context.config.where_pred_indent() {
2581 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2582 // 6 = "where ".len()
2583 IndentStyle::Visual => shape.indent + extra_indent + 6,
2585 // FIXME: if where_pred_indent != Visual, then the budgets below might
2586 // be out by a char or two.
2588 let budget = context.config.max_width() - offset.width();
2589 let span_start = where_clause.predicates[0].span().lo();
2590 // If we don't have the start of the next span, then use the end of the
2591 // predicates, but that means we miss comments.
2592 let len = where_clause.predicates.len();
2593 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2594 let span_end = span_end.unwrap_or(end_of_preds);
2595 let items = itemize_list(
2597 where_clause.predicates.iter(),
2599 |pred| pred.span().lo(),
2600 |pred| pred.span().hi(),
2601 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2606 let item_vec = items.collect::<Vec<_>>();
2607 // FIXME: we don't need to collect here if the where_layout isn't
2608 // HorizontalVertical.
2609 let tactic = definitive_tactic(
2611 context.config.where_layout(),
2616 let mut comma_tactic = context.config.trailing_comma();
2617 // Kind of a hack because we don't usually have trailing commas in where clauses.
2618 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2619 comma_tactic = SeparatorTactic::Never;
2622 let fmt = ListFormatting {
2625 trailing_separator: comma_tactic,
2626 separator_place: SeparatorPlace::Back,
2627 shape: Shape::legacy(budget, offset),
2628 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2629 preserve_newline: true,
2630 config: context.config,
2632 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2634 let end_length = if terminator == "{" {
2635 // If the brace is on the next line we don't need to count it otherwise it needs two
2638 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2639 BraceStyle::PreferSameLine => 2,
2641 } else if terminator == "=" {
2646 if density == Density::Tall || preds_str.contains('\n') ||
2647 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2651 (shape.indent + extra_indent).to_string(context.config),
2655 Some(format!(" where {}", preds_str))
2659 fn missing_span_before_after_where(
2660 before_item_span_end: BytePos,
2661 where_clause: &ast::WhereClause,
2663 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2665 let pos_after_where = where_clause.span.lo() + BytePos(5);
2666 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2667 (missing_span_before, missing_span_after)
2670 fn rewrite_comments_before_after_where(
2671 context: &RewriteContext,
2672 span_before_where: Span,
2673 span_after_where: Span,
2675 ) -> Option<(String, String)> {
2676 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2677 let after_comment = try_opt!(rewrite_missing_comment(
2679 shape.block_indent(context.config.tab_spaces()),
2682 Some((before_comment, after_comment))
2685 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2686 format!("{}{}{}", format_visibility(vis), item_name, ident)
2690 context: &RewriteContext,
2691 generics: &ast::Generics,
2694 brace_style: BraceStyle,
2695 force_same_line_brace: bool,
2699 ) -> Option<String> {
2700 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2701 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2703 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2704 let budget = context.budget(last_line_used_width(&result, offset.width()));
2705 let option = WhereClauseOption::snuggled(&result);
2706 let where_clause_str = try_opt!(rewrite_where_clause(
2708 &generics.where_clause,
2710 Shape::legacy(budget, offset.block_only()),
2717 result.push_str(&where_clause_str);
2718 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2719 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2721 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2722 brace_style != BraceStyle::AlwaysNextLine
2724 let total_used_width = last_line_used_width(&result, used_width);
2725 let remaining_budget = context.budget(total_used_width);
2726 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2727 // and hence we take the closer into account as well for one line budget.
2728 // We assume that the closer has the same length as the opener.
2729 let overhead = if force_same_line_brace {
2730 1 + opener.len() + opener.len()
2734 let forbid_same_line_brace = overhead > remaining_budget;
2735 if !forbid_same_line_brace && same_line_brace {
2739 result.push_str(&offset.block_only().to_string(context.config));
2741 result.push_str(opener);
2746 impl Rewrite for ast::ForeignItem {
2747 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2748 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2749 // Drop semicolon or it will be interpreted as comment.
2750 // FIXME: this may be a faulty span from libsyntax.
2751 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2753 let item_str = try_opt!(match self.node {
2754 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2761 ast::Unsafety::Normal,
2762 ast::Constness::NotConst,
2763 ast::Defaultness::Final,
2764 // These are not actually rust functions,
2765 // but we format them as such.
2772 ).map(|(s, _)| format!("{};", s))
2774 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2775 // FIXME(#21): we're dropping potential comments in between the
2776 // function keywords here.
2777 let vis = format_visibility(&self.vis);
2778 let mut_str = if is_mutable { "mut " } else { "" };
2779 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2781 let shape = try_opt!(shape.sub_width(1));
2782 ty.rewrite(context, shape).map(|ty_str| {
2783 // 1 = space between prefix and type.
2784 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2787 let nested_indent = shape.indent.block_indent(context.config);
2788 format!("\n{}", nested_indent.to_string(context.config))
2790 format!("{}{}{};", prefix, sep, ty_str)
2795 let missing_span = if self.attrs.is_empty() {
2796 mk_sp(self.span.lo(), self.span.lo())
2798 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2800 combine_strs_with_missing_comments(