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 let mut result = "let ".to_owned();
61 let pat_shape = try_opt!(shape.offset_left(4));
63 let pat_shape = try_opt!(pat_shape.sub_width(1));
64 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
65 result.push_str(&pat_str);
67 // String that is placed within the assignment pattern and expression.
69 let mut infix = String::with_capacity(32);
71 if let Some(ref ty) = self.ty {
72 let separator = type_annotation_separator(context.config);
73 let indent = shape.indent + last_line_width(&result) + separator.len();
75 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
76 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
78 infix.push_str(separator);
79 infix.push_str(&rewrite);
82 if self.init.is_some() {
89 result.push_str(&infix);
91 if let Some(ref ex) = self.init {
92 // 1 = trailing semicolon;
93 let nested_shape = try_opt!(shape.sub_width(1));
95 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
103 // TODO convert to using rewrite style rather than visitor
104 // TODO format modules in this style
107 keyword: &'static str,
109 vis: Option<&'a ast::Visibility>,
110 body: Vec<BodyElement<'a>>,
115 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
116 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
119 format!("extern {}", fm.abi)
127 .map(|i| BodyElement::ForeignItem(i))
134 enum BodyElement<'a> {
135 // Stmt(&'a ast::Stmt),
136 // Field(&'a ast::Field),
137 // Variant(&'a ast::Variant),
138 // Item(&'a ast::Item),
139 ForeignItem(&'a ast::ForeignItem),
142 impl<'a> FmtVisitor<'a> {
143 fn format_item(&mut self, item: Item) {
144 self.buffer.push_str(&item.abi);
145 self.buffer.push_str(" ");
147 let snippet = self.snippet(item.span);
148 let brace_pos = snippet.find_uncommented("{").unwrap();
150 self.buffer.push_str("{");
151 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
152 // FIXME: this skips comments between the extern keyword and the opening
154 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
155 self.block_indent = self.block_indent.block_indent(self.config);
157 if item.body.is_empty() {
158 self.format_missing_no_indent(item.span.hi - BytePos(1));
159 self.block_indent = self.block_indent.block_unindent(self.config);
162 .push_str(&self.block_indent.to_string(self.config));
164 for item in &item.body {
165 self.format_body_element(item);
168 self.block_indent = self.block_indent.block_unindent(self.config);
169 self.format_missing_with_indent(item.span.hi - BytePos(1));
173 self.buffer.push_str("}");
174 self.last_pos = item.span.hi;
177 fn format_body_element(&mut self, element: &BodyElement) {
179 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
183 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
184 let item = Item::from_foreign_mod(fm, span, self.config);
185 self.format_item(item);
189 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
190 let rewrite = item.rewrite(&self.get_context(), self.shape());
191 self.push_rewrite(item.span(), rewrite);
192 self.last_pos = item.span.hi;
200 generics: &ast::Generics,
201 unsafety: ast::Unsafety,
202 constness: ast::Constness,
203 defaultness: ast::Defaultness,
205 vis: &ast::Visibility,
208 ) -> Option<String> {
209 let context = self.get_context();
211 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
212 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
213 !context.config.fn_empty_single_line();
214 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
216 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
233 if force_newline_brace {
234 newline_brace = true;
235 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
236 !result.contains('\n')
238 newline_brace = false;
241 // Prepare for the function body by possibly adding a newline and
243 // FIXME we'll miss anything between the end of the signature and the
244 // start of the body, but we need more spans from the compiler to solve
248 result.push_str(&indent.to_string(self.config));
253 self.single_line_fn(&result, block).or_else(|| Some(result))
256 pub fn rewrite_required_fn(
260 sig: &ast::MethodSig,
262 ) -> Option<String> {
263 // Drop semicolon or it will be interpreted as comment.
264 let span = mk_sp(span.lo, span.hi - BytePos(1));
265 let context = self.get_context();
267 let (mut result, _) = try_opt!(rewrite_fn_base(
275 ast::Defaultness::Final,
277 &ast::Visibility::Inherited,
284 // Re-attach semicolon
290 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
291 if fn_str.contains('\n') {
295 let codemap = self.get_context().codemap;
297 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
298 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
300 return Some(format!("{}{{}}", fn_str));
303 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
305 if let Some(ref stmt) = block.stmts.first() {
306 match stmt_expr(stmt) {
308 let suffix = if semicolon_for_expr(&self.get_context(), e) {
314 format_expr(&e, ExprType::Statement, &self.get_context(), self.shape())
316 .or_else(|| Some(self.snippet(e.span)))
318 None => stmt.rewrite(&self.get_context(), self.shape()),
325 if let Some(res) = rewrite {
326 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
327 if !res.contains('\n') && width <= self.config.max_width() {
328 return Some(format!("{}{{ {} }}", fn_str, res));
339 vis: &ast::Visibility,
340 enum_def: &ast::EnumDef,
341 generics: &ast::Generics,
344 let enum_header = format_header("enum ", ident, vis);
345 self.buffer.push_str(&enum_header);
347 let enum_snippet = self.snippet(span);
348 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
349 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
350 let generics_str = format_generics(
355 self.config.item_brace_style(),
356 enum_def.variants.is_empty(),
358 mk_sp(span.lo, body_start),
359 last_line_width(&enum_header),
361 self.buffer.push_str(&generics_str);
363 self.last_pos = body_start;
365 self.block_indent = self.block_indent.block_indent(self.config);
366 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
368 Some(ref body_str) => self.buffer.push_str(body_str),
369 None => if contains_comment(&enum_snippet[brace_pos..]) {
370 self.format_missing_no_indent(span.hi - BytePos(1))
372 self.format_missing(span.hi - BytePos(1))
375 self.block_indent = self.block_indent.block_unindent(self.config);
377 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
379 .push_str(&self.block_indent.to_string(self.config));
381 self.buffer.push_str("}");
382 self.last_pos = span.hi;
385 // Format the body of an enum definition
386 fn format_variant_list(
388 enum_def: &ast::EnumDef,
391 ) -> Option<String> {
392 if enum_def.variants.is_empty() {
395 let mut result = String::with_capacity(1024);
397 let indentation = self.block_indent.to_string(self.config);
398 result.push_str(&indentation);
400 let items = itemize_list(
402 enum_def.variants.iter(),
404 |f| if !f.node.attrs.is_empty() {
405 f.node.attrs[0].span.lo
410 |f| self.format_variant(f),
416 let shape = self.shape().sub_width(2).unwrap();
417 let fmt = ListFormatting {
418 tactic: DefinitiveListTactic::Vertical,
420 trailing_separator: self.config.trailing_comma(),
421 separator_place: SeparatorPlace::Back,
423 ends_with_newline: true,
424 preserve_newline: true,
428 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
429 result.push_str(&list);
434 // Variant of an enum.
435 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
436 if contains_skip(&field.node.attrs) {
437 let lo = field.node.attrs[0].span.lo;
438 let span = mk_sp(lo, field.span.hi);
439 return Some(self.snippet(span));
442 let context = self.get_context();
443 let indent = self.block_indent;
444 let shape = self.shape();
445 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
450 .map_or(field.span.lo, |attr| attr.span.hi);
451 let span = mk_sp(lo, field.span.lo);
453 let variant_body = match field.node.data {
454 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
455 // FIXME: Should limit the width, as we have a trailing comma
456 try_opt!(format_struct(
460 &ast::Visibility::Inherited,
465 Some(self.config.struct_variant_width()),
468 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
470 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
471 if one_line_width <= shape.width {
472 format!("{} = {}", field.node.name, self.snippet(expr.span))
479 .block_indent(self.config)
480 .to_string(self.config),
481 self.snippet(expr.span)
485 String::from(field.node.name.to_string())
489 let attrs_extendable = attrs_str.is_empty() ||
490 (context.config.attributes_on_same_line_as_variant() &&
491 is_attributes_extendable(&attrs_str));
492 combine_strs_with_missing_comments(
504 context: &RewriteContext,
507 where_span_end: Option<BytePos>,
508 ) -> Option<String> {
509 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
510 let mut result = String::with_capacity(128);
511 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
512 let indent_str = offset.to_string(context.config);
513 let sep = format!("\n{}", &indent_str);
514 result.push_str(&ref_and_type);
516 let where_budget = if result.contains('\n') {
517 context.config.max_width()
522 .checked_sub(last_line_width(&result))
525 let option = WhereClauseOption::snuggled(&ref_and_type);
526 let where_clause_str = try_opt!(rewrite_where_clause(
528 &generics.where_clause,
529 context.config.item_brace_style(),
530 Shape::legacy(where_budget, offset.block_only()),
531 context.config.where_density(),
538 // If there is no where clause, we may have missing comments between the trait name and
539 // the opening brace.
540 if generics.where_clause.predicates.is_empty() {
541 if let Some(hi) = where_span_end {
542 match recover_missing_comment_in_span(
543 mk_sp(self_ty.span.hi, hi),
544 Shape::indented(offset, context.config),
546 last_line_width(&result),
548 Some(ref missing_comment) if !missing_comment.is_empty() => {
549 result.push_str(missing_comment);
556 if try_opt!(is_impl_single_line(
563 result.push_str(&where_clause_str);
564 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
565 result.push_str(&format!("{}{{{}}}", &sep, &sep));
567 result.push_str(" {}");
572 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
574 let width = offset.block_indent + context.config.tab_spaces() - 1;
575 let where_indent = Indent::new(0, width);
576 result.push_str(&where_indent.to_string(context.config));
578 result.push_str(&where_clause_str);
580 match context.config.item_brace_style() {
581 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
582 BraceStyle::AlwaysNextLine => result.push_str(&sep),
583 BraceStyle::PreferSameLine => result.push(' '),
584 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
585 result.push_str(&sep);
593 let snippet = context.snippet(item.span);
594 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
596 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
597 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
598 visitor.block_indent = offset.block_only().block_indent(context.config);
599 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
601 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
603 visitor.visit_impl_item(item);
606 visitor.format_missing(item.span.hi - BytePos(1));
608 let inner_indent_str = visitor.block_indent.to_string(context.config);
609 let outer_indent_str = offset.block_only().to_string(context.config);
612 result.push_str(&inner_indent_str);
613 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
615 result.push_str(&outer_indent_str);
618 if result.chars().last().unwrap() == '{' {
619 result.push_str(&sep);
629 fn is_impl_single_line(
630 context: &RewriteContext,
633 where_clause_str: &str,
636 let snippet = context.snippet(item.span);
637 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
640 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n') &&
641 result.len() + where_clause_str.len() <= context.config.max_width() &&
642 !contains_comment(&snippet[open_pos..]),
646 fn format_impl_ref_and_type(
647 context: &RewriteContext,
650 ) -> Option<String> {
651 if let ast::ItemKind::Impl(
661 let mut result = String::with_capacity(128);
663 result.push_str(&format_visibility(&item.vis));
664 result.push_str(&format_defaultness(defaultness));
665 result.push_str(format_unsafety(unsafety));
666 result.push_str("impl");
668 let lo = context.codemap.span_after(item.span, "impl");
669 let hi = match *trait_ref {
670 Some(ref tr) => tr.path.span.lo,
671 None => self_ty.span.lo,
673 let shape = try_opt!(generics_shape_from_config(
675 Shape::indented(offset + last_line_width(&result), context.config),
678 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
679 let generics_str = try_opt!(rewrite_generics_inner(
687 let polarity_str = if polarity == ast::ImplPolarity::Negative {
693 if let Some(ref trait_ref) = *trait_ref {
694 let result_len = result.len();
695 if let Some(trait_ref_str) = rewrite_trait_ref(
704 result.push_str(&trait_ref_str);
706 let generics_str = try_opt!(rewrite_generics_inner(
713 result.push_str(&try_opt!(rewrite_trait_ref(
724 result.push_str(&generics_str);
727 // Try to put the self type in a single line.
729 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
730 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
731 // If there is no where clause adapt budget for type formatting to take space and curly
732 // brace into account.
733 match context.config.item_brace_style() {
734 BraceStyle::AlwaysNextLine => 0,
740 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
741 // 1 = space before the type.
745 .checked_sub(used_space + 1)
747 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
748 if !self_ty_str.contains('\n') {
749 if trait_ref.is_some() {
750 result.push_str(" for ");
754 result.push_str(&self_ty_str);
759 // Couldn't fit the self type on a single line, put it on a new line.
761 // Add indentation of one additional tab.
762 let new_line_offset = offset.block_indent(context.config);
763 result.push_str(&new_line_offset.to_string(context.config));
764 if trait_ref.is_some() {
765 result.push_str("for ");
767 let budget = context.config.max_width() - last_line_width(&result);
768 let type_offset = match context.config.where_style() {
769 Style::Legacy => new_line_offset + trait_ref_overhead,
770 Style::Rfc => new_line_offset,
772 result.push_str(&*try_opt!(
773 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
781 fn rewrite_trait_ref(
782 context: &RewriteContext,
783 trait_ref: &ast::TraitRef,
789 ) -> Option<String> {
790 // 1 = space between generics and trait_ref
791 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
792 let shape = Shape::indented(offset + used_space, context.config);
793 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
794 if !(retry && trait_ref_str.contains('\n')) {
803 // We could not make enough space for trait_ref, so put it on new line.
805 let offset = offset.block_indent(context.config);
806 let shape = Shape::indented(offset, context.config);
807 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
811 &offset.to_string(context.config),
820 pub fn format_struct(
821 context: &RewriteContext,
824 vis: &ast::Visibility,
825 struct_def: &ast::VariantData,
826 generics: Option<&ast::Generics>,
829 one_line_width: Option<usize>,
830 ) -> Option<String> {
832 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
833 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
843 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
857 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
858 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
861 let mut result = String::with_capacity(128);
862 let header = format!(
864 format_visibility(&item.vis),
865 format_unsafety(unsafety),
869 result.push_str(&header);
871 let body_lo = context.codemap.span_after(item.span, "{");
873 let shape = Shape::indented(offset + last_line_width(&result), context.config);
874 let generics_str = try_opt!(rewrite_generics(
878 mk_sp(item.span.lo, body_lo),
880 result.push_str(&generics_str);
882 let trait_bound_str = try_opt!(rewrite_trait_bounds(
885 Shape::indented(offset, context.config),
887 // If the trait, generics, and trait bound cannot fit on the same line,
888 // put the trait bounds on an indented new line
889 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
890 context.config.comment_width()
893 let trait_indent = offset.block_only().block_indent(context.config);
894 result.push_str(&trait_indent.to_string(context.config));
896 result.push_str(&trait_bound_str);
898 let has_body = !trait_items.is_empty();
900 let where_density = if (context.config.where_density() == Density::Compressed &&
901 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
902 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
903 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
904 !result.contains('\n'))
911 let where_budget = try_opt!(
915 .checked_sub(last_line_width(&result))
917 let pos_before_where = if type_param_bounds.is_empty() {
918 generics.where_clause.span.lo
920 type_param_bounds[type_param_bounds.len() - 1].span().hi
922 let option = WhereClauseOption::snuggled(&generics_str);
923 let where_clause_str = try_opt!(rewrite_where_clause(
925 &generics.where_clause,
926 context.config.item_brace_style(),
927 Shape::legacy(where_budget, offset.block_only()),
934 // If the where clause cannot fit on the same line,
935 // put the where clause on a new line
936 if !where_clause_str.contains('\n') &&
937 last_line_width(&result) + where_clause_str.len() + offset.width() >
938 context.config.comment_width()
941 let width = offset.block_indent + context.config.tab_spaces() - 1;
942 let where_indent = Indent::new(0, width);
943 result.push_str(&where_indent.to_string(context.config));
945 result.push_str(&where_clause_str);
947 if generics.where_clause.predicates.is_empty() {
948 let item_snippet = context.snippet(item.span);
949 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
951 let comment_hi = body_lo - BytePos(1);
952 let comment_lo = item.span.lo + BytePos(lo as u32);
953 if comment_lo < comment_hi {
954 match recover_missing_comment_in_span(
955 mk_sp(comment_lo, comment_hi),
956 Shape::indented(offset, context.config),
958 last_line_width(&result),
960 Some(ref missing_comment) if !missing_comment.is_empty() => {
961 result.push_str(missing_comment);
969 match context.config.item_brace_style() {
970 _ if last_line_contains_single_line_comment(&result) => {
972 result.push_str(&offset.to_string(context.config));
974 BraceStyle::AlwaysNextLine => {
976 result.push_str(&offset.to_string(context.config));
978 BraceStyle::PreferSameLine => result.push(' '),
979 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
980 (!trait_items.is_empty() || result.contains('\n'))
983 result.push_str(&offset.to_string(context.config));
990 let snippet = context.snippet(item.span);
991 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
993 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
994 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
995 visitor.block_indent = offset.block_only().block_indent(context.config);
996 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
998 for item in trait_items {
999 visitor.visit_trait_item(item);
1002 visitor.format_missing(item.span.hi - BytePos(1));
1004 let inner_indent_str = visitor.block_indent.to_string(context.config);
1005 let outer_indent_str = offset.block_only().to_string(context.config);
1008 result.push_str(&inner_indent_str);
1009 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1011 result.push_str(&outer_indent_str);
1012 } else if result.contains('\n') {
1023 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1024 format!("{};", format_header(item_name, ident, vis))
1027 pub fn format_struct_struct(
1028 context: &RewriteContext,
1031 vis: &ast::Visibility,
1032 fields: &[ast::StructField],
1033 generics: Option<&ast::Generics>,
1036 one_line_width: Option<usize>,
1037 ) -> Option<String> {
1038 let mut result = String::with_capacity(1024);
1040 let header_str = format_header(item_name, ident, vis);
1041 result.push_str(&header_str);
1043 let body_lo = context.codemap.span_after(span, "{");
1045 let generics_str = match generics {
1046 Some(g) => try_opt!(format_generics(
1051 context.config.item_brace_style(),
1054 mk_sp(span.lo, body_lo),
1055 last_line_width(&result),
1058 // 3 = ` {}`, 2 = ` {`.
1059 let overhead = if fields.is_empty() { 3 } else { 2 };
1060 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1061 !fields.is_empty()) ||
1065 .checked_sub(result.len())
1066 .unwrap_or(0) < overhead
1068 format!("\n{}{{", offset.block_only().to_string(context.config))
1075 let overhead = if fields.is_empty() { 1 } else { 0 };
1076 let max_len = context
1079 .checked_sub(offset.width())
1081 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1083 result.push_str(&offset.to_string(context.config));
1084 result.push_str(&generics_str.trim_left());
1086 result.push_str(&generics_str);
1089 if fields.is_empty() {
1090 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1091 if snippet.trim().is_empty() {
1093 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1095 result.push_str(&snippet.trim_right());
1097 result.push_str(&offset.to_string(context.config));
1099 result.push_str(&snippet);
1102 return Some(result);
1106 let one_line_budget = context
1109 .checked_sub(result.len() + 3 + offset.width())
1111 let one_line_budget =
1112 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1114 let items_str = try_opt!(rewrite_with_alignment(
1117 Shape::indented(offset, context.config),
1118 mk_sp(body_lo, span.hi),
1122 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1123 Some(format!("{} {} }}", result, items_str))
1129 .block_indent(context.config)
1130 .to_string(context.config),
1132 offset.to_string(context.config)
1137 fn format_tuple_struct(
1138 context: &RewriteContext,
1141 vis: &ast::Visibility,
1142 fields: &[ast::StructField],
1143 generics: Option<&ast::Generics>,
1146 ) -> Option<String> {
1147 let mut result = String::with_capacity(1024);
1149 let header_str = format_header(item_name, ident, vis);
1150 result.push_str(&header_str);
1152 let body_lo = if fields.is_empty() {
1153 context.codemap.span_after(span, "(")
1157 let body_hi = if fields.is_empty() {
1158 context.codemap.span_after(span, ")")
1160 // This is a dirty hack to work around a missing `)` from the span of the last field.
1161 let last_arg_span = fields[fields.len() - 1].span;
1162 if context.snippet(last_arg_span).ends_with(")") {
1167 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1171 let where_clause_str = match generics {
1173 let budget = context.budget(last_line_width(&header_str));
1174 let shape = Shape::legacy(budget, offset);
1175 let g_span = mk_sp(span.lo, body_lo);
1176 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1177 result.push_str(&generics_str);
1179 let where_budget = context.budget(last_line_width(&result));
1180 let option = WhereClauseOption::new(true, false);
1181 try_opt!(rewrite_where_clause(
1183 &generics.where_clause,
1184 context.config.item_brace_style(),
1185 Shape::legacy(where_budget, offset.block_only()),
1186 Density::Compressed,
1193 None => "".to_owned(),
1196 if fields.is_empty() {
1198 let used_width = last_line_used_width(&result, offset.width()) + 3;
1199 if used_width > context.config.max_width() {
1201 result.push_str(&offset
1202 .block_indent(context.config)
1203 .to_string(context.config))
1206 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1207 if snippet.is_empty() {
1209 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1210 result.push_str(&snippet.trim_right());
1212 result.push_str(&offset.to_string(context.config));
1214 result.push_str(&snippet);
1219 let body = try_opt!(
1223 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1225 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1226 context.config.fn_call_width(),
1230 result.push_str(&body);
1233 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1234 (result.contains('\n') ||
1235 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1236 context.config.max_width())
1238 // We need to put the where clause on a new line, but we didn't
1239 // know that earlier, so the where clause will not be indented properly.
1241 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1242 .to_string(context.config));
1244 result.push_str(&where_clause_str);
1249 pub fn rewrite_type_alias(
1250 context: &RewriteContext,
1254 generics: &ast::Generics,
1255 vis: &ast::Visibility,
1257 ) -> Option<String> {
1258 let mut result = String::with_capacity(128);
1260 result.push_str(&format_visibility(vis));
1261 result.push_str("type ");
1262 result.push_str(&ident.to_string());
1265 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1266 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1267 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1268 result.push_str(&generics_str);
1270 let where_budget = try_opt!(
1274 .checked_sub(last_line_width(&result))
1276 let option = WhereClauseOption::snuggled(&result);
1277 let where_clause_str = try_opt!(rewrite_where_clause(
1279 &generics.where_clause,
1280 context.config.item_brace_style(),
1281 Shape::legacy(where_budget, indent),
1282 context.config.where_density(),
1288 result.push_str(&where_clause_str);
1289 if where_clause_str.is_empty() {
1290 result.push_str(" = ");
1292 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1295 let line_width = last_line_width(&result);
1296 // This checked_sub may fail as the extra space after '=' is not taken into account
1297 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1298 let budget = context
1301 .checked_sub(indent.width() + line_width + ";".len())
1303 let type_indent = indent + line_width;
1304 // Try to fit the type on the same line
1305 let ty_str = try_opt!(
1306 ty.rewrite(context, Shape::legacy(budget, type_indent))
1308 // The line was too short, try to put the type on the next line
1310 // Remove the space after '='
1312 let type_indent = indent.block_indent(context.config);
1314 result.push_str(&type_indent.to_string(context.config));
1315 let budget = try_opt!(
1319 .checked_sub(type_indent.width() + ";".len())
1321 ty.rewrite(context, Shape::legacy(budget, type_indent))
1324 result.push_str(&ty_str);
1325 result.push_str(";");
1329 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1331 if config.space_before_type_annotation() {
1336 if config.space_after_type_annotation_colon() {
1344 pub fn rewrite_struct_field_prefix(
1345 context: &RewriteContext,
1346 field: &ast::StructField,
1347 ) -> Option<String> {
1348 let vis = format_visibility(&field.vis);
1349 let type_annotation_spacing = type_annotation_spacing(context.config);
1350 Some(match field.ident {
1351 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1352 None => format!("{}", vis),
1356 fn rewrite_struct_field_type(
1357 context: &RewriteContext,
1358 last_line_width: usize,
1359 field: &ast::StructField,
1362 ) -> Option<String> {
1363 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1366 .rewrite(context, ty_shape)
1367 .map(|ty| format!("{}{}", spacing, ty))
1370 impl Rewrite for ast::StructField {
1371 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1372 rewrite_struct_field(context, self, shape, 0)
1376 pub fn rewrite_struct_field(
1377 context: &RewriteContext,
1378 field: &ast::StructField,
1380 lhs_max_width: usize,
1381 ) -> Option<String> {
1382 if contains_skip(&field.attrs) {
1383 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1384 return wrap_str(span, context.config.max_width(), shape);
1387 let type_annotation_spacing = type_annotation_spacing(context.config);
1388 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1390 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1391 let attrs_extendable = attrs_str.is_empty() ||
1392 (context.config.attributes_on_same_line_as_field() && is_attributes_extendable(&attrs_str));
1393 let missing_span = if field.attrs.is_empty() {
1394 mk_sp(field.span.lo, field.span.lo)
1396 mk_sp(field.attrs.last().unwrap().span.hi, field.span.lo)
1398 let mut spacing = String::from(if field.ident.is_some() {
1399 type_annotation_spacing.1
1403 // Try to put everything on a single line.
1404 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1412 let overhead = last_line_width(&attr_prefix);
1413 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1414 for _ in 0..lhs_offset {
1417 // In this extreme case we will be missing a space betweeen an attribute and a field.
1418 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1421 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1422 if let Some(ref ty) = ty_rewritten {
1423 if !ty.contains('\n') {
1424 return Some(attr_prefix + &ty);
1428 // We must use multiline.
1429 let last_line_width = last_line_width(&prefix);
1430 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1432 let type_offset = shape.indent.block_indent(context.config);
1433 let rewrite_type_in_next_line = || {
1436 .rewrite(context, Shape::indented(type_offset, context.config))
1439 let field_str = match ty_rewritten {
1440 // If we start from the next line and type fits in a single line, then do so.
1441 Some(ref ty) => match rewrite_type_in_next_line() {
1442 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1445 type_offset.to_string(&context.config),
1451 let ty = try_opt!(rewrite_type_in_next_line());
1455 type_offset.to_string(&context.config),
1460 combine_strs_with_missing_comments(
1470 pub fn rewrite_static(
1472 vis: &ast::Visibility,
1475 mutability: ast::Mutability,
1476 expr_opt: Option<&ptr::P<ast::Expr>>,
1479 context: &RewriteContext,
1480 ) -> Option<String> {
1481 let colon = colon_spaces(
1482 context.config.space_before_type_annotation(),
1483 context.config.space_after_type_annotation_colon(),
1485 let prefix = format!(
1487 format_visibility(vis),
1489 format_mutability(mutability),
1494 let ty_str = try_opt!(ty.rewrite(
1497 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1501 if let Some(expr) = expr_opt {
1502 let lhs = format!("{}{} =", prefix, ty_str);
1504 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1509 Shape::legacy(remaining_width, offset.block_only()),
1511 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1513 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1515 Some(format!("{}{};", prefix, ty_str))
1519 pub fn rewrite_associated_type(
1521 ty_opt: Option<&ptr::P<ast::Ty>>,
1522 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1523 context: &RewriteContext,
1525 ) -> Option<String> {
1526 let prefix = format!("type {}", ident);
1528 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1530 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1531 let bounds: &[_] = ty_param_bounds;
1532 let bound_str = try_opt!(
1535 .map(|ty_bound| ty_bound.rewrite(context, shape))
1536 .collect::<Option<Vec<_>>>()
1538 if bounds.len() > 0 {
1539 format!(": {}", join_bounds(context, shape, &bound_str))
1547 if let Some(ty) = ty_opt {
1548 let ty_str = try_opt!(ty.rewrite(
1551 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1552 indent.block_only(),
1555 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1557 Some(format!("{}{};", prefix, type_bounds_str))
1561 pub fn rewrite_associated_impl_type(
1563 defaultness: ast::Defaultness,
1564 ty_opt: Option<&ptr::P<ast::Ty>>,
1565 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1566 context: &RewriteContext,
1568 ) -> Option<String> {
1569 let result = try_opt!(rewrite_associated_type(
1572 ty_param_bounds_opt,
1578 ast::Defaultness::Default => Some(format!("default {}", result)),
1583 impl Rewrite for ast::FunctionRetTy {
1584 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1586 ast::FunctionRetTy::Default(_) => Some(String::new()),
1587 ast::FunctionRetTy::Ty(ref ty) => {
1588 let inner_width = try_opt!(shape.width.checked_sub(3));
1589 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1590 .map(|r| format!("-> {}", r))
1596 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1598 ast::TyKind::Infer => {
1599 let original = context.snippet(ty.span);
1606 impl Rewrite for ast::Arg {
1607 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1608 if is_named_arg(self) {
1609 let mut result = try_opt!(
1611 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1614 if !is_empty_infer(context, &*self.ty) {
1615 if context.config.space_before_type_annotation() {
1616 result.push_str(" ");
1618 result.push_str(":");
1619 if context.config.space_after_type_annotation_colon() {
1620 result.push_str(" ");
1622 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1623 let ty_str = try_opt!(self.ty.rewrite(
1625 Shape::legacy(max_width, shape.indent + result.len()),
1627 result.push_str(&ty_str);
1632 self.ty.rewrite(context, shape)
1637 fn rewrite_explicit_self(
1638 explicit_self: &ast::ExplicitSelf,
1640 context: &RewriteContext,
1641 ) -> Option<String> {
1642 match explicit_self.node {
1643 ast::SelfKind::Region(lt, m) => {
1644 let mut_str = format_mutability(m);
1647 let lifetime_str = try_opt!(l.rewrite(
1649 Shape::legacy(context.config.max_width(), Indent::empty()),
1651 Some(format!("&{} {}self", lifetime_str, mut_str))
1653 None => Some(format!("&{}self", mut_str)),
1656 ast::SelfKind::Explicit(ref ty, _) => {
1657 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1659 let mutability = explicit_self_mutability(&args[0]);
1660 let type_str = try_opt!(ty.rewrite(
1662 Shape::legacy(context.config.max_width(), Indent::empty()),
1667 format_mutability(mutability),
1671 ast::SelfKind::Value(_) => {
1672 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1674 let mutability = explicit_self_mutability(&args[0]);
1676 Some(format!("{}self", format_mutability(mutability)))
1681 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1682 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1683 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1684 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1691 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1692 if is_named_arg(arg) {
1699 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1701 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1702 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1703 _ => arg.ty.span.hi,
1707 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1708 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1709 ident.node != symbol::keywords::Invalid.ident()
1715 // Return type is (result, force_new_line_for_brace)
1717 context: &RewriteContext,
1721 generics: &ast::Generics,
1722 unsafety: ast::Unsafety,
1723 constness: ast::Constness,
1724 defaultness: ast::Defaultness,
1726 vis: &ast::Visibility,
1728 newline_brace: bool,
1731 ) -> Option<(String, bool)> {
1732 let mut force_new_line_for_brace = false;
1734 let where_clause = &generics.where_clause;
1736 let mut result = String::with_capacity(1024);
1737 // Vis defaultness constness unsafety abi.
1738 result.push_str(&*format_visibility(vis));
1739 result.push_str(format_defaultness(defaultness));
1740 result.push_str(format_constness(constness));
1741 result.push_str(format_unsafety(unsafety));
1742 if abi != abi::Abi::Rust {
1743 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1747 result.push_str("fn ");
1748 result.push_str(&ident.to_string());
1751 let overhead = if has_braces && !newline_brace {
1758 let used_width = last_line_used_width(&result, indent.width());
1759 let one_line_budget = context
1762 .checked_sub(used_width + overhead)
1765 width: one_line_budget,
1769 let g_span = mk_sp(span.lo, fd.output.span().lo);
1770 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1771 result.push_str(&generics_str);
1773 let snuggle_angle_bracket = generics_str
1776 .map_or(false, |l| l.trim_left().len() == 1);
1778 // Note that the width and indent don't really matter, we'll re-layout the
1779 // return type later anyway.
1780 let ret_str = try_opt!(
1782 .rewrite(&context, Shape::indented(indent, context.config))
1785 let multi_line_ret_str = ret_str.contains('\n');
1786 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1789 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1800 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1806 // Check if vertical layout was forced.
1807 if one_line_budget == 0 {
1808 if snuggle_angle_bracket {
1811 if context.config.fn_args_paren_newline() {
1813 result.push_str(&arg_indent.to_string(context.config));
1814 if context.config.fn_args_layout() == IndentStyle::Visual {
1815 arg_indent = arg_indent + 1; // extra space for `(`
1819 result.push_str("(");
1820 if context.config.fn_args_layout() == IndentStyle::Visual {
1822 result.push_str(&arg_indent.to_string(context.config));
1829 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1833 // A conservative estimation, to goal is to be over all parens in generics
1834 let args_start = generics
1837 .map_or(span.lo, |tp| end_typaram(tp));
1838 let args_end = if fd.inputs.is_empty() {
1839 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1841 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1842 context.codemap.span_after(last_span, ")")
1844 let args_span = mk_sp(
1845 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1848 let arg_str = try_opt!(rewrite_args(
1851 fd.get_self().as_ref(),
1858 generics_str.contains('\n'),
1861 let put_args_in_block = match context.config.fn_args_layout() {
1862 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1864 } && !fd.inputs.is_empty();
1866 let mut args_last_line_contains_comment = false;
1867 if put_args_in_block {
1868 arg_indent = indent.block_indent(context.config);
1870 result.push_str(&arg_indent.to_string(context.config));
1871 result.push_str(&arg_str);
1873 result.push_str(&indent.to_string(context.config));
1876 result.push_str(&arg_str);
1877 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1878 // Put the closing brace on the next line if it overflows the max width.
1880 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1883 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1886 // If the last line of args contains comment, we cannot put the closing paren
1887 // on the same line.
1891 .map_or(false, |last_line| last_line.contains("//"))
1893 args_last_line_contains_comment = true;
1895 result.push_str(&arg_indent.to_string(context.config));
1901 if let ast::FunctionRetTy::Ty(..) = fd.output {
1902 let ret_should_indent = match context.config.fn_args_layout() {
1903 // If our args are block layout then we surely must have space.
1904 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1905 _ if args_last_line_contains_comment => false,
1906 _ if result.contains('\n') || multi_line_ret_str => true,
1908 // If the return type would push over the max width, then put the return type on
1909 // a new line. With the +1 for the signature length an additional space between
1910 // the closing parenthesis of the argument and the arrow '->' is considered.
1911 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1913 // If there is no where clause, take into account the space after the return type
1915 if where_clause.predicates.is_empty() {
1919 sig_length > context.config.max_width()
1922 let ret_indent = if ret_should_indent {
1923 let indent = match context.config.fn_return_indent() {
1924 ReturnIndent::WithWhereClause => indent + 4,
1925 // Aligning with non-existent args looks silly.
1926 _ if arg_str.is_empty() => {
1927 force_new_line_for_brace = true;
1930 // FIXME: we might want to check that using the arg indent
1931 // doesn't blow our budget, and if it does, then fallback to
1932 // the where clause indent.
1937 result.push_str(&indent.to_string(context.config));
1941 Indent::new(indent.block_indent, last_line_width(&result))
1944 if multi_line_ret_str || ret_should_indent {
1945 // Now that we know the proper indent and width, we need to
1946 // re-layout the return type.
1947 let ret_str = try_opt!(
1949 .rewrite(context, Shape::indented(ret_indent, context.config))
1951 result.push_str(&ret_str);
1953 result.push_str(&ret_str);
1956 // Comment between return type and the end of the decl.
1957 let snippet_lo = fd.output.span().hi;
1958 if where_clause.predicates.is_empty() {
1959 let snippet_hi = span.hi;
1960 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1961 // Try to preserve the layout of the original snippet.
1962 let original_starts_with_newline = snippet
1964 .map_or(false, |i| snippet[i..].starts_with('\n'));
1965 let original_ends_with_newline = snippet
1966 .rfind(|c| c != ' ')
1967 .map_or(false, |i| snippet[i..].ends_with('\n'));
1968 let snippet = snippet.trim();
1969 if !snippet.is_empty() {
1970 result.push(if original_starts_with_newline {
1975 result.push_str(snippet);
1976 if original_ends_with_newline {
1977 force_new_line_for_brace = true;
1983 let should_compress_where = match context.config.where_density() {
1984 Density::Compressed => !result.contains('\n'),
1985 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1989 let pos_before_where = match fd.output {
1990 ast::FunctionRetTy::Default(..) => args_span.hi,
1991 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
1994 if where_clause.predicates.len() == 1 && should_compress_where {
1995 let budget = context
1998 .checked_sub(last_line_used_width(&result, indent.width()))
2000 if let Some(where_clause_str) = rewrite_where_clause(
2003 context.config.fn_brace_style(),
2004 Shape::legacy(budget, indent),
2005 Density::Compressed,
2009 WhereClauseOption::compressed(),
2011 result.push_str(&where_clause_str);
2012 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2013 return Some((result, force_new_line_for_brace));
2017 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2018 let where_clause_str = try_opt!(rewrite_where_clause(
2021 context.config.fn_brace_style(),
2022 Shape::indented(indent, context.config),
2029 // If there are neither where clause nor return type, we may be missing comments between
2031 if where_clause_str.is_empty() {
2032 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2033 match recover_missing_comment_in_span(
2034 mk_sp(args_span.hi, ret_span.hi),
2037 last_line_width(&result),
2039 Some(ref missing_comment) if !missing_comment.is_empty() => {
2040 result.push_str(missing_comment);
2041 force_new_line_for_brace = true;
2048 result.push_str(&where_clause_str);
2050 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2051 return Some((result, force_new_line_for_brace));
2054 struct WhereClauseOption {
2055 suppress_comma: bool, // Force no trailing comma
2056 snuggle: bool, // Do not insert newline before `where`
2057 compress_where: bool, // Try single line where clause instead of vertical layout
2060 impl WhereClauseOption {
2061 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2063 suppress_comma: suppress_comma,
2065 compress_where: false,
2069 pub fn compressed() -> WhereClauseOption {
2071 suppress_comma: true,
2073 compress_where: true,
2077 pub fn snuggled(current: &str) -> WhereClauseOption {
2079 suppress_comma: false,
2080 snuggle: trimmed_last_line_width(current) == 1,
2081 compress_where: false,
2087 context: &RewriteContext,
2089 explicit_self: Option<&ast::ExplicitSelf>,
2090 one_line_budget: usize,
2091 multi_line_budget: usize,
2096 generics_str_contains_newline: bool,
2097 ) -> Option<String> {
2098 let mut arg_item_strs = try_opt!(
2101 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2103 .collect::<Option<Vec<_>>>()
2106 // Account for sugary self.
2107 // FIXME: the comment for the self argument is dropped. This is blocked
2108 // on rust issue #27522.
2109 let min_args = explicit_self
2110 .and_then(|explicit_self| {
2111 rewrite_explicit_self(explicit_self, args, context)
2113 .map_or(1, |self_str| {
2114 arg_item_strs[0] = self_str;
2118 // Comments between args.
2119 let mut arg_items = Vec::new();
2121 arg_items.push(ListItem::from_str(""));
2124 // FIXME(#21): if there are no args, there might still be a comment, but
2125 // without spans for the comment or parens, there is no chance of
2126 // getting it right. You also don't get to put a comment on self, unless
2128 if args.len() >= min_args || variadic {
2129 let comment_span_start = if min_args == 2 {
2130 let second_arg_start = if arg_has_pattern(&args[1]) {
2135 let reduced_span = mk_sp(span.lo, second_arg_start);
2137 context.codemap.span_after_last(reduced_span, ",")
2142 enum ArgumentKind<'a> {
2143 Regular(&'a ast::Arg),
2147 let variadic_arg = if variadic {
2148 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2149 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2150 Some(ArgumentKind::Variadic(variadic_start))
2155 let more_items = itemize_list(
2157 args[min_args - 1..]
2159 .map(ArgumentKind::Regular)
2160 .chain(variadic_arg),
2163 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2164 ArgumentKind::Variadic(start) => start,
2167 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2168 ArgumentKind::Variadic(start) => start + BytePos(3),
2171 ArgumentKind::Regular(..) => None,
2172 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2179 arg_items.extend(more_items);
2182 let fits_in_one_line = !generics_str_contains_newline &&
2183 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2185 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2186 item.item = Some(arg);
2189 let last_line_ends_with_comment = arg_items
2192 .and_then(|item| item.post_comment.as_ref())
2193 .map_or(false, |s| s.trim().starts_with("//"));
2195 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2196 IndentStyle::Block if fits_in_one_line => {
2197 (indent.block_indent(context.config), SeparatorTactic::Never)
2199 IndentStyle::Block => (
2200 indent.block_indent(context.config),
2201 context.config.trailing_comma(),
2203 IndentStyle::Visual if last_line_ends_with_comment => {
2204 (arg_indent, context.config.trailing_comma())
2206 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2209 let tactic = definitive_tactic(
2211 context.config.fn_args_density().to_list_tactic(),
2215 let budget = match tactic {
2216 DefinitiveListTactic::Horizontal => one_line_budget,
2217 _ => multi_line_budget,
2220 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2222 let fmt = ListFormatting {
2225 trailing_separator: if variadic {
2226 SeparatorTactic::Never
2230 separator_place: SeparatorPlace::Back,
2231 shape: Shape::legacy(budget, indent),
2232 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2233 preserve_newline: true,
2234 config: context.config,
2237 write_list(&arg_items, &fmt)
2240 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2241 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2242 ident.node != symbol::keywords::Invalid.ident()
2248 fn compute_budgets_for_args(
2249 context: &RewriteContext,
2253 newline_brace: bool,
2255 force_vertical_layout: bool,
2256 ) -> Option<((usize, usize, Indent))> {
2258 "compute_budgets_for_args {} {:?}, {}, {}",
2264 // Try keeping everything on the same line.
2265 if !result.contains('\n') && !force_vertical_layout {
2266 // 2 = `()`, 3 = `() `, space is before ret_string.
2267 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2268 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2278 let one_line_budget = context
2281 .checked_sub(used_space)
2284 if one_line_budget > 0 {
2286 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2287 IndentStyle::Block => {
2288 let indent = indent.block_indent(context.config);
2290 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2293 IndentStyle::Visual => {
2294 let indent = indent + result.len() + 1;
2295 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2297 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2302 return Some((one_line_budget, multi_line_budget, indent));
2306 // Didn't work. we must force vertical layout and put args on a newline.
2307 let new_indent = indent.block_indent(context.config);
2308 let used_space = match context.config.fn_args_layout() {
2310 IndentStyle::Block => new_indent.width() + 1,
2311 // Account for `)` and possibly ` {`.
2312 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2314 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2315 Some((0, max_space, new_indent))
2318 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2319 match (config.fn_brace_style(), config.where_density()) {
2320 (BraceStyle::AlwaysNextLine, _) => true,
2321 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2322 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2323 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2328 fn rewrite_generics(
2329 context: &RewriteContext,
2330 generics: &ast::Generics,
2333 ) -> Option<String> {
2334 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2335 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2336 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2337 rewrite_generics_inner(context, generics, g_shape, 0, span)
2341 fn rewrite_generics_inner(
2342 context: &RewriteContext,
2343 generics: &ast::Generics,
2345 one_line_width: usize,
2347 ) -> Option<String> {
2348 // FIXME: convert bounds to where clauses where they get too big or if
2349 // there is a where clause at all.
2350 let lifetimes: &[_] = &generics.lifetimes;
2351 let tys: &[_] = &generics.ty_params;
2352 if lifetimes.is_empty() && tys.is_empty() {
2353 return Some(String::new());
2356 // Strings for the generics.
2357 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2358 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2360 // Extract comments between generics.
2361 let lt_spans = lifetimes.iter().map(|l| {
2362 let hi = if l.bounds.is_empty() {
2365 l.bounds[l.bounds.len() - 1].span.hi
2367 mk_sp(l.lifetime.span.lo, hi)
2369 let ty_spans = tys.iter().map(|ty| ty.span());
2371 let items = itemize_list(
2373 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2377 // FIXME: don't clone
2378 |&(_, ref str)| str.clone(),
2379 context.codemap.span_after(span, "<"),
2383 format_generics_item_list(context, items, shape, one_line_width)
2386 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2387 match config.generics_indent() {
2388 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2389 IndentStyle::Block => {
2393 .block_indent(config.tab_spaces())
2394 .with_max_width(config)
2400 pub fn format_generics_item_list<I>(
2401 context: &RewriteContext,
2404 one_line_budget: usize,
2407 I: Iterator<Item = ListItem>,
2409 let item_vec = items.collect::<Vec<_>>();
2411 let tactic = definitive_tactic(
2413 ListTactic::HorizontalVertical,
2417 let fmt = ListFormatting {
2420 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2421 SeparatorTactic::Never
2423 context.config.trailing_comma()
2425 separator_place: SeparatorPlace::Back,
2427 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2428 preserve_newline: true,
2429 config: context.config,
2432 let list_str = try_opt!(write_list(&item_vec, &fmt));
2434 Some(wrap_generics_with_angle_brackets(
2441 pub fn wrap_generics_with_angle_brackets(
2442 context: &RewriteContext,
2444 list_offset: Indent,
2446 if context.config.generics_indent() == IndentStyle::Block &&
2447 (list_str.contains('\n') || list_str.ends_with(','))
2451 list_offset.to_string(context.config),
2454 .block_unindent(context.config)
2455 .to_string(context.config)
2457 } else if context.config.spaces_within_angle_brackets() {
2458 format!("< {} >", list_str)
2460 format!("<{}>", list_str)
2464 fn rewrite_trait_bounds(
2465 context: &RewriteContext,
2466 type_param_bounds: &ast::TyParamBounds,
2468 ) -> Option<String> {
2469 let bounds: &[_] = type_param_bounds;
2471 if bounds.is_empty() {
2472 return Some(String::new());
2474 let bound_str = try_opt!(
2477 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2478 .collect::<Option<Vec<_>>>()
2480 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2483 fn rewrite_where_clause_rfc_style(
2484 context: &RewriteContext,
2485 where_clause: &ast::WhereClause,
2488 span_end: Option<BytePos>,
2489 span_end_before_where: BytePos,
2490 where_clause_option: WhereClauseOption,
2491 ) -> Option<String> {
2492 let block_shape = shape.block().with_max_width(context.config);
2494 let (span_before, span_after) =
2495 missing_span_before_after_where(span_end_before_where, where_clause);
2496 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2503 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2506 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2509 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2510 // each clause on one line, trailing comma (except if suppress_comma)
2511 let span_start = where_clause.predicates[0].span().lo;
2512 // If we don't have the start of the next span, then use the end of the
2513 // predicates, but that means we miss comments.
2514 let len = where_clause.predicates.len();
2515 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2516 let span_end = span_end.unwrap_or(end_of_preds);
2517 let items = itemize_list(
2519 where_clause.predicates.iter(),
2521 |pred| pred.span().lo,
2522 |pred| pred.span().hi,
2523 |pred| pred.rewrite(context, block_shape),
2528 let comma_tactic = if where_clause_option.suppress_comma {
2529 SeparatorTactic::Never
2531 context.config.trailing_comma()
2534 let fmt = ListFormatting {
2535 tactic: DefinitiveListTactic::Vertical,
2537 trailing_separator: comma_tactic,
2538 separator_place: SeparatorPlace::Back,
2539 shape: clause_shape,
2540 ends_with_newline: true,
2541 preserve_newline: true,
2542 config: context.config,
2544 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2546 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2549 format!("\n{}", shape.indent.to_string(context.config))
2551 let newline_before_where = comment_separator(&comment_before, shape);
2552 let newline_after_where = comment_separator(&comment_after, clause_shape);
2555 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2556 comment_after.is_empty() && !preds_str.contains('\n') &&
2557 6 + preds_str.len() <= shape.width
2561 format!("\n{}", clause_shape.indent.to_string(context.config))
2564 "{}{}{}where{}{}{}{}",
2567 newline_before_where,
2568 newline_after_where,
2575 fn rewrite_where_clause(
2576 context: &RewriteContext,
2577 where_clause: &ast::WhereClause,
2578 brace_style: BraceStyle,
2582 span_end: Option<BytePos>,
2583 span_end_before_where: BytePos,
2584 where_clause_option: WhereClauseOption,
2585 ) -> Option<String> {
2586 if where_clause.predicates.is_empty() {
2587 return Some(String::new());
2590 if context.config.where_style() == Style::Rfc {
2591 return rewrite_where_clause_rfc_style(
2597 span_end_before_where,
2598 where_clause_option,
2602 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2604 let offset = match context.config.where_pred_indent() {
2605 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2606 // 6 = "where ".len()
2607 IndentStyle::Visual => shape.indent + extra_indent + 6,
2609 // FIXME: if where_pred_indent != Visual, then the budgets below might
2610 // be out by a char or two.
2612 let budget = context.config.max_width() - offset.width();
2613 let span_start = where_clause.predicates[0].span().lo;
2614 // If we don't have the start of the next span, then use the end of the
2615 // predicates, but that means we miss comments.
2616 let len = where_clause.predicates.len();
2617 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2618 let span_end = span_end.unwrap_or(end_of_preds);
2619 let items = itemize_list(
2621 where_clause.predicates.iter(),
2623 |pred| pred.span().lo,
2624 |pred| pred.span().hi,
2625 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2630 let item_vec = items.collect::<Vec<_>>();
2631 // FIXME: we don't need to collect here if the where_layout isn't
2632 // HorizontalVertical.
2633 let tactic = definitive_tactic(
2635 context.config.where_layout(),
2640 let mut comma_tactic = context.config.trailing_comma();
2641 // Kind of a hack because we don't usually have trailing commas in where clauses.
2642 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2643 comma_tactic = SeparatorTactic::Never;
2646 let fmt = ListFormatting {
2649 trailing_separator: comma_tactic,
2650 separator_place: SeparatorPlace::Back,
2651 shape: Shape::legacy(budget, offset),
2652 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2653 preserve_newline: true,
2654 config: context.config,
2656 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2658 let end_length = if terminator == "{" {
2659 // If the brace is on the next line we don't need to count it otherwise it needs two
2662 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2663 BraceStyle::PreferSameLine => 2,
2665 } else if terminator == "=" {
2670 if density == Density::Tall || preds_str.contains('\n') ||
2671 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2675 (shape.indent + extra_indent).to_string(context.config),
2679 Some(format!(" where {}", preds_str))
2683 fn missing_span_before_after_where(
2684 before_item_span_end: BytePos,
2685 where_clause: &ast::WhereClause,
2687 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo);
2689 let pos_after_where = where_clause.span.lo + BytePos(5);
2690 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2691 (missing_span_before, missing_span_after)
2694 fn rewrite_comments_before_after_where(
2695 context: &RewriteContext,
2696 span_before_where: Span,
2697 span_after_where: Span,
2699 ) -> Option<(String, String)> {
2700 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2701 let after_comment = try_opt!(rewrite_missing_comment(
2703 shape.block_indent(context.config.tab_spaces()),
2706 Some((before_comment, after_comment))
2709 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2710 format!("{}{}{}", format_visibility(vis), item_name, ident)
2714 context: &RewriteContext,
2715 generics: &ast::Generics,
2718 brace_style: BraceStyle,
2719 force_same_line_brace: bool,
2723 ) -> Option<String> {
2724 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2725 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2727 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2728 let budget = context
2731 .checked_sub(last_line_used_width(&result, offset.width()))
2733 let option = WhereClauseOption::snuggled(&result);
2734 let where_clause_str = try_opt!(rewrite_where_clause(
2736 &generics.where_clause,
2738 Shape::legacy(budget, offset.block_only()),
2745 result.push_str(&where_clause_str);
2746 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2747 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2749 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2750 brace_style != BraceStyle::AlwaysNextLine
2752 let total_used_width = last_line_used_width(&result, used_width);
2753 let remaining_budget = context
2756 .checked_sub(total_used_width)
2758 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2759 // and hence we take the closer into account as well for one line budget.
2760 // We assume that the closer has the same length as the opener.
2761 let overhead = if force_same_line_brace {
2762 1 + opener.len() + opener.len()
2766 let forbid_same_line_brace = overhead > remaining_budget;
2767 if !forbid_same_line_brace && same_line_brace {
2771 result.push_str(&offset.block_only().to_string(context.config));
2773 result.push_str(opener);
2778 impl Rewrite for ast::ForeignItem {
2779 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2780 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2781 // Drop semicolon or it will be interpreted as comment.
2782 // FIXME: this may be a faulty span from libsyntax.
2783 let span = mk_sp(self.span.lo, self.span.hi - BytePos(1));
2785 let item_str = try_opt!(match self.node {
2786 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2793 ast::Unsafety::Normal,
2794 ast::Constness::NotConst,
2795 ast::Defaultness::Final,
2796 // These are not actually rust functions,
2797 // but we format them as such.
2804 ).map(|(s, _)| format!("{};", s))
2806 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2807 // FIXME(#21): we're dropping potential comments in between the
2808 // function keywords here.
2809 let vis = format_visibility(&self.vis);
2810 let mut_str = if is_mutable { "mut " } else { "" };
2811 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2813 let shape = try_opt!(shape.sub_width(1));
2814 ty.rewrite(context, shape).map(|ty_str| {
2815 // 1 = space between prefix and type.
2816 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2819 let nested_indent = shape.indent.block_indent(context.config);
2820 format!("\n{}", nested_indent.to_string(context.config))
2822 format!("{}{}{};", prefix, sep, ty_str)
2827 let missing_span = if self.attrs.is_empty() {
2828 mk_sp(self.span.lo, self.span.lo)
2830 mk_sp(self.attrs[self.attrs.len() - 1].span.hi, self.span.lo)
2832 combine_strs_with_missing_comments(