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 rewrite_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, 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::new();
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);
188 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
189 self.format_missing_with_indent(item.span.lo);
190 // Drop semicolon or it will be interpreted as comment.
191 // FIXME: this may be a faulty span from libsyntax.
192 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
195 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
196 let indent = self.block_indent;
197 let rewrite = rewrite_fn_base(
203 ast::Unsafety::Normal,
204 ast::Constness::NotConst,
205 ast::Defaultness::Final,
206 // These are not actually rust functions,
207 // but we format them as such.
217 Some((new_fn, _)) => {
218 self.buffer.push_str(&new_fn);
219 self.buffer.push_str(";");
221 None => self.format_missing(item.span.hi),
224 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
225 // FIXME(#21): we're dropping potential comments in between the
226 // function keywords here.
227 let vis = format_visibility(&item.vis);
228 let mut_str = if is_mutable { "mut " } else { "" };
229 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
230 let offset = self.block_indent + prefix.len();
232 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
233 let rewrite = ty.rewrite(&self.get_context(), shape);
237 self.buffer.push_str(&prefix);
238 self.buffer.push_str(&result);
239 self.buffer.push_str(";");
241 None => self.format_missing(item.span.hi),
246 self.last_pos = item.span.hi;
254 generics: &ast::Generics,
255 unsafety: ast::Unsafety,
256 constness: ast::Constness,
257 defaultness: ast::Defaultness,
259 vis: &ast::Visibility,
262 ) -> Option<String> {
263 let context = self.get_context();
265 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
266 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
267 !context.config.fn_empty_single_line();
268 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
270 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
287 if force_newline_brace {
288 newline_brace = true;
289 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
290 !result.contains('\n')
292 newline_brace = false;
295 // Prepare for the function body by possibly adding a newline and
297 // FIXME we'll miss anything between the end of the signature and the
298 // start of the body, but we need more spans from the compiler to solve
302 result.push_str(&indent.to_string(self.config));
307 self.single_line_fn(&result, block).or_else(|| Some(result))
310 pub fn rewrite_required_fn(
314 sig: &ast::MethodSig,
316 ) -> Option<String> {
317 // Drop semicolon or it will be interpreted as comment.
318 let span = mk_sp(span.lo, span.hi - BytePos(1));
319 let context = self.get_context();
321 let (mut result, _) = try_opt!(rewrite_fn_base(
329 ast::Defaultness::Final,
331 &ast::Visibility::Inherited,
338 // Re-attach semicolon
344 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
345 if fn_str.contains('\n') {
349 let codemap = self.get_context().codemap;
351 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
352 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
354 return Some(format!("{}{{}}", fn_str));
357 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
359 if let Some(ref stmt) = block.stmts.first() {
360 match stmt_expr(stmt) {
362 let suffix = if semicolon_for_expr(&self.get_context(), e) {
372 Shape::indented(self.block_indent, self.config),
373 ).map(|s| s + suffix)
374 .or_else(|| Some(self.snippet(e.span)))
376 None => stmt.rewrite(
378 Shape::indented(self.block_indent, self.config),
386 if let Some(res) = rewrite {
387 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
388 if !res.contains('\n') && width <= self.config.max_width() {
389 return Some(format!("{}{{ {} }}", fn_str, res));
400 vis: &ast::Visibility,
401 enum_def: &ast::EnumDef,
402 generics: &ast::Generics,
405 let enum_header = format_header("enum ", ident, vis);
406 self.buffer.push_str(&enum_header);
408 let enum_snippet = self.snippet(span);
409 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
410 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
411 let generics_str = format_generics(
416 self.config.item_brace_style(),
417 enum_def.variants.is_empty(),
419 mk_sp(span.lo, body_start),
420 last_line_width(&enum_header),
422 self.buffer.push_str(&generics_str);
424 self.last_pos = body_start;
426 self.block_indent = self.block_indent.block_indent(self.config);
427 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
429 Some(ref body_str) => self.buffer.push_str(body_str),
430 None => if contains_comment(&enum_snippet[brace_pos..]) {
431 self.format_missing_no_indent(span.hi - BytePos(1))
433 self.format_missing(span.hi - BytePos(1))
436 self.block_indent = self.block_indent.block_unindent(self.config);
438 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
440 .push_str(&self.block_indent.to_string(self.config));
442 self.buffer.push_str("}");
443 self.last_pos = span.hi;
446 // Format the body of an enum definition
447 fn format_variant_list(
449 enum_def: &ast::EnumDef,
452 ) -> Option<String> {
453 if enum_def.variants.is_empty() {
456 let mut result = String::with_capacity(1024);
458 let indentation = self.block_indent.to_string(self.config);
459 result.push_str(&indentation);
461 let items = itemize_list(
463 enum_def.variants.iter(),
465 |f| if !f.node.attrs.is_empty() {
466 f.node.attrs[0].span.lo
471 |f| self.format_variant(f),
477 let shape = Shape::indented(self.block_indent, self.config)
480 let fmt = ListFormatting {
481 tactic: DefinitiveListTactic::Vertical,
483 trailing_separator: self.config.trailing_comma(),
485 ends_with_newline: true,
486 preserve_newline: true,
490 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
491 result.push_str(&list);
496 // Variant of an enum.
497 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
498 if contains_skip(&field.node.attrs) {
499 let lo = field.node.attrs[0].span.lo;
500 let span = mk_sp(lo, field.span.hi);
501 return Some(self.snippet(span));
504 let context = self.get_context();
505 let indent = self.block_indent;
506 let shape = Shape::indented(indent, self.config);
507 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
512 .map_or(field.span.lo, |attr| attr.span.hi);
513 let span = mk_sp(lo, field.span.lo);
515 let variant_body = match field.node.data {
516 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
517 // FIXME: Should limit the width, as we have a trailing comma
518 try_opt!(format_struct(
522 &ast::Visibility::Inherited,
527 Some(self.config.struct_variant_width()),
530 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
532 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
533 if one_line_width <= shape.width {
534 format!("{} = {}", field.node.name, self.snippet(expr.span))
541 .block_indent(self.config)
542 .to_string(self.config),
543 self.snippet(expr.span)
547 String::from(field.node.name.to_string())
551 combine_strs_with_missing_comments(
557 is_attributes_extendable(&attrs_str),
563 context: &RewriteContext,
566 where_span_end: Option<BytePos>,
567 ) -> Option<String> {
568 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
569 let mut result = String::new();
570 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
571 result.push_str(&ref_and_type);
573 let where_budget = if result.contains('\n') {
574 context.config.max_width()
579 .checked_sub(last_line_width(&result))
582 let option = WhereClauseOption::snuggled(&ref_and_type);
583 let where_clause_str = try_opt!(rewrite_where_clause(
585 &generics.where_clause,
586 context.config.item_brace_style(),
587 Shape::legacy(where_budget, offset.block_only()),
588 context.config.where_density(),
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() + last_line_used_width(generics_str, result_len);
836 let shape = Shape::indented(offset + used_space, context.config);
837 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
838 if !(retry && trait_ref_str.contains('\n')) {
847 // We could not make enough space for trait_ref, so put it on new line.
849 let offset = offset.block_indent(context.config);
850 let shape = Shape::indented(offset, context.config);
851 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
855 &offset.to_string(context.config),
864 pub fn format_struct(
865 context: &RewriteContext,
868 vis: &ast::Visibility,
869 struct_def: &ast::VariantData,
870 generics: Option<&ast::Generics>,
873 one_line_width: Option<usize>,
874 ) -> Option<String> {
876 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
877 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
887 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
901 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
902 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
905 let mut result = String::new();
906 let header = format!(
908 format_visibility(&item.vis),
909 format_unsafety(unsafety),
913 result.push_str(&header);
915 let body_lo = context.codemap.span_after(item.span, "{");
917 let shape = Shape::indented(offset + last_line_width(&result), context.config);
918 let generics_str = try_opt!(rewrite_generics(
922 mk_sp(item.span.lo, body_lo),
924 result.push_str(&generics_str);
926 let trait_bound_str = try_opt!(rewrite_trait_bounds(
929 Shape::indented(offset, context.config),
931 // If the trait, generics, and trait bound cannot fit on the same line,
932 // put the trait bounds on an indented new line
933 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
934 context.config.comment_width()
937 let trait_indent = offset.block_only().block_indent(context.config);
938 result.push_str(&trait_indent.to_string(context.config));
940 result.push_str(&trait_bound_str);
942 let has_body = !trait_items.is_empty();
944 let where_density = if (context.config.where_density() == Density::Compressed &&
945 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
946 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
947 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
948 !result.contains('\n'))
955 let where_budget = try_opt!(
959 .checked_sub(last_line_width(&result))
961 let pos_before_where = if type_param_bounds.is_empty() {
962 if generics.where_clause.predicates.is_empty() {
963 // We do not use this, so it does not matter
966 let snippet = context.snippet(item.span);
967 let where_pos = snippet.find_uncommented("where");
968 item.span.lo + where_pos.map_or(BytePos(0), |p| BytePos(p as u32))
971 type_param_bounds[type_param_bounds.len() - 1].span().hi
973 let option = WhereClauseOption::snuggled(&generics_str);
974 let where_clause_str = try_opt!(rewrite_where_clause(
976 &generics.where_clause,
977 context.config.item_brace_style(),
978 Shape::legacy(where_budget, offset.block_only()),
985 // If the where clause cannot fit on the same line,
986 // put the where clause on a new line
987 if !where_clause_str.contains('\n') &&
988 last_line_width(&result) + where_clause_str.len() + offset.width() >
989 context.config.comment_width()
992 let width = offset.block_indent + context.config.tab_spaces() - 1;
993 let where_indent = Indent::new(0, width);
994 result.push_str(&where_indent.to_string(context.config));
996 result.push_str(&where_clause_str);
998 match context.config.item_brace_style() {
999 BraceStyle::AlwaysNextLine => {
1001 result.push_str(&offset.to_string(context.config));
1003 BraceStyle::PreferSameLine => result.push(' '),
1004 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1005 (!trait_items.is_empty() || result.contains('\n'))
1008 result.push_str(&offset.to_string(context.config));
1015 let snippet = context.snippet(item.span);
1016 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1018 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1019 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1020 visitor.block_indent = offset.block_only().block_indent(context.config);
1021 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1023 for item in trait_items {
1024 visitor.visit_trait_item(item);
1027 visitor.format_missing(item.span.hi - BytePos(1));
1029 let inner_indent_str = visitor.block_indent.to_string(context.config);
1030 let outer_indent_str = offset.block_only().to_string(context.config);
1033 result.push_str(&inner_indent_str);
1034 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1036 result.push_str(&outer_indent_str);
1037 } else if result.contains('\n') {
1048 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1049 format!("{};", format_header(item_name, ident, vis))
1052 pub fn format_struct_struct(
1053 context: &RewriteContext,
1056 vis: &ast::Visibility,
1057 fields: &[ast::StructField],
1058 generics: Option<&ast::Generics>,
1061 one_line_width: Option<usize>,
1062 ) -> Option<String> {
1063 let mut result = String::with_capacity(1024);
1065 let header_str = format_header(item_name, ident, vis);
1066 result.push_str(&header_str);
1068 let body_lo = context.codemap.span_after(span, "{");
1070 let generics_str = match generics {
1071 Some(g) => try_opt!(format_generics(
1076 context.config.item_brace_style(),
1079 mk_sp(span.lo, body_lo),
1080 last_line_width(&result),
1083 // 3 = ` {}`, 2 = ` {`.
1084 let overhead = if fields.is_empty() { 3 } else { 2 };
1085 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1086 !fields.is_empty()) ||
1090 .checked_sub(result.len())
1091 .unwrap_or(0) < overhead
1093 format!("\n{}{{", offset.block_only().to_string(context.config))
1100 let overhead = if fields.is_empty() { 1 } else { 0 };
1101 let max_len = context
1104 .checked_sub(offset.width())
1106 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1108 result.push_str(&offset.to_string(context.config));
1109 result.push_str(&generics_str.trim_left());
1111 result.push_str(&generics_str);
1114 if fields.is_empty() {
1115 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1116 if snippet.trim().is_empty() {
1118 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1120 result.push_str(&snippet.trim_right());
1122 result.push_str(&offset.to_string(context.config));
1124 result.push_str(&snippet);
1127 return Some(result);
1131 let one_line_budget = context
1134 .checked_sub(result.len() + 3 + offset.width())
1136 let one_line_budget =
1137 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1139 let items_str = try_opt!(rewrite_with_alignment(
1142 Shape::indented(offset, context.config),
1143 mk_sp(body_lo, span.hi),
1147 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1148 Some(format!("{} {} }}", result, items_str))
1154 .block_indent(context.config)
1155 .to_string(context.config),
1157 offset.to_string(context.config)
1162 fn format_tuple_struct(
1163 context: &RewriteContext,
1166 vis: &ast::Visibility,
1167 fields: &[ast::StructField],
1168 generics: Option<&ast::Generics>,
1171 ) -> Option<String> {
1172 let mut result = String::with_capacity(1024);
1174 let header_str = format_header(item_name, ident, vis);
1175 result.push_str(&header_str);
1177 let body_lo = if fields.is_empty() {
1178 context.codemap.span_after(span, "(")
1182 let body_hi = if fields.is_empty() {
1183 context.codemap.span_after(span, ")")
1185 // This is a dirty hack to work around a missing `)` from the span of the last field.
1186 let last_arg_span = fields[fields.len() - 1].span;
1187 if context.snippet(last_arg_span).ends_with(")") {
1192 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1196 let where_clause_str = match generics {
1198 let budget = context.budget(last_line_width(&header_str));
1199 let shape = Shape::legacy(budget, offset);
1200 let g_span = mk_sp(span.lo, body_lo);
1201 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1202 result.push_str(&generics_str);
1204 let where_budget = context.budget(last_line_width(&result));
1205 let option = WhereClauseOption::new(true, false);
1206 try_opt!(rewrite_where_clause(
1208 &generics.where_clause,
1209 context.config.item_brace_style(),
1210 Shape::legacy(where_budget, offset.block_only()),
1211 Density::Compressed,
1218 None => "".to_owned(),
1221 if fields.is_empty() {
1223 let used_width = last_line_used_width(&result, offset.width()) + 3;
1224 if used_width > context.config.max_width() {
1226 result.push_str(&offset
1227 .block_indent(context.config)
1228 .to_string(context.config))
1231 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1232 if snippet.is_empty() {
1234 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1235 result.push_str(&snippet.trim_right());
1237 result.push_str(&offset.to_string(context.config));
1239 result.push_str(&snippet);
1244 let body = try_opt!(
1248 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1250 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1251 context.config.fn_call_width(),
1255 result.push_str(&body);
1258 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1259 (result.contains('\n') ||
1260 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1261 context.config.max_width())
1263 // We need to put the where clause on a new line, but we didn't
1264 // know that earlier, so the where clause will not be indented properly.
1266 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1267 .to_string(context.config));
1269 result.push_str(&where_clause_str);
1274 pub fn rewrite_type_alias(
1275 context: &RewriteContext,
1279 generics: &ast::Generics,
1280 vis: &ast::Visibility,
1282 ) -> Option<String> {
1283 let mut result = String::new();
1285 result.push_str(&format_visibility(vis));
1286 result.push_str("type ");
1287 result.push_str(&ident.to_string());
1290 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1291 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1292 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1293 result.push_str(&generics_str);
1295 let where_budget = try_opt!(
1299 .checked_sub(last_line_width(&result))
1301 let option = WhereClauseOption::snuggled(&result);
1302 let where_clause_str = try_opt!(rewrite_where_clause(
1304 &generics.where_clause,
1305 context.config.item_brace_style(),
1306 Shape::legacy(where_budget, indent),
1307 context.config.where_density(),
1313 result.push_str(&where_clause_str);
1314 if where_clause_str.is_empty() {
1315 result.push_str(" = ");
1317 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1320 let line_width = last_line_width(&result);
1321 // This checked_sub may fail as the extra space after '=' is not taken into account
1322 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1323 let budget = context
1326 .checked_sub(indent.width() + line_width + ";".len())
1328 let type_indent = indent + line_width;
1329 // Try to fit the type on the same line
1330 let ty_str = try_opt!(
1331 ty.rewrite(context, Shape::legacy(budget, type_indent))
1333 // The line was too short, try to put the type on the next line
1335 // Remove the space after '='
1337 let type_indent = indent.block_indent(context.config);
1339 result.push_str(&type_indent.to_string(context.config));
1340 let budget = try_opt!(
1344 .checked_sub(type_indent.width() + ";".len())
1346 ty.rewrite(context, Shape::legacy(budget, type_indent))
1349 result.push_str(&ty_str);
1350 result.push_str(";");
1354 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1356 if config.space_before_type_annotation() {
1361 if config.space_after_type_annotation_colon() {
1369 pub fn rewrite_struct_field_prefix(
1370 context: &RewriteContext,
1371 field: &ast::StructField,
1372 ) -> Option<String> {
1373 let vis = format_visibility(&field.vis);
1374 let type_annotation_spacing = type_annotation_spacing(context.config);
1375 Some(match field.ident {
1376 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1377 None => format!("{}", vis),
1381 fn rewrite_struct_field_type(
1382 context: &RewriteContext,
1383 last_line_width: usize,
1384 field: &ast::StructField,
1387 ) -> Option<String> {
1388 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1391 .rewrite(context, ty_shape)
1392 .map(|ty| format!("{}{}", spacing, ty))
1395 impl Rewrite for ast::StructField {
1396 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1397 rewrite_struct_field(context, self, shape, 0)
1401 pub fn rewrite_struct_field(
1402 context: &RewriteContext,
1403 field: &ast::StructField,
1405 lhs_max_width: usize,
1406 ) -> Option<String> {
1407 if contains_skip(&field.attrs) {
1408 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1409 return wrap_str(span, context.config.max_width(), shape);
1412 let type_annotation_spacing = type_annotation_spacing(context.config);
1413 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1415 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1416 let missing_span = if field.attrs.is_empty() {
1417 mk_sp(field.span.lo, field.span.lo)
1419 mk_sp(field.attrs.last().unwrap().span.hi, field.span.lo)
1421 let mut spacing = String::from(if field.ident.is_some() {
1422 type_annotation_spacing.1
1426 // Try to put everything on a single line.
1427 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1433 is_attributes_extendable(&attrs_str),
1435 let overhead = last_line_width(&attr_prefix);
1436 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1437 for _ in 0..lhs_offset {
1440 // In this extreme case we will be missing a space betweeen an attribute and a field.
1441 if prefix.is_empty() && !attrs_str.is_empty() && is_attributes_extendable(&attrs_str) &&
1446 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1447 if let Some(ref ty) = ty_rewritten {
1448 if !ty.contains('\n') {
1449 return Some(attr_prefix + &ty);
1453 // We must use multiline.
1454 let last_line_width = last_line_width(&prefix);
1455 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1457 let type_offset = shape.indent.block_indent(context.config);
1458 let rewrite_type_in_next_line = || {
1461 .rewrite(context, Shape::indented(type_offset, context.config))
1464 let field_str = match ty_rewritten {
1465 // If we start from the next line and type fits in a single line, then do so.
1466 Some(ref ty) => match rewrite_type_in_next_line() {
1467 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1470 type_offset.to_string(&context.config),
1476 let ty = try_opt!(rewrite_type_in_next_line());
1480 type_offset.to_string(&context.config),
1485 combine_strs_with_missing_comments(
1491 is_attributes_extendable(&attrs_str),
1495 pub fn rewrite_static(
1497 vis: &ast::Visibility,
1500 mutability: ast::Mutability,
1501 expr_opt: Option<&ptr::P<ast::Expr>>,
1504 context: &RewriteContext,
1505 ) -> Option<String> {
1506 let colon = colon_spaces(
1507 context.config.space_before_type_annotation(),
1508 context.config.space_after_type_annotation_colon(),
1510 let prefix = format!(
1512 format_visibility(vis),
1514 format_mutability(mutability),
1519 let ty_str = try_opt!(ty.rewrite(
1522 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1526 if let Some(expr) = expr_opt {
1527 let lhs = format!("{}{} =", prefix, ty_str);
1529 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1534 Shape::legacy(remaining_width, offset.block_only()),
1536 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1538 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1540 Some(format!("{}{};", prefix, ty_str))
1544 pub fn rewrite_associated_type(
1546 ty_opt: Option<&ptr::P<ast::Ty>>,
1547 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1548 context: &RewriteContext,
1550 ) -> Option<String> {
1551 let prefix = format!("type {}", ident);
1553 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1555 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1556 let bounds: &[_] = ty_param_bounds;
1557 let bound_str = try_opt!(
1560 .map(|ty_bound| ty_bound.rewrite(context, shape))
1561 .collect::<Option<Vec<_>>>()
1563 if bounds.len() > 0 {
1564 format!(": {}", join_bounds(context, shape, &bound_str))
1572 if let Some(ty) = ty_opt {
1573 let ty_str = try_opt!(ty.rewrite(
1576 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1577 indent.block_only(),
1580 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1582 Some(format!("{}{};", prefix, type_bounds_str))
1586 pub fn rewrite_associated_impl_type(
1588 defaultness: ast::Defaultness,
1589 ty_opt: Option<&ptr::P<ast::Ty>>,
1590 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1591 context: &RewriteContext,
1593 ) -> Option<String> {
1594 let result = try_opt!(rewrite_associated_type(
1597 ty_param_bounds_opt,
1603 ast::Defaultness::Default => Some(format!("default {}", result)),
1608 impl Rewrite for ast::FunctionRetTy {
1609 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1611 ast::FunctionRetTy::Default(_) => Some(String::new()),
1612 ast::FunctionRetTy::Ty(ref ty) => {
1613 let inner_width = try_opt!(shape.width.checked_sub(3));
1614 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1615 .map(|r| format!("-> {}", r))
1621 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1623 ast::TyKind::Infer => {
1624 let original = context.snippet(ty.span);
1631 impl Rewrite for ast::Arg {
1632 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1633 if is_named_arg(self) {
1634 let mut result = try_opt!(
1636 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1639 if !is_empty_infer(context, &*self.ty) {
1640 if context.config.space_before_type_annotation() {
1641 result.push_str(" ");
1643 result.push_str(":");
1644 if context.config.space_after_type_annotation_colon() {
1645 result.push_str(" ");
1647 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1648 let ty_str = try_opt!(self.ty.rewrite(
1650 Shape::legacy(max_width, shape.indent + result.len()),
1652 result.push_str(&ty_str);
1657 self.ty.rewrite(context, shape)
1662 fn rewrite_explicit_self(
1663 explicit_self: &ast::ExplicitSelf,
1665 context: &RewriteContext,
1666 ) -> Option<String> {
1667 match explicit_self.node {
1668 ast::SelfKind::Region(lt, m) => {
1669 let mut_str = format_mutability(m);
1672 let lifetime_str = try_opt!(l.rewrite(
1674 Shape::legacy(context.config.max_width(), Indent::empty()),
1676 Some(format!("&{} {}self", lifetime_str, mut_str))
1678 None => Some(format!("&{}self", mut_str)),
1681 ast::SelfKind::Explicit(ref ty, _) => {
1682 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1684 let mutability = explicit_self_mutability(&args[0]);
1685 let type_str = try_opt!(ty.rewrite(
1687 Shape::legacy(context.config.max_width(), Indent::empty()),
1692 format_mutability(mutability),
1696 ast::SelfKind::Value(_) => {
1697 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1699 let mutability = explicit_self_mutability(&args[0]);
1701 Some(format!("{}self", format_mutability(mutability)))
1706 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1707 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1708 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1709 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1716 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1717 if is_named_arg(arg) {
1724 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1726 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1727 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1728 _ => arg.ty.span.hi,
1732 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1733 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1734 ident.node != symbol::keywords::Invalid.ident()
1740 // Return type is (result, force_new_line_for_brace)
1742 context: &RewriteContext,
1746 generics: &ast::Generics,
1747 unsafety: ast::Unsafety,
1748 constness: ast::Constness,
1749 defaultness: ast::Defaultness,
1751 vis: &ast::Visibility,
1753 newline_brace: bool,
1756 ) -> Option<(String, bool)> {
1757 let mut force_new_line_for_brace = false;
1759 let where_clause = &generics.where_clause;
1761 let mut result = String::with_capacity(1024);
1762 // Vis defaultness constness unsafety abi.
1763 result.push_str(&*format_visibility(vis));
1764 result.push_str(format_defaultness(defaultness));
1765 result.push_str(format_constness(constness));
1766 result.push_str(format_unsafety(unsafety));
1767 if abi != abi::Abi::Rust {
1768 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1772 result.push_str("fn ");
1773 result.push_str(&ident.to_string());
1776 let overhead = if has_braces && !newline_brace {
1783 let used_width = last_line_used_width(&result, indent.width());
1784 let one_line_budget = context
1787 .checked_sub(used_width + overhead)
1790 width: one_line_budget,
1794 let g_span = mk_sp(span.lo, fd.output.span().lo);
1795 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1796 result.push_str(&generics_str);
1798 let snuggle_angle_bracket = generics_str
1801 .map_or(false, |l| l.trim_left().len() == 1);
1803 // Note that the width and indent don't really matter, we'll re-layout the
1804 // return type later anyway.
1805 let ret_str = try_opt!(
1807 .rewrite(&context, Shape::indented(indent, context.config))
1810 let multi_line_ret_str = ret_str.contains('\n');
1811 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1814 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1825 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1831 // Check if vertical layout was forced.
1832 if one_line_budget == 0 {
1833 if snuggle_angle_bracket {
1836 if context.config.fn_args_paren_newline() {
1838 result.push_str(&arg_indent.to_string(context.config));
1839 if context.config.fn_args_layout() == IndentStyle::Visual {
1840 arg_indent = arg_indent + 1; // extra space for `(`
1844 result.push_str("(");
1845 if context.config.fn_args_layout() == IndentStyle::Visual {
1847 result.push_str(&arg_indent.to_string(context.config));
1854 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1858 // A conservative estimation, to goal is to be over all parens in generics
1859 let args_start = generics
1862 .map_or(span.lo, |tp| end_typaram(tp));
1863 let args_end = if fd.inputs.is_empty() {
1864 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1866 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1867 context.codemap.span_after(last_span, ")")
1869 let args_span = mk_sp(
1870 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1873 let arg_str = try_opt!(rewrite_args(
1876 fd.get_self().as_ref(),
1883 generics_str.contains('\n'),
1886 let put_args_in_block = match context.config.fn_args_layout() {
1887 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1889 } && !fd.inputs.is_empty();
1891 let mut args_last_line_contains_comment = false;
1892 if put_args_in_block {
1893 arg_indent = indent.block_indent(context.config);
1895 result.push_str(&arg_indent.to_string(context.config));
1896 result.push_str(&arg_str);
1898 result.push_str(&indent.to_string(context.config));
1901 result.push_str(&arg_str);
1902 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1903 // Put the closing brace on the next line if it overflows the max width.
1905 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1908 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1911 // If the last line of args contains comment, we cannot put the closing paren
1912 // on the same line.
1916 .map_or(false, |last_line| last_line.contains("//"))
1918 args_last_line_contains_comment = true;
1920 result.push_str(&arg_indent.to_string(context.config));
1926 if let ast::FunctionRetTy::Ty(..) = fd.output {
1927 let ret_should_indent = match context.config.fn_args_layout() {
1928 // If our args are block layout then we surely must have space.
1929 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1930 _ if args_last_line_contains_comment => false,
1931 _ if result.contains('\n') || multi_line_ret_str => true,
1933 // If the return type would push over the max width, then put the return type on
1934 // a new line. With the +1 for the signature length an additional space between
1935 // the closing parenthesis of the argument and the arrow '->' is considered.
1936 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1938 // If there is no where clause, take into account the space after the return type
1940 if where_clause.predicates.is_empty() {
1944 sig_length > context.config.max_width()
1947 let ret_indent = if ret_should_indent {
1948 let indent = match context.config.fn_return_indent() {
1949 ReturnIndent::WithWhereClause => indent + 4,
1950 // Aligning with non-existent args looks silly.
1951 _ if arg_str.is_empty() => {
1952 force_new_line_for_brace = true;
1955 // FIXME: we might want to check that using the arg indent
1956 // doesn't blow our budget, and if it does, then fallback to
1957 // the where clause indent.
1962 result.push_str(&indent.to_string(context.config));
1966 Indent::new(indent.block_indent, last_line_width(&result))
1969 if multi_line_ret_str || ret_should_indent {
1970 // Now that we know the proper indent and width, we need to
1971 // re-layout the return type.
1972 let ret_str = try_opt!(
1974 .rewrite(context, Shape::indented(ret_indent, context.config))
1976 result.push_str(&ret_str);
1978 result.push_str(&ret_str);
1981 // Comment between return type and the end of the decl.
1982 let snippet_lo = fd.output.span().hi;
1983 if where_clause.predicates.is_empty() {
1984 let snippet_hi = span.hi;
1985 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1986 // Try to preserve the layout of the original snippet.
1987 let original_starts_with_newline = snippet
1989 .map_or(false, |i| snippet[i..].starts_with('\n'));
1990 let original_ends_with_newline = snippet
1991 .rfind(|c| c != ' ')
1992 .map_or(false, |i| snippet[i..].ends_with('\n'));
1993 let snippet = snippet.trim();
1994 if !snippet.is_empty() {
1995 result.push(if original_starts_with_newline {
2000 result.push_str(snippet);
2001 if original_ends_with_newline {
2002 force_new_line_for_brace = true;
2008 let should_compress_where = match context.config.where_density() {
2009 Density::Compressed => !result.contains('\n'),
2010 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2014 let pos_before_where = match fd.output {
2015 ast::FunctionRetTy::Default(..) => args_span.hi,
2016 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2019 if where_clause.predicates.len() == 1 && should_compress_where {
2020 let budget = context
2023 .checked_sub(last_line_used_width(&result, indent.width()))
2025 if let Some(where_clause_str) = rewrite_where_clause(
2028 context.config.fn_brace_style(),
2029 Shape::legacy(budget, indent),
2030 Density::Compressed,
2034 WhereClauseOption::compressed(),
2036 result.push_str(&where_clause_str);
2037 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2038 return Some((result, force_new_line_for_brace));
2042 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2043 let where_clause_str = try_opt!(rewrite_where_clause(
2046 context.config.fn_brace_style(),
2047 Shape::indented(indent, context.config),
2054 // If there are neither where clause nor return type, we may be missing comments between
2056 if where_clause_str.is_empty() {
2057 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2058 let sp = mk_sp(args_span.hi, ret_span.hi);
2059 let missing_snippet = context.snippet(sp);
2060 let trimmed_snippet = missing_snippet.trim();
2061 let missing_comment = if trimmed_snippet.is_empty() {
2064 try_opt!(rewrite_comment(
2067 Shape::indented(indent, context.config),
2071 if !missing_comment.is_empty() {
2072 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
2074 let total_width = missing_comment.len() + last_line_width(&result) + 1;
2075 let force_new_line_before_comment = missing_snippet[..pos].contains('\n') ||
2076 total_width > context.config.max_width();
2077 let sep = if force_new_line_before_comment {
2078 format!("\n{}", indent.to_string(context.config))
2082 result.push_str(&sep);
2083 result.push_str(&missing_comment);
2084 force_new_line_for_brace = true;
2089 result.push_str(&where_clause_str);
2091 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2092 return Some((result, force_new_line_for_brace));
2095 struct WhereClauseOption {
2096 suppress_comma: bool, // Force no trailing comma
2097 snuggle: bool, // Do not insert newline before `where`
2098 compress_where: bool, // Try single line where clause instead of vertical layout
2101 impl WhereClauseOption {
2102 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2104 suppress_comma: suppress_comma,
2106 compress_where: false,
2110 pub fn compressed() -> WhereClauseOption {
2112 suppress_comma: true,
2114 compress_where: true,
2118 pub fn snuggled(current: &str) -> WhereClauseOption {
2120 suppress_comma: false,
2121 snuggle: trimmed_last_line_width(current) == 1,
2122 compress_where: false,
2128 context: &RewriteContext,
2130 explicit_self: Option<&ast::ExplicitSelf>,
2131 one_line_budget: usize,
2132 multi_line_budget: usize,
2137 generics_str_contains_newline: bool,
2138 ) -> Option<String> {
2139 let mut arg_item_strs = try_opt!(
2142 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2144 .collect::<Option<Vec<_>>>()
2147 // Account for sugary self.
2148 // FIXME: the comment for the self argument is dropped. This is blocked
2149 // on rust issue #27522.
2150 let min_args = explicit_self
2151 .and_then(|explicit_self| {
2152 rewrite_explicit_self(explicit_self, args, context)
2154 .map_or(1, |self_str| {
2155 arg_item_strs[0] = self_str;
2159 // Comments between args.
2160 let mut arg_items = Vec::new();
2162 arg_items.push(ListItem::from_str(""));
2165 // FIXME(#21): if there are no args, there might still be a comment, but
2166 // without spans for the comment or parens, there is no chance of
2167 // getting it right. You also don't get to put a comment on self, unless
2169 if args.len() >= min_args || variadic {
2170 let comment_span_start = if min_args == 2 {
2171 let second_arg_start = if arg_has_pattern(&args[1]) {
2176 let reduced_span = mk_sp(span.lo, second_arg_start);
2178 context.codemap.span_after_last(reduced_span, ",")
2183 enum ArgumentKind<'a> {
2184 Regular(&'a ast::Arg),
2188 let variadic_arg = if variadic {
2189 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2190 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2191 Some(ArgumentKind::Variadic(variadic_start))
2196 let more_items = itemize_list(
2198 args[min_args - 1..]
2200 .map(ArgumentKind::Regular)
2201 .chain(variadic_arg),
2204 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2205 ArgumentKind::Variadic(start) => start,
2208 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2209 ArgumentKind::Variadic(start) => start + BytePos(3),
2212 ArgumentKind::Regular(..) => None,
2213 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2220 arg_items.extend(more_items);
2223 let fits_in_one_line = !generics_str_contains_newline &&
2224 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2226 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2227 item.item = Some(arg);
2230 let last_line_ends_with_comment = arg_items
2233 .and_then(|item| item.post_comment.as_ref())
2234 .map_or(false, |s| s.trim().starts_with("//"));
2236 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2237 IndentStyle::Block if fits_in_one_line => {
2238 (indent.block_indent(context.config), SeparatorTactic::Never)
2240 IndentStyle::Block => (
2241 indent.block_indent(context.config),
2242 context.config.trailing_comma(),
2244 IndentStyle::Visual if last_line_ends_with_comment => {
2245 (arg_indent, context.config.trailing_comma())
2247 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2250 let tactic = definitive_tactic(
2252 context.config.fn_args_density().to_list_tactic(),
2256 let budget = match tactic {
2257 DefinitiveListTactic::Horizontal => one_line_budget,
2258 _ => multi_line_budget,
2261 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2263 let fmt = ListFormatting {
2266 trailing_separator: if variadic {
2267 SeparatorTactic::Never
2271 shape: Shape::legacy(budget, indent),
2272 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2273 preserve_newline: true,
2274 config: context.config,
2277 write_list(&arg_items, &fmt)
2280 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2281 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2282 ident.node != symbol::keywords::Invalid.ident()
2288 fn compute_budgets_for_args(
2289 context: &RewriteContext,
2293 newline_brace: bool,
2295 force_vertical_layout: bool,
2296 ) -> Option<((usize, usize, Indent))> {
2298 "compute_budgets_for_args {} {:?}, {}, {}",
2304 // Try keeping everything on the same line.
2305 if !result.contains('\n') && !force_vertical_layout {
2306 // 2 = `()`, 3 = `() `, space is before ret_string.
2307 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2308 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2318 let one_line_budget = context
2321 .checked_sub(used_space)
2324 if one_line_budget > 0 {
2326 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2327 IndentStyle::Block => {
2328 let indent = indent.block_indent(context.config);
2330 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2333 IndentStyle::Visual => {
2334 let indent = indent + result.len() + 1;
2335 let multi_line_overhead =
2336 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2338 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2343 return Some((one_line_budget, multi_line_budget, indent));
2347 // Didn't work. we must force vertical layout and put args on a newline.
2348 let new_indent = indent.block_indent(context.config);
2349 let used_space = match context.config.fn_args_layout() {
2351 IndentStyle::Block => new_indent.width() + 1,
2352 // Account for `)` and possibly ` {`.
2353 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2355 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2356 Some((0, max_space, new_indent))
2359 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2360 match (config.fn_brace_style(), config.where_density()) {
2361 (BraceStyle::AlwaysNextLine, _) => true,
2362 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2363 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2364 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2369 fn rewrite_generics(
2370 context: &RewriteContext,
2371 generics: &ast::Generics,
2374 ) -> Option<String> {
2375 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2376 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2377 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2378 rewrite_generics_inner(context, generics, g_shape, 0, span)
2382 fn rewrite_generics_inner(
2383 context: &RewriteContext,
2384 generics: &ast::Generics,
2386 one_line_width: usize,
2388 ) -> Option<String> {
2389 // FIXME: convert bounds to where clauses where they get too big or if
2390 // there is a where clause at all.
2391 let lifetimes: &[_] = &generics.lifetimes;
2392 let tys: &[_] = &generics.ty_params;
2393 if lifetimes.is_empty() && tys.is_empty() {
2394 return Some(String::new());
2397 // Strings for the generics.
2398 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2399 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2401 // Extract comments between generics.
2402 let lt_spans = lifetimes.iter().map(|l| {
2403 let hi = if l.bounds.is_empty() {
2406 l.bounds[l.bounds.len() - 1].span.hi
2408 mk_sp(l.lifetime.span.lo, hi)
2410 let ty_spans = tys.iter().map(|ty| ty.span());
2412 let items = itemize_list(
2414 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2418 // FIXME: don't clone
2419 |&(_, ref str)| str.clone(),
2420 context.codemap.span_after(span, "<"),
2424 format_generics_item_list(context, items, shape, one_line_width)
2427 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2428 match config.generics_indent() {
2429 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2430 IndentStyle::Block => {
2434 .block_indent(config.tab_spaces())
2435 .with_max_width(config)
2441 pub fn format_generics_item_list<I>(
2442 context: &RewriteContext,
2445 one_line_budget: usize,
2448 I: Iterator<Item = ListItem>,
2450 let item_vec = items.collect::<Vec<_>>();
2452 let tactic = definitive_tactic(
2454 ListTactic::HorizontalVertical,
2458 let fmt = ListFormatting {
2461 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2462 SeparatorTactic::Never
2464 context.config.trailing_comma()
2467 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2468 preserve_newline: true,
2469 config: context.config,
2472 let list_str = try_opt!(write_list(&item_vec, &fmt));
2474 Some(wrap_generics_with_angle_brackets(
2481 pub fn wrap_generics_with_angle_brackets(
2482 context: &RewriteContext,
2484 list_offset: Indent,
2486 if context.config.generics_indent() == IndentStyle::Block &&
2487 (list_str.contains('\n') || list_str.ends_with(','))
2491 list_offset.to_string(context.config),
2494 .block_unindent(context.config)
2495 .to_string(context.config)
2497 } else if context.config.spaces_within_angle_brackets() {
2498 format!("< {} >", list_str)
2500 format!("<{}>", list_str)
2504 fn rewrite_trait_bounds(
2505 context: &RewriteContext,
2506 type_param_bounds: &ast::TyParamBounds,
2508 ) -> Option<String> {
2509 let bounds: &[_] = type_param_bounds;
2511 if bounds.is_empty() {
2512 return Some(String::new());
2514 let bound_str = try_opt!(
2517 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2518 .collect::<Option<Vec<_>>>()
2520 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2523 fn rewrite_where_clause_rfc_style(
2524 context: &RewriteContext,
2525 where_clause: &ast::WhereClause,
2528 span_end: Option<BytePos>,
2529 span_end_before_where: BytePos,
2530 where_clause_option: WhereClauseOption,
2531 ) -> Option<String> {
2532 let block_shape = shape.block().with_max_width(context.config);
2534 let (span_before, span_after) =
2535 missing_span_before_after_where(span_end_before_where, where_clause);
2536 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2543 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2546 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2549 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2550 // each clause on one line, trailing comma (except if suppress_comma)
2551 let span_start = where_clause.predicates[0].span().lo;
2552 // If we don't have the start of the next span, then use the end of the
2553 // predicates, but that means we miss comments.
2554 let len = where_clause.predicates.len();
2555 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2556 let span_end = span_end.unwrap_or(end_of_preds);
2557 let items = itemize_list(
2559 where_clause.predicates.iter(),
2561 |pred| pred.span().lo,
2562 |pred| pred.span().hi,
2563 |pred| pred.rewrite(context, block_shape),
2568 let comma_tactic = if where_clause_option.suppress_comma {
2569 SeparatorTactic::Never
2571 context.config.trailing_comma()
2574 let fmt = ListFormatting {
2575 tactic: DefinitiveListTactic::Vertical,
2577 trailing_separator: comma_tactic,
2578 shape: clause_shape,
2579 ends_with_newline: true,
2580 preserve_newline: true,
2581 config: context.config,
2583 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2585 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2588 format!("\n{}", shape.indent.to_string(context.config))
2590 let newline_before_where = comment_separator(&comment_before, shape);
2591 let newline_after_where = comment_separator(&comment_after, clause_shape);
2594 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2595 comment_after.is_empty() && !preds_str.contains('\n') &&
2596 6 + preds_str.len() <= shape.width
2600 format!("\n{}", clause_shape.indent.to_string(context.config))
2603 "{}{}{}where{}{}{}{}",
2606 newline_before_where,
2607 newline_after_where,
2614 fn rewrite_where_clause(
2615 context: &RewriteContext,
2616 where_clause: &ast::WhereClause,
2617 brace_style: BraceStyle,
2621 span_end: Option<BytePos>,
2622 span_end_before_where: BytePos,
2623 where_clause_option: WhereClauseOption,
2624 ) -> Option<String> {
2625 if where_clause.predicates.is_empty() {
2626 return Some(String::new());
2629 if context.config.where_style() == Style::Rfc {
2630 return rewrite_where_clause_rfc_style(
2636 span_end_before_where,
2637 where_clause_option,
2641 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2643 let offset = match context.config.where_pred_indent() {
2644 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2645 // 6 = "where ".len()
2646 IndentStyle::Visual => shape.indent + extra_indent + 6,
2648 // FIXME: if where_pred_indent != Visual, then the budgets below might
2649 // be out by a char or two.
2651 let budget = context.config.max_width() - offset.width();
2652 let span_start = where_clause.predicates[0].span().lo;
2653 // If we don't have the start of the next span, then use the end of the
2654 // predicates, but that means we miss comments.
2655 let len = where_clause.predicates.len();
2656 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2657 let span_end = span_end.unwrap_or(end_of_preds);
2658 let items = itemize_list(
2660 where_clause.predicates.iter(),
2662 |pred| pred.span().lo,
2663 |pred| pred.span().hi,
2664 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2669 let item_vec = items.collect::<Vec<_>>();
2670 // FIXME: we don't need to collect here if the where_layout isn't
2671 // HorizontalVertical.
2672 let tactic = definitive_tactic(
2674 context.config.where_layout(),
2679 let mut comma_tactic = context.config.trailing_comma();
2680 // Kind of a hack because we don't usually have trailing commas in where clauses.
2681 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2682 comma_tactic = SeparatorTactic::Never;
2685 let fmt = ListFormatting {
2688 trailing_separator: comma_tactic,
2689 shape: Shape::legacy(budget, offset),
2690 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2691 preserve_newline: true,
2692 config: context.config,
2694 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2696 let end_length = if terminator == "{" {
2697 // If the brace is on the next line we don't need to count it otherwise it needs two
2700 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2701 BraceStyle::PreferSameLine => 2,
2703 } else if terminator == "=" {
2708 if density == Density::Tall || preds_str.contains('\n') ||
2709 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2713 (shape.indent + extra_indent).to_string(context.config),
2717 Some(format!(" where {}", preds_str))
2721 fn missing_span_before_after_where(
2722 before_item_span_end: BytePos,
2723 where_clause: &ast::WhereClause,
2725 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo);
2727 let pos_after_where = where_clause.span.lo + BytePos(5);
2728 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2729 (missing_span_before, missing_span_after)
2732 fn rewrite_missing_comment_in_where(
2733 context: &RewriteContext,
2736 ) -> Option<String> {
2737 let comment = comment.trim();
2738 if comment.is_empty() {
2741 rewrite_comment(comment, false, shape, context.config)
2745 fn rewrite_comments_before_after_where(
2746 context: &RewriteContext,
2747 span_before_where: Span,
2748 span_after_where: Span,
2750 ) -> Option<(String, String)> {
2751 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2753 &context.snippet(span_before_where),
2756 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2758 &context.snippet(span_after_where),
2759 shape.block_indent(context.config.tab_spaces()),
2761 Some((before_comment, after_comment))
2764 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2765 format!("{}{}{}", format_visibility(vis), item_name, ident)
2769 context: &RewriteContext,
2770 generics: &ast::Generics,
2773 brace_style: BraceStyle,
2774 force_same_line_brace: bool,
2778 ) -> Option<String> {
2779 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2780 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2782 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2783 let budget = context
2786 .checked_sub(last_line_used_width(&result, offset.width()))
2788 let option = WhereClauseOption::snuggled(&result);
2789 let where_clause_str = try_opt!(rewrite_where_clause(
2791 &generics.where_clause,
2793 Shape::legacy(budget, offset.block_only()),
2800 result.push_str(&where_clause_str);
2801 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2802 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2804 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2805 brace_style != BraceStyle::AlwaysNextLine
2807 let total_used_width = last_line_used_width(&result, used_width);
2808 let remaining_budget = context
2811 .checked_sub(total_used_width)
2813 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2814 // and hence we take the closer into account as well for one line budget.
2815 // We assume that the closer has the same length as the opener.
2816 let overhead = if force_same_line_brace {
2817 1 + opener.len() + opener.len()
2821 let forbid_same_line_brace = overhead > remaining_budget;
2822 if !forbid_same_line_brace && same_line_brace {
2826 result.push_str(&offset.block_only().to_string(context.config));
2828 result.push_str(opener);