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::SpanUtils;
21 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
22 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
23 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
24 rewrite_call_inner, ExprType};
25 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
26 ListItem, ListTactic, SeparatorTactic};
27 use rewrite::{Rewrite, RewriteContext};
28 use types::join_bounds;
29 use utils::{colon_spaces, contains_skip, end_typaram, format_defaultness, format_mutability,
30 format_unsafety, format_visibility, last_line_width, mk_sp, semicolon_for_expr,
31 stmt_expr, trim_newlines, trimmed_last_line_width, wrap_str};
32 use vertical::rewrite_with_alignment;
33 use visitor::FmtVisitor;
35 fn type_annotation_separator(config: &Config) -> &str {
37 config.space_before_type_annotation(),
38 config.space_after_type_annotation_colon(),
43 // Statements of the form
44 // let pat: ty = init;
45 impl Rewrite for ast::Local {
46 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
48 "Local::rewrite {:?} {} {:?}",
53 let mut result = "let ".to_owned();
56 let pat_shape = try_opt!(shape.offset_left(4));
58 let pat_shape = try_opt!(pat_shape.sub_width(1));
59 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
60 result.push_str(&pat_str);
62 // String that is placed within the assignment pattern and expression.
64 let mut infix = String::new();
66 if let Some(ref ty) = self.ty {
67 let separator = type_annotation_separator(context.config);
68 let indent = shape.indent + last_line_width(&result) + separator.len();
70 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
71 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
73 infix.push_str(separator);
74 infix.push_str(&rewrite);
77 if self.init.is_some() {
84 result.push_str(&infix);
86 if let Some(ref ex) = self.init {
87 // 1 = trailing semicolon;
88 let nested_shape = try_opt!(shape.sub_width(1));
90 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
98 // TODO convert to using rewrite style rather than visitor
99 // TODO format modules in this style
102 keyword: &'static str,
104 vis: Option<&'a ast::Visibility>,
105 body: Vec<BodyElement<'a>>,
110 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
111 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
114 format!("extern {}", fm.abi)
122 .map(|i| BodyElement::ForeignItem(i))
129 enum BodyElement<'a> {
130 // Stmt(&'a ast::Stmt),
131 // Field(&'a ast::Field),
132 // Variant(&'a ast::Variant),
133 // Item(&'a ast::Item),
134 ForeignItem(&'a ast::ForeignItem),
137 impl<'a> FmtVisitor<'a> {
138 fn format_item(&mut self, item: Item) {
139 self.buffer.push_str(&item.abi);
140 self.buffer.push_str(" ");
142 let snippet = self.snippet(item.span);
143 let brace_pos = snippet.find_uncommented("{").unwrap();
145 self.buffer.push_str("{");
146 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
147 // FIXME: this skips comments between the extern keyword and the opening
149 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
150 self.block_indent = self.block_indent.block_indent(self.config);
152 if item.body.is_empty() {
153 self.format_missing_no_indent(item.span.hi - BytePos(1));
154 self.block_indent = self.block_indent.block_unindent(self.config);
157 .push_str(&self.block_indent.to_string(self.config));
159 for item in &item.body {
160 self.format_body_element(item);
163 self.block_indent = self.block_indent.block_unindent(self.config);
164 self.format_missing_with_indent(item.span.hi - BytePos(1));
168 self.buffer.push_str("}");
169 self.last_pos = item.span.hi;
172 fn format_body_element(&mut self, element: &BodyElement) {
174 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
178 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
179 let item = Item::from_foreign_mod(fm, span, self.config);
180 self.format_item(item);
183 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
184 self.format_missing_with_indent(item.span.lo);
185 // Drop semicolon or it will be interpreted as comment.
186 // FIXME: this may be a faulty span from libsyntax.
187 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
190 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
191 let indent = self.block_indent;
192 let rewrite = rewrite_fn_base(
198 ast::Unsafety::Normal,
199 ast::Constness::NotConst,
200 ast::Defaultness::Final,
201 // These are not actually rust functions,
202 // but we format them as such.
212 Some((new_fn, _)) => {
213 self.buffer.push_str(&new_fn);
214 self.buffer.push_str(";");
216 None => self.format_missing(item.span.hi),
219 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
220 // FIXME(#21): we're dropping potential comments in between the
221 // function keywords here.
222 let vis = format_visibility(&item.vis);
223 let mut_str = if is_mutable { "mut " } else { "" };
224 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
225 let offset = self.block_indent + prefix.len();
227 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
228 let rewrite = ty.rewrite(&self.get_context(), shape);
232 self.buffer.push_str(&prefix);
233 self.buffer.push_str(&result);
234 self.buffer.push_str(";");
236 None => self.format_missing(item.span.hi),
241 self.last_pos = item.span.hi;
249 generics: &ast::Generics,
250 unsafety: ast::Unsafety,
251 constness: ast::Constness,
252 defaultness: ast::Defaultness,
254 vis: &ast::Visibility,
257 ) -> Option<String> {
258 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
259 let context = self.get_context();
261 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
262 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
263 !context.config.fn_empty_single_line();
265 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
282 if force_newline_brace {
283 newline_brace = true;
284 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
285 !result.contains('\n')
287 newline_brace = false;
290 // Prepare for the function body by possibly adding a newline and
292 // FIXME we'll miss anything between the end of the signature and the
293 // start of the body, but we need more spans from the compiler to solve
297 result.push_str(&indent.to_string(self.config));
302 self.single_line_fn(&result, block).or_else(|| Some(result))
305 pub fn rewrite_required_fn(
309 sig: &ast::MethodSig,
311 ) -> Option<String> {
312 // Drop semicolon or it will be interpreted as comment.
313 let span = mk_sp(span.lo, span.hi - BytePos(1));
314 let context = self.get_context();
316 let (mut result, _) = try_opt!(rewrite_fn_base(
324 ast::Defaultness::Final,
326 &ast::Visibility::Inherited,
333 // Re-attach semicolon
339 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
340 if fn_str.contains('\n') {
344 let codemap = self.get_context().codemap;
346 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
347 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
349 return Some(format!("{}{{}}", fn_str));
352 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
354 if let Some(ref stmt) = block.stmts.first() {
355 match stmt_expr(stmt) {
357 let suffix = if semicolon_for_expr(&self.get_context(), e) {
367 Shape::indented(self.block_indent, self.config),
368 ).map(|s| s + suffix)
369 .or_else(|| Some(self.snippet(e.span)))
371 None => stmt.rewrite(
373 Shape::indented(self.block_indent, self.config),
381 if let Some(res) = rewrite {
382 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
383 if !res.contains('\n') && width <= self.config.max_width() {
384 return Some(format!("{}{{ {} }}", fn_str, res));
395 vis: &ast::Visibility,
396 enum_def: &ast::EnumDef,
397 generics: &ast::Generics,
400 let enum_header = format_header("enum ", ident, vis);
401 self.buffer.push_str(&enum_header);
403 let enum_snippet = self.snippet(span);
404 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
405 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
406 let generics_str = format_generics(
411 self.config.item_brace_style(),
412 enum_def.variants.is_empty(),
414 mk_sp(span.lo, body_start),
415 last_line_width(&enum_header),
417 self.buffer.push_str(&generics_str);
419 self.last_pos = body_start;
421 self.block_indent = self.block_indent.block_indent(self.config);
422 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
424 Some(ref body_str) => self.buffer.push_str(body_str),
425 None => if contains_comment(&enum_snippet[brace_pos..]) {
426 self.format_missing_no_indent(span.hi - BytePos(1))
428 self.format_missing(span.hi - BytePos(1))
431 self.block_indent = self.block_indent.block_unindent(self.config);
433 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
435 .push_str(&self.block_indent.to_string(self.config));
437 self.buffer.push_str("}");
438 self.last_pos = span.hi;
441 // Format the body of an enum definition
442 fn format_variant_list(
444 enum_def: &ast::EnumDef,
447 ) -> Option<String> {
448 if enum_def.variants.is_empty() {
451 let mut result = String::with_capacity(1024);
453 let indentation = self.block_indent.to_string(self.config);
454 result.push_str(&indentation);
456 let items = itemize_list(
458 enum_def.variants.iter(),
460 |f| if !f.node.attrs.is_empty() {
461 f.node.attrs[0].span.lo
466 |f| self.format_variant(f),
471 let shape = Shape::indented(self.block_indent, self.config)
474 let fmt = ListFormatting {
475 tactic: DefinitiveListTactic::Vertical,
477 trailing_separator: self.config.trailing_comma(),
479 ends_with_newline: true,
480 preserve_newline: true,
484 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
485 result.push_str(&list);
490 // Variant of an enum.
491 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
492 if contains_skip(&field.node.attrs) {
493 let lo = field.node.attrs[0].span.lo;
494 let span = mk_sp(lo, field.span.hi);
495 return Some(self.snippet(span));
498 let context = self.get_context();
499 let indent = self.block_indent;
500 let mut result = try_opt!(
504 .rewrite(&context, Shape::indented(indent, self.config))
506 if !result.is_empty() {
508 width: context.config.max_width(),
509 indent: self.block_indent,
510 offset: self.block_indent.alignment,
512 let missing_comment = rewrite_missing_comment_on_field(
515 field.node.attrs[field.node.attrs.len() - 1].span.hi,
518 ).unwrap_or(String::new());
519 result.push_str(&missing_comment);
522 let variant_body = match field.node.data {
523 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
524 // FIXME: Should limit the width, as we have a trailing comma
529 &ast::Visibility::Inherited,
534 Some(self.config.struct_variant_width()),
537 ast::VariantData::Unit(..) => {
538 let tag = if let Some(ref expr) = field.node.disr_expr {
539 format!("{} = {}", field.node.name, self.snippet(expr.span))
541 field.node.name.to_string()
546 self.config.max_width(),
547 Shape::indented(indent, self.config),
552 if let Some(variant_str) = variant_body {
553 result.push_str(&variant_str);
562 context: &RewriteContext,
565 where_span_end: Option<BytePos>,
566 ) -> Option<String> {
567 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
568 let mut result = String::new();
569 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
570 result.push_str(&ref_and_type);
572 let where_budget = if result.contains('\n') {
573 context.config.max_width()
578 .checked_sub(last_line_width(&result))
581 let where_clause_str = try_opt!(rewrite_where_clause(
583 &generics.where_clause,
584 context.config.item_brace_style(),
585 Shape::legacy(where_budget, offset.block_only()),
586 context.config.where_density(),
589 last_line_width(&ref_and_type) == 1,
595 if try_opt!(is_impl_single_line(
602 result.push_str(&where_clause_str);
603 if where_clause_str.contains('\n') {
604 let white_space = offset.to_string(context.config);
605 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
607 result.push_str(" {}");
612 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
614 let width = offset.block_indent + context.config.tab_spaces() - 1;
615 let where_indent = Indent::new(0, width);
616 result.push_str(&where_indent.to_string(context.config));
618 result.push_str(&where_clause_str);
620 match context.config.item_brace_style() {
621 BraceStyle::AlwaysNextLine => {
623 result.push_str(&offset.to_string(context.config));
625 BraceStyle::PreferSameLine => result.push(' '),
626 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
628 result.push_str(&offset.to_string(context.config));
636 let snippet = context.snippet(item.span);
637 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
639 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
640 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
641 visitor.block_indent = offset.block_only().block_indent(context.config);
642 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
644 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
646 visitor.visit_impl_item(item);
649 visitor.format_missing(item.span.hi - BytePos(1));
651 let inner_indent_str = visitor.block_indent.to_string(context.config);
652 let outer_indent_str = offset.block_only().to_string(context.config);
655 result.push_str(&inner_indent_str);
656 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
658 result.push_str(&outer_indent_str);
661 if result.chars().last().unwrap() == '{' {
663 result.push_str(&offset.to_string(context.config));
673 fn is_impl_single_line(
674 context: &RewriteContext,
677 where_clause_str: &str,
680 let snippet = context.snippet(item.span);
681 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
684 context.config.impl_empty_single_line() && items.is_empty() &&
685 result.len() + where_clause_str.len() <= context.config.max_width() &&
686 !contains_comment(&snippet[open_pos..]),
690 fn format_impl_ref_and_type(
691 context: &RewriteContext,
694 ) -> Option<String> {
695 if let ast::ItemKind::Impl(
705 let mut result = String::new();
707 result.push_str(&format_visibility(&item.vis));
708 result.push_str(&format_defaultness(defaultness));
709 result.push_str(format_unsafety(unsafety));
710 result.push_str("impl");
712 let lo = context.codemap.span_after(item.span, "impl");
713 let hi = match *trait_ref {
714 Some(ref tr) => tr.path.span.lo,
715 None => self_ty.span.lo,
717 let shape = try_opt!(generics_shape_from_config(
719 Shape::indented(offset + last_line_width(&result), context.config),
722 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
723 let generics_str = try_opt!(rewrite_generics_inner(
731 let polarity_str = if polarity == ast::ImplPolarity::Negative {
737 if let Some(ref trait_ref) = *trait_ref {
738 let result_len = result.len();
739 if let Some(trait_ref_str) = rewrite_trait_ref(
748 result.push_str(&trait_ref_str);
750 let generics_str = try_opt!(rewrite_generics_inner(
757 result.push_str(&try_opt!(rewrite_trait_ref(
768 result.push_str(&generics_str);
771 // Try to put the self type in a single line.
773 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
774 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
775 // If there is no where clause adapt budget for type formatting to take space and curly
776 // brace into account.
777 match context.config.item_brace_style() {
778 BraceStyle::AlwaysNextLine => 0,
784 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
785 // 1 = space before the type.
789 .checked_sub(used_space + 1)
791 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
792 if !self_ty_str.contains('\n') {
793 if trait_ref.is_some() {
794 result.push_str(" for ");
798 result.push_str(&self_ty_str);
803 // Couldn't fit the self type on a single line, put it on a new line.
805 // Add indentation of one additional tab.
806 let new_line_offset = offset.block_indent(context.config);
807 result.push_str(&new_line_offset.to_string(context.config));
808 if trait_ref.is_some() {
809 result.push_str("for ");
811 let budget = context.config.max_width() - last_line_width(&result);
812 let type_offset = match context.config.where_style() {
813 Style::Legacy => new_line_offset + trait_ref_overhead,
814 Style::Rfc => new_line_offset,
816 result.push_str(&*try_opt!(
817 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
825 fn rewrite_trait_ref(
826 context: &RewriteContext,
827 trait_ref: &ast::TraitRef,
833 ) -> Option<String> {
834 // 1 = space between generics and trait_ref
835 let used_space = 1 + polarity_str.len() + if generics_str.contains('\n') {
836 last_line_width(&generics_str)
838 result_len + generics_str.len()
840 let shape = Shape::indented(offset + used_space, context.config);
841 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
842 if !(retry && trait_ref_str.contains('\n')) {
851 // We could not make enough space for trait_ref, so put it on new line.
853 let offset = offset.block_indent(context.config);
854 let shape = Shape::indented(offset, context.config);
855 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
859 &offset.to_string(context.config),
868 pub fn format_struct(
869 context: &RewriteContext,
872 vis: &ast::Visibility,
873 struct_def: &ast::VariantData,
874 generics: Option<&ast::Generics>,
877 one_line_width: Option<usize>,
878 ) -> Option<String> {
880 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
881 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
891 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
905 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
906 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
909 let mut result = String::new();
910 let header = format!(
912 format_visibility(&item.vis),
913 format_unsafety(unsafety),
917 result.push_str(&header);
919 let body_lo = context.codemap.span_after(item.span, "{");
921 let shape = Shape::indented(offset + last_line_width(&result), context.config);
922 let generics_str = try_opt!(rewrite_generics(
926 mk_sp(item.span.lo, body_lo),
928 result.push_str(&generics_str);
930 let trait_bound_str = try_opt!(rewrite_trait_bounds(
933 Shape::indented(offset, context.config),
935 // If the trait, generics, and trait bound cannot fit on the same line,
936 // put the trait bounds on an indented new line
937 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
938 context.config.comment_width()
941 let trait_indent = offset.block_only().block_indent(context.config);
942 result.push_str(&trait_indent.to_string(context.config));
944 result.push_str(&trait_bound_str);
946 let has_body = !trait_items.is_empty();
948 let where_density = if (context.config.where_density() == Density::Compressed &&
949 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
950 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
951 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
952 !result.contains('\n'))
959 let where_budget = try_opt!(
963 .checked_sub(last_line_width(&result))
965 let pos_before_where = if type_param_bounds.is_empty() {
966 // We do not use this, so it does not matter
969 type_param_bounds[type_param_bounds.len() - 1].span().hi
971 let where_clause_str = try_opt!(rewrite_where_clause(
973 &generics.where_clause,
974 context.config.item_brace_style(),
975 Shape::legacy(where_budget, offset.block_only()),
979 trait_bound_str.is_empty() && last_line_width(&generics_str) == 1,
984 // If the where clause cannot fit on the same line,
985 // put the where clause on a new line
986 if !where_clause_str.contains('\n') &&
987 last_line_width(&result) + where_clause_str.len() + offset.width() >
988 context.config.comment_width()
991 let width = offset.block_indent + context.config.tab_spaces() - 1;
992 let where_indent = Indent::new(0, width);
993 result.push_str(&where_indent.to_string(context.config));
995 result.push_str(&where_clause_str);
997 match context.config.item_brace_style() {
998 BraceStyle::AlwaysNextLine => {
1000 result.push_str(&offset.to_string(context.config));
1002 BraceStyle::PreferSameLine => result.push(' '),
1003 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1004 (!trait_items.is_empty() || result.contains('\n'))
1007 result.push_str(&offset.to_string(context.config));
1014 let snippet = context.snippet(item.span);
1015 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1017 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1018 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1019 visitor.block_indent = offset.block_only().block_indent(context.config);
1020 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1022 for item in trait_items {
1023 visitor.visit_trait_item(item);
1026 visitor.format_missing(item.span.hi - BytePos(1));
1028 let inner_indent_str = visitor.block_indent.to_string(context.config);
1029 let outer_indent_str = offset.block_only().to_string(context.config);
1032 result.push_str(&inner_indent_str);
1033 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1035 result.push_str(&outer_indent_str);
1036 } else if result.contains('\n') {
1047 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1048 format!("{};", format_header(item_name, ident, vis))
1051 pub fn format_struct_struct(
1052 context: &RewriteContext,
1055 vis: &ast::Visibility,
1056 fields: &[ast::StructField],
1057 generics: Option<&ast::Generics>,
1060 one_line_width: Option<usize>,
1061 ) -> Option<String> {
1062 let mut result = String::with_capacity(1024);
1064 let header_str = format_header(item_name, ident, vis);
1065 result.push_str(&header_str);
1067 let body_lo = context.codemap.span_after(span, "{");
1069 let generics_str = match generics {
1070 Some(g) => try_opt!(format_generics(
1075 context.config.item_brace_style(),
1078 mk_sp(span.lo, body_lo),
1079 last_line_width(&result),
1082 // 3 = ` {}`, 2 = ` {`.
1083 let overhead = if fields.is_empty() { 3 } else { 2 };
1084 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1085 !fields.is_empty()) ||
1089 .checked_sub(result.len())
1090 .unwrap_or(0) < overhead
1092 format!("\n{}{{", offset.block_only().to_string(context.config))
1099 let overhead = if fields.is_empty() { 1 } else { 0 };
1100 let max_len = context
1103 .checked_sub(offset.width())
1105 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1107 result.push_str(&offset.to_string(context.config));
1108 result.push_str(&generics_str.trim_left());
1110 result.push_str(&generics_str);
1113 if fields.is_empty() {
1114 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1115 if snippet.trim().is_empty() {
1117 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1119 result.push_str(&snippet.trim_right());
1121 result.push_str(&offset.to_string(context.config));
1123 result.push_str(&snippet);
1126 return Some(result);
1130 let one_line_budget = context
1133 .checked_sub(result.len() + 3 + offset.width())
1135 let one_line_budget =
1136 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1138 let items_str = try_opt!(rewrite_with_alignment(
1141 Shape::indented(offset, context.config),
1142 mk_sp(body_lo, span.hi),
1146 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1147 Some(format!("{} {} }}", result, items_str))
1153 .block_indent(context.config)
1154 .to_string(context.config),
1156 offset.to_string(context.config)
1161 fn format_tuple_struct(
1162 context: &RewriteContext,
1165 vis: &ast::Visibility,
1166 fields: &[ast::StructField],
1167 generics: Option<&ast::Generics>,
1170 ) -> Option<String> {
1171 let mut result = String::with_capacity(1024);
1173 let header_str = format_header(item_name, ident, vis);
1174 result.push_str(&header_str);
1176 let body_lo = if fields.is_empty() {
1177 context.codemap.span_after(span, "(")
1181 let body_hi = if fields.is_empty() {
1182 context.codemap.span_after(span, ")")
1184 // This is a dirty hack to work around a missing `)` from the span of the last field.
1185 let last_arg_span = fields[fields.len() - 1].span;
1186 if context.snippet(last_arg_span).ends_with(")") {
1191 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1195 let where_clause_str = match generics {
1197 let budget = context.budget(last_line_width(&header_str));
1198 let shape = Shape::legacy(budget, offset);
1199 let g_span = mk_sp(span.lo, body_lo);
1200 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1201 result.push_str(&generics_str);
1203 let where_budget = context.budget(last_line_width(&result));
1204 try_opt!(rewrite_where_clause(
1206 &generics.where_clause,
1207 context.config.item_brace_style(),
1208 Shape::legacy(where_budget, offset.block_only()),
1209 Density::Compressed,
1218 None => "".to_owned(),
1221 if fields.is_empty() {
1223 let used_width = if result.contains('\n') {
1224 last_line_width(&result) + 3
1226 offset.width() + result.len() + 3
1228 if used_width > context.config.max_width() {
1230 result.push_str(&offset
1231 .block_indent(context.config)
1232 .to_string(context.config))
1235 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1236 if snippet.is_empty() {
1238 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1239 result.push_str(&snippet.trim_right());
1241 result.push_str(&offset.to_string(context.config));
1243 result.push_str(&snippet);
1248 let body = try_opt!(
1252 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1254 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1255 context.config.fn_call_width(),
1259 result.push_str(&body);
1262 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1263 (result.contains('\n') ||
1264 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1265 context.config.max_width())
1267 // We need to put the where clause on a new line, but we didn't
1268 // know that earlier, so the where clause will not be indented properly.
1270 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1271 .to_string(context.config));
1273 result.push_str(&where_clause_str);
1278 pub fn rewrite_type_alias(
1279 context: &RewriteContext,
1283 generics: &ast::Generics,
1284 vis: &ast::Visibility,
1286 ) -> Option<String> {
1287 let mut result = String::new();
1289 result.push_str(&format_visibility(vis));
1290 result.push_str("type ");
1291 result.push_str(&ident.to_string());
1294 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1295 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1296 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1297 result.push_str(&generics_str);
1299 let where_budget = try_opt!(
1303 .checked_sub(last_line_width(&result))
1305 let where_clause_str = try_opt!(rewrite_where_clause(
1307 &generics.where_clause,
1308 context.config.item_brace_style(),
1309 Shape::legacy(where_budget, indent),
1310 context.config.where_density(),
1318 result.push_str(&where_clause_str);
1319 result.push_str(" = ");
1321 let line_width = last_line_width(&result);
1322 // This checked_sub may fail as the extra space after '=' is not taken into account
1323 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1324 let budget = context
1327 .checked_sub(indent.width() + line_width + ";".len())
1329 let type_indent = indent + line_width;
1330 // Try to fit the type on the same line
1331 let ty_str = try_opt!(
1332 ty.rewrite(context, Shape::legacy(budget, type_indent))
1334 // The line was too short, try to put the type on the next line
1336 // Remove the space after '='
1338 let type_indent = indent.block_indent(context.config);
1340 result.push_str(&type_indent.to_string(context.config));
1341 let budget = try_opt!(
1345 .checked_sub(type_indent.width() + ";".len())
1347 ty.rewrite(context, Shape::legacy(budget, type_indent))
1350 result.push_str(&ty_str);
1351 result.push_str(";");
1355 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1357 if config.space_before_type_annotation() {
1362 if config.space_after_type_annotation_colon() {
1370 fn rewrite_missing_comment_on_field(
1371 context: &RewriteContext,
1375 result: &mut String,
1376 ) -> Option<String> {
1377 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1378 let newline_index = possibly_comment_snippet.find('\n');
1379 let comment_index = possibly_comment_snippet.find('/');
1380 match (newline_index, comment_index) {
1381 (Some(i), Some(j)) if i > j => result.push(' '),
1384 result.push_str(&shape.indent.to_string(context.config));
1387 let trimmed = possibly_comment_snippet.trim();
1388 if trimmed.is_empty() {
1391 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1392 format!("{}\n{}", s, shape.indent.to_string(context.config))
1397 pub fn rewrite_struct_field_prefix(
1398 context: &RewriteContext,
1399 field: &ast::StructField,
1401 ) -> Option<String> {
1402 let vis = format_visibility(&field.vis);
1403 let mut attr_str = try_opt!(
1406 .rewrite(context, Shape::indented(shape.indent, context.config))
1408 // Try format missing comments after attributes
1409 let missing_comment = if !field.attrs.is_empty() {
1410 rewrite_missing_comment_on_field(
1413 field.attrs[field.attrs.len() - 1].span.hi,
1416 ).unwrap_or(String::new())
1421 let type_annotation_spacing = type_annotation_spacing(context.config);
1422 Some(match field.ident {
1423 Some(name) => format!(
1429 type_annotation_spacing.0
1431 None => format!("{}{}{}", attr_str, missing_comment, vis),
1435 fn rewrite_struct_field_type(
1436 context: &RewriteContext,
1437 last_line_width: usize,
1438 field: &ast::StructField,
1441 ) -> Option<String> {
1442 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1445 .rewrite(context, ty_shape)
1446 .map(|ty| format!("{}{}", spacing, ty))
1449 impl Rewrite for ast::StructField {
1450 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1451 rewrite_struct_field(context, self, shape, 0)
1455 pub fn rewrite_struct_field(
1456 context: &RewriteContext,
1457 field: &ast::StructField,
1459 lhs_max_width: usize,
1460 ) -> Option<String> {
1461 if contains_skip(&field.attrs) {
1462 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1463 return wrap_str(span, context.config.max_width(), shape);
1466 let type_annotation_spacing = type_annotation_spacing(context.config);
1467 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1469 // Try to put everything on a single line.
1470 let last_line_width = last_line_width(&prefix);
1471 let mut spacing = String::from(if field.ident.is_some() {
1472 type_annotation_spacing.1
1476 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1477 for _ in 0..lhs_offset {
1480 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1481 if let Some(ref ty) = ty_rewritten {
1482 if !ty.contains('\n') {
1483 return Some(prefix + &ty);
1487 // We must use multiline.
1488 let type_offset = shape.indent.block_indent(context.config);
1489 let rewrite_type_in_next_line = || {
1492 .rewrite(context, Shape::indented(type_offset, context.config))
1495 match ty_rewritten {
1496 // If we start from the next line and type fits in a single line, then do so.
1497 Some(ref ty) => match rewrite_type_in_next_line() {
1498 Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
1501 type_offset.to_string(&context.config),
1504 _ => Some(prefix + &ty),
1507 let ty = try_opt!(rewrite_type_in_next_line());
1511 type_offset.to_string(&context.config),
1518 pub fn rewrite_static(
1520 vis: &ast::Visibility,
1523 mutability: ast::Mutability,
1524 expr_opt: Option<&ptr::P<ast::Expr>>,
1527 context: &RewriteContext,
1528 ) -> Option<String> {
1529 let colon = colon_spaces(
1530 context.config.space_before_type_annotation(),
1531 context.config.space_after_type_annotation_colon(),
1533 let prefix = format!(
1535 format_visibility(vis),
1537 format_mutability(mutability),
1542 let ty_str = try_opt!(ty.rewrite(
1545 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1549 if let Some(expr) = expr_opt {
1550 let lhs = format!("{}{} =", prefix, ty_str);
1552 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1557 Shape::legacy(remaining_width, offset.block_only()),
1559 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1561 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1563 Some(format!("{}{};", prefix, ty_str))
1567 pub fn rewrite_associated_type(
1569 ty_opt: Option<&ptr::P<ast::Ty>>,
1570 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1571 context: &RewriteContext,
1573 ) -> Option<String> {
1574 let prefix = format!("type {}", ident);
1576 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1577 let shape = Shape::indented(indent, context.config);
1578 let bounds: &[_] = ty_param_bounds;
1579 let bound_str = try_opt!(
1582 .map(|ty_bound| ty_bound.rewrite(context, shape))
1583 .collect::<Option<Vec<_>>>()
1585 if bounds.len() > 0 {
1586 format!(": {}", join_bounds(context, shape, &bound_str))
1594 if let Some(ty) = ty_opt {
1595 let ty_str = try_opt!(ty.rewrite(
1598 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1599 indent.block_only(),
1602 Some(format!("{} = {};", prefix, ty_str))
1604 Some(format!("{}{};", prefix, type_bounds_str))
1608 pub fn rewrite_associated_impl_type(
1610 defaultness: ast::Defaultness,
1611 ty_opt: Option<&ptr::P<ast::Ty>>,
1612 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1613 context: &RewriteContext,
1615 ) -> Option<String> {
1616 let result = try_opt!(rewrite_associated_type(
1619 ty_param_bounds_opt,
1625 ast::Defaultness::Default => Some(format!("default {}", result)),
1630 impl Rewrite for ast::FunctionRetTy {
1631 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1633 ast::FunctionRetTy::Default(_) => Some(String::new()),
1634 ast::FunctionRetTy::Ty(ref ty) => {
1635 let inner_width = try_opt!(shape.width.checked_sub(3));
1636 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1637 .map(|r| format!("-> {}", r))
1643 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1645 ast::TyKind::Infer => {
1646 let original = context.snippet(ty.span);
1653 impl Rewrite for ast::Arg {
1654 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1655 if is_named_arg(self) {
1656 let mut result = try_opt!(
1658 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1661 if !is_empty_infer(context, &*self.ty) {
1662 if context.config.space_before_type_annotation() {
1663 result.push_str(" ");
1665 result.push_str(":");
1666 if context.config.space_after_type_annotation_colon() {
1667 result.push_str(" ");
1669 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1670 let ty_str = try_opt!(self.ty.rewrite(
1672 Shape::legacy(max_width, shape.indent + result.len()),
1674 result.push_str(&ty_str);
1679 self.ty.rewrite(context, shape)
1684 fn rewrite_explicit_self(
1685 explicit_self: &ast::ExplicitSelf,
1687 context: &RewriteContext,
1688 ) -> Option<String> {
1689 match explicit_self.node {
1690 ast::SelfKind::Region(lt, m) => {
1691 let mut_str = format_mutability(m);
1694 let lifetime_str = try_opt!(l.rewrite(
1696 Shape::legacy(context.config.max_width(), Indent::empty()),
1698 Some(format!("&{} {}self", lifetime_str, mut_str))
1700 None => Some(format!("&{}self", mut_str)),
1703 ast::SelfKind::Explicit(ref ty, _) => {
1704 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1706 let mutability = explicit_self_mutability(&args[0]);
1707 let type_str = try_opt!(ty.rewrite(
1709 Shape::legacy(context.config.max_width(), Indent::empty()),
1714 format_mutability(mutability),
1718 ast::SelfKind::Value(_) => {
1719 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1721 let mutability = explicit_self_mutability(&args[0]);
1723 Some(format!("{}self", format_mutability(mutability)))
1728 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1729 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1730 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1731 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1738 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1739 if is_named_arg(arg) {
1746 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1748 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1749 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1750 _ => arg.ty.span.hi,
1754 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1755 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1756 ident.node != symbol::keywords::Invalid.ident()
1762 // Return type is (result, force_new_line_for_brace)
1764 context: &RewriteContext,
1768 generics: &ast::Generics,
1769 unsafety: ast::Unsafety,
1770 constness: ast::Constness,
1771 defaultness: ast::Defaultness,
1773 vis: &ast::Visibility,
1775 newline_brace: bool,
1778 ) -> Option<(String, bool)> {
1779 let mut force_new_line_for_brace = false;
1781 let where_clause = &generics.where_clause;
1783 let mut result = String::with_capacity(1024);
1784 // Vis unsafety abi.
1785 result.push_str(&*format_visibility(vis));
1787 if let ast::Defaultness::Default = defaultness {
1788 result.push_str("default ");
1791 if let ast::Constness::Const = constness {
1792 result.push_str("const ");
1795 result.push_str(::utils::format_unsafety(unsafety));
1797 if abi != abi::Abi::Rust {
1798 result.push_str(&::utils::format_abi(
1800 context.config.force_explicit_abi(),
1805 result.push_str("fn ");
1806 result.push_str(&ident.to_string());
1809 let overhead = if has_braces && !newline_brace {
1816 let shape = try_opt!(
1817 Shape::indented(indent + last_line_width(&result), context.config).sub_width(overhead)
1819 let g_span = mk_sp(span.lo, fd.output.span().lo);
1820 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1821 result.push_str(&generics_str);
1823 let snuggle_angle_bracket = generics_str
1826 .map_or(false, |l| l.trim_left().len() == 1);
1828 // Note that the width and indent don't really matter, we'll re-layout the
1829 // return type later anyway.
1830 let ret_str = try_opt!(
1832 .rewrite(&context, Shape::indented(indent, context.config))
1835 let multi_line_ret_str = ret_str.contains('\n');
1836 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1839 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1840 try_opt!(compute_budgets_for_args(
1849 if context.config.fn_args_layout() == IndentStyle::Block {
1850 arg_indent = indent.block_indent(context.config);
1852 multi_line_budget = context.config.max_width() - (arg_indent.width() + 1);
1856 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1862 // Check if vertical layout was forced.
1863 if one_line_budget == 0 {
1864 if snuggle_angle_bracket {
1867 if context.config.fn_args_paren_newline() {
1869 result.push_str(&arg_indent.to_string(context.config));
1870 if context.config.fn_args_layout() == IndentStyle::Visual {
1871 arg_indent = arg_indent + 1; // extra space for `(`
1875 result.push_str("(");
1876 if context.config.fn_args_layout() == IndentStyle::Visual {
1878 result.push_str(&arg_indent.to_string(context.config));
1885 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1889 if multi_line_ret_str {
1890 one_line_budget = 0;
1893 // A conservative estimation, to goal is to be over all parens in generics
1894 let args_start = generics
1897 .map_or(span.lo, |tp| end_typaram(tp));
1898 let args_end = if fd.inputs.is_empty() {
1899 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1901 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1902 context.codemap.span_after(last_span, ")")
1904 let args_span = mk_sp(
1905 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1908 let arg_str = try_opt!(rewrite_args(
1911 fd.get_self().as_ref(),
1918 generics_str.contains('\n'),
1921 let multi_line_arg_str =
1922 arg_str.contains('\n') || arg_str.chars().last().map_or(false, |c| c == ',');
1924 let put_args_in_block = match context.config.fn_args_layout() {
1925 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1927 } && !fd.inputs.is_empty();
1929 let mut args_last_line_contains_comment = false;
1930 if put_args_in_block {
1931 arg_indent = indent.block_indent(context.config);
1933 result.push_str(&arg_indent.to_string(context.config));
1934 result.push_str(&arg_str);
1936 result.push_str(&indent.to_string(context.config));
1939 result.push_str(&arg_str);
1940 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1943 // If the last line of args contains comment, we cannot put the closing paren
1944 // on the same line.
1948 .map_or(false, |last_line| last_line.contains("//"))
1950 args_last_line_contains_comment = true;
1952 result.push_str(&arg_indent.to_string(context.config));
1958 if !ret_str.is_empty() {
1959 let ret_should_indent = match context.config.fn_args_layout() {
1960 // If our args are block layout then we surely must have space.
1961 IndentStyle::Block if put_args_in_block => false,
1963 // If we've already gone multi-line, or the return type would push over the max
1964 // width, then put the return type on a new line. With the +1 for the signature
1965 // length an additional space between the closing parenthesis of the argument and
1966 // the arrow '->' is considered.
1967 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1969 // If there is no where clause, take into account the space after the return type
1971 if where_clause.predicates.is_empty() {
1975 let overlong_sig = sig_length > context.config.max_width();
1977 (!args_last_line_contains_comment) &&
1978 (result.contains('\n') || multi_line_ret_str || overlong_sig)
1981 let ret_indent = if ret_should_indent {
1982 let indent = match context.config.fn_return_indent() {
1983 ReturnIndent::WithWhereClause => indent + 4,
1984 // Aligning with non-existent args looks silly.
1985 _ if arg_str.is_empty() => {
1986 force_new_line_for_brace = true;
1989 // FIXME: we might want to check that using the arg indent
1990 // doesn't blow our budget, and if it does, then fallback to
1991 // the where clause indent.
1996 result.push_str(&indent.to_string(context.config));
2000 Indent::new(indent.block_indent, last_line_width(&result))
2003 if multi_line_ret_str || ret_should_indent {
2004 // Now that we know the proper indent and width, we need to
2005 // re-layout the return type.
2006 let ret_str = try_opt!(
2008 .rewrite(context, Shape::indented(ret_indent, context.config))
2010 result.push_str(&ret_str);
2012 result.push_str(&ret_str);
2015 // Comment between return type and the end of the decl.
2016 let snippet_lo = fd.output.span().hi;
2017 if where_clause.predicates.is_empty() {
2018 let snippet_hi = span.hi;
2019 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2020 // Try to preserve the layout of the original snippet.
2021 let original_starts_with_newline = snippet
2023 .map_or(false, |i| snippet[i..].starts_with('\n'));
2024 let original_ends_with_newline = snippet
2025 .rfind(|c| c != ' ')
2026 .map_or(false, |i| snippet[i..].ends_with('\n'));
2027 let snippet = snippet.trim();
2028 if !snippet.is_empty() {
2029 result.push(if original_starts_with_newline {
2034 result.push_str(snippet);
2035 if original_ends_with_newline {
2036 force_new_line_for_brace = true;
2040 // FIXME it would be nice to catch comments between the return type
2041 // and the where clause, but we don't have a span for the where
2046 let should_compress_where = match context.config.where_density() {
2047 Density::Compressed => !result.contains('\n') || put_args_in_block,
2048 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2050 } || (put_args_in_block && ret_str.is_empty());
2052 let pos_before_where = match fd.output {
2053 ast::FunctionRetTy::Default(..) => args_span.hi,
2054 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2056 if where_clause.predicates.len() == 1 && should_compress_where {
2057 let budget = try_opt!(
2061 .checked_sub(last_line_width(&result))
2063 if let Some(where_clause_str) = rewrite_where_clause(
2066 context.config.fn_brace_style(),
2067 Shape::legacy(budget, indent),
2068 Density::Compressed,
2071 put_args_in_block && ret_str.is_empty(),
2076 if !where_clause_str.contains('\n') {
2077 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
2081 result.push_str(&where_clause_str);
2083 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2084 return Some((result, force_new_line_for_brace));
2089 let where_clause_str = try_opt!(rewrite_where_clause(
2092 context.config.fn_brace_style(),
2093 Shape::indented(indent, context.config),
2097 put_args_in_block && ret_str.is_empty(),
2103 result.push_str(&where_clause_str);
2105 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2106 return Some((result, force_new_line_for_brace));
2109 fn last_line_contains_single_line_comment(s: &str) -> bool {
2110 s.lines().last().map_or(false, |l| l.contains("//"))
2114 context: &RewriteContext,
2116 explicit_self: Option<&ast::ExplicitSelf>,
2117 one_line_budget: usize,
2118 multi_line_budget: usize,
2123 generics_str_contains_newline: bool,
2124 ) -> Option<String> {
2125 let mut arg_item_strs = try_opt!(
2128 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2130 .collect::<Option<Vec<_>>>()
2133 // Account for sugary self.
2134 // FIXME: the comment for the self argument is dropped. This is blocked
2135 // on rust issue #27522.
2136 let min_args = explicit_self
2137 .and_then(|explicit_self| {
2138 rewrite_explicit_self(explicit_self, args, context)
2140 .map_or(1, |self_str| {
2141 arg_item_strs[0] = self_str;
2145 // Comments between args.
2146 let mut arg_items = Vec::new();
2148 arg_items.push(ListItem::from_str(""));
2151 // FIXME(#21): if there are no args, there might still be a comment, but
2152 // without spans for the comment or parens, there is no chance of
2153 // getting it right. You also don't get to put a comment on self, unless
2155 if args.len() >= min_args || variadic {
2156 let comment_span_start = if min_args == 2 {
2157 let second_arg_start = if arg_has_pattern(&args[1]) {
2162 let reduced_span = mk_sp(span.lo, second_arg_start);
2164 context.codemap.span_after_last(reduced_span, ",")
2169 enum ArgumentKind<'a> {
2170 Regular(&'a ast::Arg),
2174 let variadic_arg = if variadic {
2175 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2176 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2177 Some(ArgumentKind::Variadic(variadic_start))
2182 let more_items = itemize_list(
2184 args[min_args - 1..]
2186 .map(ArgumentKind::Regular)
2187 .chain(variadic_arg),
2190 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2191 ArgumentKind::Variadic(start) => start,
2194 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2195 ArgumentKind::Variadic(start) => start + BytePos(3),
2198 ArgumentKind::Regular(..) => None,
2199 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2205 arg_items.extend(more_items);
2208 let fits_in_one_line = !generics_str_contains_newline &&
2209 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2211 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2212 item.item = Some(arg);
2215 let last_line_ends_with_comment = arg_items
2218 .and_then(|item| item.post_comment.as_ref())
2219 .map_or(false, |s| s.trim().starts_with("//"));
2221 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2222 IndentStyle::Block if fits_in_one_line => {
2223 (indent.block_indent(context.config), SeparatorTactic::Never)
2225 IndentStyle::Block => (
2226 indent.block_indent(context.config),
2227 context.config.trailing_comma(),
2229 IndentStyle::Visual if last_line_ends_with_comment => {
2230 (arg_indent, context.config.trailing_comma())
2232 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2235 let tactic = definitive_tactic(
2237 context.config.fn_args_density().to_list_tactic(),
2240 let budget = match tactic {
2241 DefinitiveListTactic::Horizontal => one_line_budget,
2242 _ => multi_line_budget,
2245 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2247 let fmt = ListFormatting {
2250 trailing_separator: if variadic {
2251 SeparatorTactic::Never
2255 shape: Shape::legacy(budget, indent),
2256 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2257 preserve_newline: true,
2258 config: context.config,
2261 write_list(&arg_items, &fmt)
2264 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2265 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2266 ident.node != symbol::keywords::Invalid.ident()
2272 fn compute_budgets_for_args(
2273 context: &RewriteContext,
2277 newline_brace: bool,
2279 ) -> Option<((usize, usize, Indent))> {
2281 "compute_budgets_for_args {} {:?}, {}, {}",
2287 // Try keeping everything on the same line.
2288 if !result.contains('\n') {
2289 // 2 = `()`, 3 = `() `, space is before ret_string.
2290 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2291 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2301 let one_line_budget = context
2304 .checked_sub(used_space)
2307 if one_line_budget > 0 {
2309 let multi_line_overhead =
2310 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2311 let multi_line_budget =
2312 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2317 indent + result.len() + 1,
2322 // Didn't work. we must force vertical layout and put args on a newline.
2323 let new_indent = indent.block_indent(context.config);
2324 // Account for `)` and possibly ` {`.
2325 let used_space = new_indent.width() + if ret_str_len == 0 { 1 } else { 3 };
2326 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2327 Some((0, max_space, new_indent))
2330 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2331 match config.fn_brace_style() {
2332 BraceStyle::AlwaysNextLine => true,
2333 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
2338 fn rewrite_generics(
2339 context: &RewriteContext,
2340 generics: &ast::Generics,
2343 ) -> Option<String> {
2344 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2345 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2346 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2347 rewrite_generics_inner(context, generics, g_shape, 0, span)
2351 fn rewrite_generics_inner(
2352 context: &RewriteContext,
2353 generics: &ast::Generics,
2355 one_line_width: usize,
2357 ) -> Option<String> {
2358 // FIXME: convert bounds to where clauses where they get too big or if
2359 // there is a where clause at all.
2360 let lifetimes: &[_] = &generics.lifetimes;
2361 let tys: &[_] = &generics.ty_params;
2362 if lifetimes.is_empty() && tys.is_empty() {
2363 return Some(String::new());
2366 // Strings for the generics.
2367 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2368 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2370 // Extract comments between generics.
2371 let lt_spans = lifetimes.iter().map(|l| {
2372 let hi = if l.bounds.is_empty() {
2375 l.bounds[l.bounds.len() - 1].span.hi
2377 mk_sp(l.lifetime.span.lo, hi)
2379 let ty_spans = tys.iter().map(|ty| ty.span());
2381 let items = itemize_list(
2383 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2387 // FIXME: don't clone
2388 |&(_, ref str)| str.clone(),
2389 context.codemap.span_after(span, "<"),
2392 format_generics_item_list(context, items, shape, one_line_width)
2395 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2396 match config.generics_indent() {
2397 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2398 IndentStyle::Block => {
2402 .block_indent(config.tab_spaces())
2403 .with_max_width(config)
2409 pub fn format_generics_item_list<I>(
2410 context: &RewriteContext,
2413 one_line_budget: usize,
2416 I: Iterator<Item = ListItem>,
2418 let item_vec = items.collect::<Vec<_>>();
2420 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, one_line_budget);
2421 let fmt = ListFormatting {
2424 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2425 SeparatorTactic::Never
2427 context.config.trailing_comma()
2430 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2431 preserve_newline: true,
2432 config: context.config,
2435 let list_str = try_opt!(write_list(&item_vec, &fmt));
2437 Some(wrap_generics_with_angle_brackets(
2444 pub fn wrap_generics_with_angle_brackets(
2445 context: &RewriteContext,
2447 list_offset: Indent,
2449 if context.config.generics_indent() == IndentStyle::Block &&
2450 (list_str.contains('\n') || list_str.ends_with(','))
2454 list_offset.to_string(context.config),
2457 .block_unindent(context.config)
2458 .to_string(context.config)
2460 } else if context.config.spaces_within_angle_brackets() {
2461 format!("< {} >", list_str)
2463 format!("<{}>", list_str)
2467 fn rewrite_trait_bounds(
2468 context: &RewriteContext,
2469 type_param_bounds: &ast::TyParamBounds,
2471 ) -> Option<String> {
2472 let bounds: &[_] = type_param_bounds;
2474 if bounds.is_empty() {
2475 return Some(String::new());
2477 let bound_str = try_opt!(
2480 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2481 .collect::<Option<Vec<_>>>()
2483 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2486 fn rewrite_where_clause_rfc_style(
2487 context: &RewriteContext,
2488 where_clause: &ast::WhereClause,
2491 suppress_comma: bool,
2492 // where clause can be kept on the current line.
2494 span_end: Option<BytePos>,
2496 span_end_before_where: BytePos,
2497 ) -> Option<String> {
2498 let block_shape = shape.block().with_max_width(context.config);
2500 let (span_before, span_after) =
2501 missing_span_before_after_where(context, span.hi, span_end_before_where, where_clause);
2502 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2509 let starting_newline = if snuggle && comment_before.is_empty() {
2512 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2515 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2516 // each clause on one line, trailing comma (except if suppress_comma)
2517 let span_start = where_clause.predicates[0].span().lo;
2518 // If we don't have the start of the next span, then use the end of the
2519 // predicates, but that means we miss comments.
2520 let len = where_clause.predicates.len();
2521 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2522 let span_end = span_end.unwrap_or(end_of_preds);
2523 let items = itemize_list(
2525 where_clause.predicates.iter(),
2527 |pred| pred.span().lo,
2528 |pred| pred.span().hi,
2529 |pred| pred.rewrite(context, block_shape),
2533 let comma_tactic = if suppress_comma {
2534 SeparatorTactic::Never
2536 context.config.trailing_comma()
2539 let fmt = ListFormatting {
2540 tactic: DefinitiveListTactic::Vertical,
2542 trailing_separator: comma_tactic,
2543 shape: clause_shape,
2544 ends_with_newline: true,
2545 preserve_newline: true,
2546 config: context.config,
2548 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2550 let newline_before_where = if comment_before.is_empty() || comment_before.ends_with('\n') {
2553 "\n".to_owned() + &shape.indent.to_string(context.config)
2555 let newline_after_where = if comment_after.is_empty() {
2558 "\n".to_owned() + &clause_shape.indent.to_string(context.config)
2561 "{}{}{}where{}{}\n{}{}",
2564 newline_before_where,
2565 newline_after_where,
2567 clause_shape.indent.to_string(context.config),
2572 fn rewrite_where_clause(
2573 context: &RewriteContext,
2574 where_clause: &ast::WhereClause,
2575 brace_style: BraceStyle,
2579 suppress_comma: bool,
2581 span_end: Option<BytePos>,
2583 span_end_before_where: BytePos,
2584 ) -> Option<String> {
2585 if where_clause.predicates.is_empty() {
2586 return Some(String::new());
2589 if context.config.where_style() == Style::Rfc {
2590 return rewrite_where_clause_rfc_style(
2599 span_end_before_where,
2603 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2605 let offset = match context.config.where_pred_indent() {
2606 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2607 // 6 = "where ".len()
2608 IndentStyle::Visual => shape.indent + extra_indent + 6,
2610 // FIXME: if where_pred_indent != Visual, then the budgets below might
2611 // be out by a char or two.
2613 let budget = context.config.max_width() - offset.width();
2614 let span_start = where_clause.predicates[0].span().lo;
2615 // If we don't have the start of the next span, then use the end of the
2616 // predicates, but that means we miss comments.
2617 let len = where_clause.predicates.len();
2618 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2619 let span_end = span_end.unwrap_or(end_of_preds);
2620 let items = itemize_list(
2622 where_clause.predicates.iter(),
2624 |pred| pred.span().lo,
2625 |pred| pred.span().hi,
2626 |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(&item_vec, context.config.where_layout(), budget);
2635 let mut comma_tactic = context.config.trailing_comma();
2636 // Kind of a hack because we don't usually have trailing commas in where clauses.
2637 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2638 comma_tactic = SeparatorTactic::Never;
2641 let fmt = ListFormatting {
2644 trailing_separator: comma_tactic,
2645 shape: Shape::legacy(budget, offset),
2646 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2647 preserve_newline: true,
2648 config: context.config,
2650 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2652 let end_length = if terminator == "{" {
2653 // If the brace is on the next line we don't need to count it otherwise it needs two
2656 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2657 BraceStyle::PreferSameLine => 2,
2659 } else if terminator == "=" {
2664 if density == Density::Tall || preds_str.contains('\n') ||
2665 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2669 (shape.indent + extra_indent).to_string(context.config),
2673 Some(format!(" where {}", preds_str))
2677 fn missing_span_before_after_where(
2678 context: &RewriteContext,
2680 before_item_span_end: BytePos,
2681 where_clause: &ast::WhereClause,
2683 let snippet = context.snippet(mk_sp(before_item_span_end, item_end));
2684 let pos_before_where =
2685 before_item_span_end + BytePos(snippet.find_uncommented("where").unwrap() as u32);
2686 let missing_span_before = mk_sp(before_item_span_end, pos_before_where);
2688 let pos_after_where = pos_before_where + BytePos(5);
2689 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2690 (missing_span_before, missing_span_after)
2693 fn rewrite_missing_comment_in_where(
2694 context: &RewriteContext,
2697 ) -> Option<String> {
2698 let comment = comment.trim();
2699 if comment.is_empty() {
2702 rewrite_comment(comment, false, shape, context.config)
2706 fn rewrite_comments_before_after_where(
2707 context: &RewriteContext,
2708 span_before_where: Span,
2709 span_after_where: Span,
2711 ) -> Option<(String, String)> {
2712 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2714 &context.snippet(span_before_where),
2717 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2719 &context.snippet(span_after_where),
2720 shape.block_indent(context.config.tab_spaces()),
2722 Some((before_comment, after_comment))
2725 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2726 format!("{}{}{}", format_visibility(vis), item_name, ident)
2730 context: &RewriteContext,
2731 generics: &ast::Generics,
2734 brace_style: BraceStyle,
2735 force_same_line_brace: bool,
2739 ) -> Option<String> {
2740 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2741 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2743 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2744 let budget = context
2747 .checked_sub(last_line_width(&result))
2749 let where_clause_str = try_opt!(rewrite_where_clause(
2751 &generics.where_clause,
2753 Shape::legacy(budget, offset.block_only()),
2757 trimmed_last_line_width(&result) == 1,
2762 result.push_str(&where_clause_str);
2763 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2764 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2766 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2767 brace_style != BraceStyle::AlwaysNextLine
2769 let total_used_width = if result.contains('\n') {
2770 last_line_width(&result)
2772 used_width + result.len()
2774 let remaining_budget = context
2777 .checked_sub(total_used_width)
2779 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2780 // and hence we take the closer into account as well for one line budget.
2781 // We assume that the closer has the same length as the opener.
2782 let overhead = if force_same_line_brace {
2783 1 + opener.len() + opener.len()
2787 let forbid_same_line_brace = overhead > remaining_budget;
2788 if !forbid_same_line_brace && same_line_brace {
2792 result.push_str(&offset.block_only().to_string(context.config));
2794 result.push_str(opener);