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::{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, Separator, SeparatorTactic};
27 use rewrite::{Rewrite, RewriteContext};
28 use types::join_bounds;
29 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
30 format_constness, format_defaultness, format_mutability, format_unsafety,
31 format_visibility, last_line_used_width, last_line_width, mk_sp, semicolon_for_expr,
32 stmt_expr, trim_newlines, trimmed_last_line_width, wrap_str};
33 use vertical::rewrite_with_alignment;
34 use visitor::FmtVisitor;
36 fn type_annotation_separator(config: &Config) -> &str {
38 config.space_before_type_annotation(),
39 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 {:?} {} {:?}",
54 skip_out_of_file_lines_range!(context, self.span);
56 let mut result = "let ".to_owned();
59 let pat_shape = try_opt!(shape.offset_left(4));
61 let pat_shape = try_opt!(pat_shape.sub_width(1));
62 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
63 result.push_str(&pat_str);
65 // String that is placed within the assignment pattern and expression.
67 let mut infix = String::new();
69 if let Some(ref ty) = self.ty {
70 let separator = type_annotation_separator(context.config);
71 let indent = shape.indent + last_line_width(&result) + separator.len();
73 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
74 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
76 infix.push_str(separator);
77 infix.push_str(&rewrite);
80 if self.init.is_some() {
87 result.push_str(&infix);
89 if let Some(ref ex) = self.init {
90 // 1 = trailing semicolon;
91 let nested_shape = try_opt!(shape.sub_width(1));
93 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
101 // TODO convert to using rewrite style rather than visitor
102 // TODO format modules in this style
105 keyword: &'static str,
107 vis: Option<&'a ast::Visibility>,
108 body: Vec<BodyElement<'a>>,
113 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
114 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
117 format!("extern {}", fm.abi)
125 .map(|i| BodyElement::ForeignItem(i))
132 enum BodyElement<'a> {
133 // Stmt(&'a ast::Stmt),
134 // Field(&'a ast::Field),
135 // Variant(&'a ast::Variant),
136 // Item(&'a ast::Item),
137 ForeignItem(&'a ast::ForeignItem),
140 impl<'a> FmtVisitor<'a> {
141 fn format_item(&mut self, item: Item) {
142 self.buffer.push_str(&item.abi);
143 self.buffer.push_str(" ");
145 let snippet = self.snippet(item.span);
146 let brace_pos = snippet.find_uncommented("{").unwrap();
148 self.buffer.push_str("{");
149 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
150 // FIXME: this skips comments between the extern keyword and the opening
152 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
153 self.block_indent = self.block_indent.block_indent(self.config);
155 if item.body.is_empty() {
156 self.format_missing_no_indent(item.span.hi - BytePos(1));
157 self.block_indent = self.block_indent.block_unindent(self.config);
160 .push_str(&self.block_indent.to_string(self.config));
162 for item in &item.body {
163 self.format_body_element(item);
166 self.block_indent = self.block_indent.block_unindent(self.config);
167 self.format_missing_with_indent(item.span.hi - BytePos(1));
171 self.buffer.push_str("}");
172 self.last_pos = item.span.hi;
175 fn format_body_element(&mut self, element: &BodyElement) {
177 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
181 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
182 let item = Item::from_foreign_mod(fm, span, self.config);
183 self.format_item(item);
186 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
187 self.format_missing_with_indent(item.span.lo);
188 // Drop semicolon or it will be interpreted as comment.
189 // FIXME: this may be a faulty span from libsyntax.
190 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
193 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
194 let indent = self.block_indent;
195 let rewrite = rewrite_fn_base(
201 ast::Unsafety::Normal,
202 ast::Constness::NotConst,
203 ast::Defaultness::Final,
204 // These are not actually rust functions,
205 // but we format them as such.
215 Some((new_fn, _)) => {
216 self.buffer.push_str(&new_fn);
217 self.buffer.push_str(";");
219 None => self.format_missing(item.span.hi),
222 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
223 // FIXME(#21): we're dropping potential comments in between the
224 // function keywords here.
225 let vis = format_visibility(&item.vis);
226 let mut_str = if is_mutable { "mut " } else { "" };
227 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
228 let offset = self.block_indent + prefix.len();
230 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
231 let rewrite = ty.rewrite(&self.get_context(), shape);
235 self.buffer.push_str(&prefix);
236 self.buffer.push_str(&result);
237 self.buffer.push_str(";");
239 None => self.format_missing(item.span.hi),
244 self.last_pos = item.span.hi;
252 generics: &ast::Generics,
253 unsafety: ast::Unsafety,
254 constness: ast::Constness,
255 defaultness: ast::Defaultness,
257 vis: &ast::Visibility,
260 ) -> Option<String> {
261 let context = self.get_context();
263 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
264 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
265 !context.config.fn_empty_single_line();
266 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause, has_body);
268 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
285 if force_newline_brace {
286 newline_brace = true;
287 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
288 !result.contains('\n')
290 newline_brace = false;
293 // Prepare for the function body by possibly adding a newline and
295 // FIXME we'll miss anything between the end of the signature and the
296 // start of the body, but we need more spans from the compiler to solve
300 result.push_str(&indent.to_string(self.config));
305 self.single_line_fn(&result, block).or_else(|| Some(result))
308 pub fn rewrite_required_fn(
312 sig: &ast::MethodSig,
314 ) -> Option<String> {
315 // Drop semicolon or it will be interpreted as comment.
316 let span = mk_sp(span.lo, span.hi - BytePos(1));
317 let context = self.get_context();
319 let (mut result, _) = try_opt!(rewrite_fn_base(
327 ast::Defaultness::Final,
329 &ast::Visibility::Inherited,
336 // Re-attach semicolon
342 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
343 if fn_str.contains('\n') {
347 let codemap = self.get_context().codemap;
349 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
350 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
352 return Some(format!("{}{{}}", fn_str));
355 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
357 if let Some(ref stmt) = block.stmts.first() {
358 match stmt_expr(stmt) {
360 let suffix = if semicolon_for_expr(&self.get_context(), e) {
370 Shape::indented(self.block_indent, self.config),
371 ).map(|s| s + suffix)
372 .or_else(|| Some(self.snippet(e.span)))
374 None => stmt.rewrite(
376 Shape::indented(self.block_indent, self.config),
384 if let Some(res) = rewrite {
385 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
386 if !res.contains('\n') && width <= self.config.max_width() {
387 return Some(format!("{}{{ {} }}", fn_str, res));
398 vis: &ast::Visibility,
399 enum_def: &ast::EnumDef,
400 generics: &ast::Generics,
403 let enum_header = format_header("enum ", ident, vis);
404 self.buffer.push_str(&enum_header);
406 let enum_snippet = self.snippet(span);
407 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
408 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
409 let generics_str = format_generics(
414 self.config.item_brace_style(),
415 enum_def.variants.is_empty(),
417 mk_sp(span.lo, body_start),
418 last_line_width(&enum_header),
420 self.buffer.push_str(&generics_str);
422 self.last_pos = body_start;
424 self.block_indent = self.block_indent.block_indent(self.config);
425 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
427 Some(ref body_str) => self.buffer.push_str(body_str),
428 None => if contains_comment(&enum_snippet[brace_pos..]) {
429 self.format_missing_no_indent(span.hi - BytePos(1))
431 self.format_missing(span.hi - BytePos(1))
434 self.block_indent = self.block_indent.block_unindent(self.config);
436 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
438 .push_str(&self.block_indent.to_string(self.config));
440 self.buffer.push_str("}");
441 self.last_pos = span.hi;
444 // Format the body of an enum definition
445 fn format_variant_list(
447 enum_def: &ast::EnumDef,
450 ) -> Option<String> {
451 if enum_def.variants.is_empty() {
454 let mut result = String::with_capacity(1024);
456 let indentation = self.block_indent.to_string(self.config);
457 result.push_str(&indentation);
459 let items = itemize_list(
461 enum_def.variants.iter(),
463 |f| if !f.node.attrs.is_empty() {
464 f.node.attrs[0].span.lo
469 |f| self.format_variant(f),
474 let shape = Shape::indented(self.block_indent, self.config)
477 let fmt = ListFormatting {
478 tactic: DefinitiveListTactic::Vertical,
480 trailing_separator: self.config.trailing_comma(),
482 ends_with_newline: true,
483 preserve_newline: true,
487 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
488 result.push_str(&list);
493 // Variant of an enum.
494 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
495 if contains_skip(&field.node.attrs) {
496 let lo = field.node.attrs[0].span.lo;
497 let span = mk_sp(lo, field.span.hi);
498 return Some(self.snippet(span));
501 let context = self.get_context();
502 let indent = self.block_indent;
503 let mut result = try_opt!(
507 .rewrite(&context, Shape::indented(indent, self.config))
509 if !result.is_empty() {
511 width: context.config.max_width(),
512 indent: self.block_indent,
513 offset: self.block_indent.alignment,
515 let missing_comment = rewrite_missing_comment_on_field(
518 field.node.attrs[field.node.attrs.len() - 1].span.hi,
521 ).unwrap_or(String::new());
522 result.push_str(&missing_comment);
525 let variant_body = match field.node.data {
526 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
527 // FIXME: Should limit the width, as we have a trailing comma
532 &ast::Visibility::Inherited,
537 Some(self.config.struct_variant_width()),
540 ast::VariantData::Unit(..) => {
541 let tag = if let Some(ref expr) = field.node.disr_expr {
542 format!("{} = {}", field.node.name, self.snippet(expr.span))
544 field.node.name.to_string()
549 self.config.max_width(),
550 Shape::indented(indent, self.config),
555 if let Some(variant_str) = variant_body {
556 result.push_str(&variant_str);
565 context: &RewriteContext,
568 where_span_end: Option<BytePos>,
569 ) -> Option<String> {
570 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
571 let mut result = String::new();
572 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
573 result.push_str(&ref_and_type);
575 let where_budget = if result.contains('\n') {
576 context.config.max_width()
581 .checked_sub(last_line_width(&result))
584 let option = WhereClauseOption::snuggled(&ref_and_type);
585 let where_clause_str = try_opt!(rewrite_where_clause(
587 &generics.where_clause,
588 context.config.item_brace_style(),
589 Shape::legacy(where_budget, offset.block_only()),
590 context.config.where_density(),
597 if try_opt!(is_impl_single_line(
604 result.push_str(&where_clause_str);
605 if where_clause_str.contains('\n') {
606 let white_space = offset.to_string(context.config);
607 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
609 result.push_str(" {}");
614 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
616 let width = offset.block_indent + context.config.tab_spaces() - 1;
617 let where_indent = Indent::new(0, width);
618 result.push_str(&where_indent.to_string(context.config));
620 result.push_str(&where_clause_str);
622 match context.config.item_brace_style() {
623 BraceStyle::AlwaysNextLine => {
625 result.push_str(&offset.to_string(context.config));
627 BraceStyle::PreferSameLine => result.push(' '),
628 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
630 result.push_str(&offset.to_string(context.config));
638 let snippet = context.snippet(item.span);
639 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
641 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
642 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
643 visitor.block_indent = offset.block_only().block_indent(context.config);
644 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
646 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
648 visitor.visit_impl_item(item);
651 visitor.format_missing(item.span.hi - BytePos(1));
653 let inner_indent_str = visitor.block_indent.to_string(context.config);
654 let outer_indent_str = offset.block_only().to_string(context.config);
657 result.push_str(&inner_indent_str);
658 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
660 result.push_str(&outer_indent_str);
663 if result.chars().last().unwrap() == '{' {
665 result.push_str(&offset.to_string(context.config));
675 fn is_impl_single_line(
676 context: &RewriteContext,
679 where_clause_str: &str,
682 let snippet = context.snippet(item.span);
683 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
686 context.config.impl_empty_single_line() && items.is_empty() &&
687 result.len() + where_clause_str.len() <= context.config.max_width() &&
688 !contains_comment(&snippet[open_pos..]),
692 fn format_impl_ref_and_type(
693 context: &RewriteContext,
696 ) -> Option<String> {
697 if let ast::ItemKind::Impl(
707 let mut result = String::new();
709 result.push_str(&format_visibility(&item.vis));
710 result.push_str(&format_defaultness(defaultness));
711 result.push_str(format_unsafety(unsafety));
712 result.push_str("impl");
714 let lo = context.codemap.span_after(item.span, "impl");
715 let hi = match *trait_ref {
716 Some(ref tr) => tr.path.span.lo,
717 None => self_ty.span.lo,
719 let shape = try_opt!(generics_shape_from_config(
721 Shape::indented(offset + last_line_width(&result), context.config),
724 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
725 let generics_str = try_opt!(rewrite_generics_inner(
733 let polarity_str = if polarity == ast::ImplPolarity::Negative {
739 if let Some(ref trait_ref) = *trait_ref {
740 let result_len = result.len();
741 if let Some(trait_ref_str) = rewrite_trait_ref(
750 result.push_str(&trait_ref_str);
752 let generics_str = try_opt!(rewrite_generics_inner(
759 result.push_str(&try_opt!(rewrite_trait_ref(
770 result.push_str(&generics_str);
773 // Try to put the self type in a single line.
775 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
776 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
777 // If there is no where clause adapt budget for type formatting to take space and curly
778 // brace into account.
779 match context.config.item_brace_style() {
780 BraceStyle::AlwaysNextLine => 0,
786 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
787 // 1 = space before the type.
791 .checked_sub(used_space + 1)
793 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
794 if !self_ty_str.contains('\n') {
795 if trait_ref.is_some() {
796 result.push_str(" for ");
800 result.push_str(&self_ty_str);
805 // Couldn't fit the self type on a single line, put it on a new line.
807 // Add indentation of one additional tab.
808 let new_line_offset = offset.block_indent(context.config);
809 result.push_str(&new_line_offset.to_string(context.config));
810 if trait_ref.is_some() {
811 result.push_str("for ");
813 let budget = context.config.max_width() - last_line_width(&result);
814 let type_offset = match context.config.where_style() {
815 Style::Legacy => new_line_offset + trait_ref_overhead,
816 Style::Rfc => new_line_offset,
818 result.push_str(&*try_opt!(
819 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
827 fn rewrite_trait_ref(
828 context: &RewriteContext,
829 trait_ref: &ast::TraitRef,
835 ) -> Option<String> {
836 // 1 = space between generics and trait_ref
837 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
838 let shape = Shape::indented(offset + used_space, context.config);
839 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
840 if !(retry && trait_ref_str.contains('\n')) {
849 // We could not make enough space for trait_ref, so put it on new line.
851 let offset = offset.block_indent(context.config);
852 let shape = Shape::indented(offset, context.config);
853 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
857 &offset.to_string(context.config),
866 pub fn format_struct(
867 context: &RewriteContext,
870 vis: &ast::Visibility,
871 struct_def: &ast::VariantData,
872 generics: Option<&ast::Generics>,
875 one_line_width: Option<usize>,
876 ) -> Option<String> {
878 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
879 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
889 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
903 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
904 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
907 let mut result = String::new();
908 let header = format!(
910 format_visibility(&item.vis),
911 format_unsafety(unsafety),
915 result.push_str(&header);
917 let body_lo = context.codemap.span_after(item.span, "{");
919 let shape = Shape::indented(offset + last_line_width(&result), context.config);
920 let generics_str = try_opt!(rewrite_generics(
924 mk_sp(item.span.lo, body_lo),
926 result.push_str(&generics_str);
928 let trait_bound_str = try_opt!(rewrite_trait_bounds(
931 Shape::indented(offset, context.config),
933 // If the trait, generics, and trait bound cannot fit on the same line,
934 // put the trait bounds on an indented new line
935 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
936 context.config.comment_width()
939 let trait_indent = offset.block_only().block_indent(context.config);
940 result.push_str(&trait_indent.to_string(context.config));
942 result.push_str(&trait_bound_str);
944 let has_body = !trait_items.is_empty();
946 let where_density = if (context.config.where_density() == Density::Compressed &&
947 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
948 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
949 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
950 !result.contains('\n'))
957 let where_budget = try_opt!(
961 .checked_sub(last_line_width(&result))
963 let pos_before_where = if type_param_bounds.is_empty() {
964 if generics.where_clause.predicates.is_empty() {
965 // We do not use this, so it does not matter
968 let snippet = context.snippet(item.span);
969 let where_pos = snippet.find_uncommented("where");
970 item.span.lo + where_pos.map_or(BytePos(0), |p| BytePos(p as u32))
973 type_param_bounds[type_param_bounds.len() - 1].span().hi
975 let option = WhereClauseOption::snuggled(&generics_str);
976 let where_clause_str = try_opt!(rewrite_where_clause(
978 &generics.where_clause,
979 context.config.item_brace_style(),
980 Shape::legacy(where_budget, offset.block_only()),
987 // If the where clause cannot fit on the same line,
988 // put the where clause on a new line
989 if !where_clause_str.contains('\n') &&
990 last_line_width(&result) + where_clause_str.len() + offset.width() >
991 context.config.comment_width()
994 let width = offset.block_indent + context.config.tab_spaces() - 1;
995 let where_indent = Indent::new(0, width);
996 result.push_str(&where_indent.to_string(context.config));
998 result.push_str(&where_clause_str);
1000 match context.config.item_brace_style() {
1001 BraceStyle::AlwaysNextLine => {
1003 result.push_str(&offset.to_string(context.config));
1005 BraceStyle::PreferSameLine => result.push(' '),
1006 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1007 (!trait_items.is_empty() || result.contains('\n'))
1010 result.push_str(&offset.to_string(context.config));
1017 let snippet = context.snippet(item.span);
1018 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1020 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1021 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1022 visitor.block_indent = offset.block_only().block_indent(context.config);
1023 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1025 for item in trait_items {
1026 visitor.visit_trait_item(item);
1029 visitor.format_missing(item.span.hi - BytePos(1));
1031 let inner_indent_str = visitor.block_indent.to_string(context.config);
1032 let outer_indent_str = offset.block_only().to_string(context.config);
1035 result.push_str(&inner_indent_str);
1036 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1038 result.push_str(&outer_indent_str);
1039 } else if result.contains('\n') {
1050 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1051 format!("{};", format_header(item_name, ident, vis))
1054 pub fn format_struct_struct(
1055 context: &RewriteContext,
1058 vis: &ast::Visibility,
1059 fields: &[ast::StructField],
1060 generics: Option<&ast::Generics>,
1063 one_line_width: Option<usize>,
1064 ) -> Option<String> {
1065 let mut result = String::with_capacity(1024);
1067 let header_str = format_header(item_name, ident, vis);
1068 result.push_str(&header_str);
1070 let body_lo = context.codemap.span_after(span, "{");
1072 let generics_str = match generics {
1073 Some(g) => try_opt!(format_generics(
1078 context.config.item_brace_style(),
1081 mk_sp(span.lo, body_lo),
1082 last_line_width(&result),
1085 // 3 = ` {}`, 2 = ` {`.
1086 let overhead = if fields.is_empty() { 3 } else { 2 };
1087 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1088 !fields.is_empty()) ||
1092 .checked_sub(result.len())
1093 .unwrap_or(0) < overhead
1095 format!("\n{}{{", offset.block_only().to_string(context.config))
1102 let overhead = if fields.is_empty() { 1 } else { 0 };
1103 let max_len = context
1106 .checked_sub(offset.width())
1108 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1110 result.push_str(&offset.to_string(context.config));
1111 result.push_str(&generics_str.trim_left());
1113 result.push_str(&generics_str);
1116 if fields.is_empty() {
1117 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1118 if snippet.trim().is_empty() {
1120 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1122 result.push_str(&snippet.trim_right());
1124 result.push_str(&offset.to_string(context.config));
1126 result.push_str(&snippet);
1129 return Some(result);
1133 let one_line_budget = context
1136 .checked_sub(result.len() + 3 + offset.width())
1138 let one_line_budget =
1139 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1141 let items_str = try_opt!(rewrite_with_alignment(
1144 Shape::indented(offset, context.config),
1145 mk_sp(body_lo, span.hi),
1149 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1150 Some(format!("{} {} }}", result, items_str))
1156 .block_indent(context.config)
1157 .to_string(context.config),
1159 offset.to_string(context.config)
1164 fn format_tuple_struct(
1165 context: &RewriteContext,
1168 vis: &ast::Visibility,
1169 fields: &[ast::StructField],
1170 generics: Option<&ast::Generics>,
1173 ) -> Option<String> {
1174 let mut result = String::with_capacity(1024);
1176 let header_str = format_header(item_name, ident, vis);
1177 result.push_str(&header_str);
1179 let body_lo = if fields.is_empty() {
1180 context.codemap.span_after(span, "(")
1184 let body_hi = if fields.is_empty() {
1185 context.codemap.span_after(span, ")")
1187 // This is a dirty hack to work around a missing `)` from the span of the last field.
1188 let last_arg_span = fields[fields.len() - 1].span;
1189 if context.snippet(last_arg_span).ends_with(")") {
1194 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1198 let where_clause_str = match generics {
1200 let budget = context.budget(last_line_width(&header_str));
1201 let shape = Shape::legacy(budget, offset);
1202 let g_span = mk_sp(span.lo, body_lo);
1203 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1204 result.push_str(&generics_str);
1206 let where_budget = context.budget(last_line_width(&result));
1207 let option = WhereClauseOption::new(true, false);
1208 try_opt!(rewrite_where_clause(
1210 &generics.where_clause,
1211 context.config.item_brace_style(),
1212 Shape::legacy(where_budget, offset.block_only()),
1213 Density::Compressed,
1220 None => "".to_owned(),
1223 if fields.is_empty() {
1225 let used_width = last_line_used_width(&result, offset.width()) + 3;
1226 if used_width > context.config.max_width() {
1228 result.push_str(&offset
1229 .block_indent(context.config)
1230 .to_string(context.config))
1233 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1234 if snippet.is_empty() {
1236 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1237 result.push_str(&snippet.trim_right());
1239 result.push_str(&offset.to_string(context.config));
1241 result.push_str(&snippet);
1246 let body = try_opt!(
1250 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1252 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1253 context.config.fn_call_width(),
1257 result.push_str(&body);
1260 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1261 (result.contains('\n') ||
1262 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1263 context.config.max_width())
1265 // We need to put the where clause on a new line, but we didn't
1266 // know that earlier, so the where clause will not be indented properly.
1268 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1269 .to_string(context.config));
1271 result.push_str(&where_clause_str);
1276 pub fn rewrite_type_alias(
1277 context: &RewriteContext,
1281 generics: &ast::Generics,
1282 vis: &ast::Visibility,
1284 ) -> Option<String> {
1285 let mut result = String::new();
1287 result.push_str(&format_visibility(vis));
1288 result.push_str("type ");
1289 result.push_str(&ident.to_string());
1292 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1293 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1294 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1295 result.push_str(&generics_str);
1297 let where_budget = try_opt!(
1301 .checked_sub(last_line_width(&result))
1303 let option = WhereClauseOption::snuggled(&result);
1304 let where_clause_str = try_opt!(rewrite_where_clause(
1306 &generics.where_clause,
1307 context.config.item_brace_style(),
1308 Shape::legacy(where_budget, indent),
1309 context.config.where_density(),
1315 result.push_str(&where_clause_str);
1316 result.push_str(" = ");
1318 let line_width = last_line_width(&result);
1319 // This checked_sub may fail as the extra space after '=' is not taken into account
1320 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1321 let budget = context
1324 .checked_sub(indent.width() + line_width + ";".len())
1326 let type_indent = indent + line_width;
1327 // Try to fit the type on the same line
1328 let ty_str = try_opt!(
1329 ty.rewrite(context, Shape::legacy(budget, type_indent))
1331 // The line was too short, try to put the type on the next line
1333 // Remove the space after '='
1335 let type_indent = indent.block_indent(context.config);
1337 result.push_str(&type_indent.to_string(context.config));
1338 let budget = try_opt!(
1342 .checked_sub(type_indent.width() + ";".len())
1344 ty.rewrite(context, Shape::legacy(budget, type_indent))
1347 result.push_str(&ty_str);
1348 result.push_str(";");
1352 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1354 if config.space_before_type_annotation() {
1359 if config.space_after_type_annotation_colon() {
1367 fn rewrite_missing_comment_on_field(
1368 context: &RewriteContext,
1372 result: &mut String,
1373 ) -> Option<String> {
1374 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1375 let newline_index = possibly_comment_snippet.find('\n');
1376 let comment_index = possibly_comment_snippet.find('/');
1377 match (newline_index, comment_index) {
1378 (Some(i), Some(j)) if i > j => result.push(' '),
1381 result.push_str(&shape.indent.to_string(context.config));
1384 let trimmed = possibly_comment_snippet.trim();
1385 if trimmed.is_empty() {
1388 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1389 format!("{}\n{}", s, shape.indent.to_string(context.config))
1394 pub fn rewrite_struct_field_prefix(
1395 context: &RewriteContext,
1396 field: &ast::StructField,
1398 ) -> Option<String> {
1399 let vis = format_visibility(&field.vis);
1400 let mut attr_str = try_opt!(
1403 .rewrite(context, Shape::indented(shape.indent, context.config))
1405 // Try format missing comments after attributes
1406 let missing_comment = if !field.attrs.is_empty() {
1407 rewrite_missing_comment_on_field(
1410 field.attrs[field.attrs.len() - 1].span.hi,
1413 ).unwrap_or(String::new())
1418 let type_annotation_spacing = type_annotation_spacing(context.config);
1419 Some(match field.ident {
1420 Some(name) => format!(
1426 type_annotation_spacing.0
1428 None => format!("{}{}{}", attr_str, missing_comment, vis),
1432 fn rewrite_struct_field_type(
1433 context: &RewriteContext,
1434 last_line_width: usize,
1435 field: &ast::StructField,
1438 ) -> Option<String> {
1439 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1442 .rewrite(context, ty_shape)
1443 .map(|ty| format!("{}{}", spacing, ty))
1446 impl Rewrite for ast::StructField {
1447 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1448 rewrite_struct_field(context, self, shape, 0)
1452 pub fn rewrite_struct_field(
1453 context: &RewriteContext,
1454 field: &ast::StructField,
1456 lhs_max_width: usize,
1457 ) -> Option<String> {
1458 if contains_skip(&field.attrs) {
1459 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1460 return wrap_str(span, context.config.max_width(), shape);
1463 let type_annotation_spacing = type_annotation_spacing(context.config);
1464 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1466 // Try to put everything on a single line.
1467 let last_line_width = last_line_width(&prefix);
1468 let mut spacing = String::from(if field.ident.is_some() {
1469 type_annotation_spacing.1
1473 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1474 for _ in 0..lhs_offset {
1477 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1478 if let Some(ref ty) = ty_rewritten {
1479 if !ty.contains('\n') {
1480 return Some(prefix + &ty);
1484 // We must use multiline.
1485 let type_offset = shape.indent.block_indent(context.config);
1486 let rewrite_type_in_next_line = || {
1489 .rewrite(context, Shape::indented(type_offset, context.config))
1492 match ty_rewritten {
1493 // If we start from the next line and type fits in a single line, then do so.
1494 Some(ref ty) => match rewrite_type_in_next_line() {
1495 Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
1498 type_offset.to_string(&context.config),
1501 _ => Some(prefix + &ty),
1504 let ty = try_opt!(rewrite_type_in_next_line());
1508 type_offset.to_string(&context.config),
1515 pub fn rewrite_static(
1517 vis: &ast::Visibility,
1520 mutability: ast::Mutability,
1521 expr_opt: Option<&ptr::P<ast::Expr>>,
1524 context: &RewriteContext,
1525 ) -> Option<String> {
1526 let colon = colon_spaces(
1527 context.config.space_before_type_annotation(),
1528 context.config.space_after_type_annotation_colon(),
1530 let prefix = format!(
1532 format_visibility(vis),
1534 format_mutability(mutability),
1539 let ty_str = try_opt!(ty.rewrite(
1542 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1546 if let Some(expr) = expr_opt {
1547 let lhs = format!("{}{} =", prefix, ty_str);
1549 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1554 Shape::legacy(remaining_width, offset.block_only()),
1556 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1558 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1560 Some(format!("{}{};", prefix, ty_str))
1564 pub fn rewrite_associated_type(
1566 ty_opt: Option<&ptr::P<ast::Ty>>,
1567 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1568 context: &RewriteContext,
1570 ) -> Option<String> {
1571 let prefix = format!("type {}", ident);
1573 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1574 let shape = Shape::indented(indent, context.config);
1575 let bounds: &[_] = ty_param_bounds;
1576 let bound_str = try_opt!(
1579 .map(|ty_bound| ty_bound.rewrite(context, shape))
1580 .collect::<Option<Vec<_>>>()
1582 if bounds.len() > 0 {
1583 format!(": {}", join_bounds(context, shape, &bound_str))
1591 if let Some(ty) = ty_opt {
1592 let ty_str = try_opt!(ty.rewrite(
1595 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1596 indent.block_only(),
1599 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1601 Some(format!("{}{};", prefix, type_bounds_str))
1605 pub fn rewrite_associated_impl_type(
1607 defaultness: ast::Defaultness,
1608 ty_opt: Option<&ptr::P<ast::Ty>>,
1609 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1610 context: &RewriteContext,
1612 ) -> Option<String> {
1613 let result = try_opt!(rewrite_associated_type(
1616 ty_param_bounds_opt,
1622 ast::Defaultness::Default => Some(format!("default {}", result)),
1627 impl Rewrite for ast::FunctionRetTy {
1628 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1630 ast::FunctionRetTy::Default(_) => Some(String::new()),
1631 ast::FunctionRetTy::Ty(ref ty) => {
1632 let inner_width = try_opt!(shape.width.checked_sub(3));
1633 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1634 .map(|r| format!("-> {}", r))
1640 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1642 ast::TyKind::Infer => {
1643 let original = context.snippet(ty.span);
1650 impl Rewrite for ast::Arg {
1651 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1652 if is_named_arg(self) {
1653 let mut result = try_opt!(
1655 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1658 if !is_empty_infer(context, &*self.ty) {
1659 if context.config.space_before_type_annotation() {
1660 result.push_str(" ");
1662 result.push_str(":");
1663 if context.config.space_after_type_annotation_colon() {
1664 result.push_str(" ");
1666 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1667 let ty_str = try_opt!(self.ty.rewrite(
1669 Shape::legacy(max_width, shape.indent + result.len()),
1671 result.push_str(&ty_str);
1676 self.ty.rewrite(context, shape)
1681 fn rewrite_explicit_self(
1682 explicit_self: &ast::ExplicitSelf,
1684 context: &RewriteContext,
1685 ) -> Option<String> {
1686 match explicit_self.node {
1687 ast::SelfKind::Region(lt, m) => {
1688 let mut_str = format_mutability(m);
1691 let lifetime_str = try_opt!(l.rewrite(
1693 Shape::legacy(context.config.max_width(), Indent::empty()),
1695 Some(format!("&{} {}self", lifetime_str, mut_str))
1697 None => Some(format!("&{}self", mut_str)),
1700 ast::SelfKind::Explicit(ref ty, _) => {
1701 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1703 let mutability = explicit_self_mutability(&args[0]);
1704 let type_str = try_opt!(ty.rewrite(
1706 Shape::legacy(context.config.max_width(), Indent::empty()),
1711 format_mutability(mutability),
1715 ast::SelfKind::Value(_) => {
1716 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1718 let mutability = explicit_self_mutability(&args[0]);
1720 Some(format!("{}self", format_mutability(mutability)))
1725 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1726 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1727 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1728 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1735 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1736 if is_named_arg(arg) {
1743 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1745 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1746 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1747 _ => arg.ty.span.hi,
1751 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1752 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1753 ident.node != symbol::keywords::Invalid.ident()
1759 // Return type is (result, force_new_line_for_brace)
1761 context: &RewriteContext,
1765 generics: &ast::Generics,
1766 unsafety: ast::Unsafety,
1767 constness: ast::Constness,
1768 defaultness: ast::Defaultness,
1770 vis: &ast::Visibility,
1772 newline_brace: bool,
1775 ) -> Option<(String, bool)> {
1776 let mut force_new_line_for_brace = false;
1778 let where_clause = &generics.where_clause;
1780 let mut result = String::with_capacity(1024);
1781 // Vis defaultness constness unsafety abi.
1782 result.push_str(&*format_visibility(vis));
1783 result.push_str(format_defaultness(defaultness));
1784 result.push_str(format_constness(constness));
1785 result.push_str(format_unsafety(unsafety));
1786 if abi != abi::Abi::Rust {
1787 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1791 result.push_str("fn ");
1792 result.push_str(&ident.to_string());
1795 let overhead = if has_braces && !newline_brace {
1802 let used_width = last_line_used_width(&result, indent.width());
1803 let one_line_budget = context
1806 .checked_sub(used_width + overhead)
1809 width: one_line_budget,
1813 let g_span = mk_sp(span.lo, fd.output.span().lo);
1814 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1815 result.push_str(&generics_str);
1817 let snuggle_angle_bracket = generics_str
1820 .map_or(false, |l| l.trim_left().len() == 1);
1822 // Note that the width and indent don't really matter, we'll re-layout the
1823 // return type later anyway.
1824 let ret_str = try_opt!(
1826 .rewrite(&context, Shape::indented(indent, context.config))
1829 let multi_line_ret_str = ret_str.contains('\n');
1830 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1833 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1844 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1850 // Check if vertical layout was forced.
1851 if one_line_budget == 0 {
1852 if snuggle_angle_bracket {
1855 if context.config.fn_args_paren_newline() {
1857 result.push_str(&arg_indent.to_string(context.config));
1858 if context.config.fn_args_layout() == IndentStyle::Visual {
1859 arg_indent = arg_indent + 1; // extra space for `(`
1863 result.push_str("(");
1864 if context.config.fn_args_layout() == IndentStyle::Visual {
1866 result.push_str(&arg_indent.to_string(context.config));
1873 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1877 // A conservative estimation, to goal is to be over all parens in generics
1878 let args_start = generics
1881 .map_or(span.lo, |tp| end_typaram(tp));
1882 let args_end = if fd.inputs.is_empty() {
1883 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1885 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1886 context.codemap.span_after(last_span, ")")
1888 let args_span = mk_sp(
1889 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1892 let arg_str = try_opt!(rewrite_args(
1895 fd.get_self().as_ref(),
1902 generics_str.contains('\n'),
1905 let put_args_in_block = match context.config.fn_args_layout() {
1906 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1908 } && !fd.inputs.is_empty();
1910 let mut args_last_line_contains_comment = false;
1911 if put_args_in_block {
1912 arg_indent = indent.block_indent(context.config);
1914 result.push_str(&arg_indent.to_string(context.config));
1915 result.push_str(&arg_str);
1917 result.push_str(&indent.to_string(context.config));
1920 result.push_str(&arg_str);
1921 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1922 // Put the closing brace on the next line if it overflows the max width.
1924 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1927 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1930 // If the last line of args contains comment, we cannot put the closing paren
1931 // on the same line.
1935 .map_or(false, |last_line| last_line.contains("//"))
1937 args_last_line_contains_comment = true;
1939 result.push_str(&arg_indent.to_string(context.config));
1945 if let ast::FunctionRetTy::Ty(..) = fd.output {
1946 let ret_should_indent = match context.config.fn_args_layout() {
1947 // If our args are block layout then we surely must have space.
1948 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1949 _ if args_last_line_contains_comment => false,
1950 _ if result.contains('\n') || multi_line_ret_str => true,
1952 // If the return type would push over the max width, then put the return type on
1953 // a new line. With the +1 for the signature length an additional space between
1954 // the closing parenthesis of the argument and the arrow '->' is considered.
1955 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1957 // If there is no where clause, take into account the space after the return type
1959 if where_clause.predicates.is_empty() {
1963 sig_length > context.config.max_width()
1966 let ret_indent = if ret_should_indent {
1967 let indent = match context.config.fn_return_indent() {
1968 ReturnIndent::WithWhereClause => indent + 4,
1969 // Aligning with non-existent args looks silly.
1970 _ if arg_str.is_empty() => {
1971 force_new_line_for_brace = true;
1974 // FIXME: we might want to check that using the arg indent
1975 // doesn't blow our budget, and if it does, then fallback to
1976 // the where clause indent.
1981 result.push_str(&indent.to_string(context.config));
1985 Indent::new(indent.block_indent, last_line_width(&result))
1988 if multi_line_ret_str || ret_should_indent {
1989 // Now that we know the proper indent and width, we need to
1990 // re-layout the return type.
1991 let ret_str = try_opt!(
1993 .rewrite(context, Shape::indented(ret_indent, context.config))
1995 result.push_str(&ret_str);
1997 result.push_str(&ret_str);
2000 // Comment between return type and the end of the decl.
2001 let snippet_lo = fd.output.span().hi;
2002 if where_clause.predicates.is_empty() {
2003 let snippet_hi = span.hi;
2004 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2005 // Try to preserve the layout of the original snippet.
2006 let original_starts_with_newline = snippet
2008 .map_or(false, |i| snippet[i..].starts_with('\n'));
2009 let original_ends_with_newline = snippet
2010 .rfind(|c| c != ' ')
2011 .map_or(false, |i| snippet[i..].ends_with('\n'));
2012 let snippet = snippet.trim();
2013 if !snippet.is_empty() {
2014 result.push(if original_starts_with_newline {
2019 result.push_str(snippet);
2020 if original_ends_with_newline {
2021 force_new_line_for_brace = true;
2027 let should_compress_where = match context.config.where_density() {
2028 Density::Compressed => !result.contains('\n'),
2029 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2033 let pos_before_where = match fd.output {
2034 ast::FunctionRetTy::Default(..) => args_span.hi,
2035 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2038 if where_clause.predicates.len() == 1 && should_compress_where {
2039 let budget = context
2042 .checked_sub(last_line_used_width(&result, indent.width()))
2044 if let Some(where_clause_str) = rewrite_where_clause(
2047 context.config.fn_brace_style(),
2048 Shape::legacy(budget, indent),
2049 Density::Compressed,
2053 WhereClauseOption::compressed(),
2055 result.push_str(&where_clause_str);
2056 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2057 return Some((result, force_new_line_for_brace));
2061 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2062 let where_clause_str = try_opt!(rewrite_where_clause(
2065 context.config.fn_brace_style(),
2066 Shape::indented(indent, context.config),
2074 result.push_str(&where_clause_str);
2076 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2077 return Some((result, force_new_line_for_brace));
2080 struct WhereClauseOption {
2081 suppress_comma: bool, // Force no trailing comma
2082 snuggle: bool, // Do not insert newline before `where`
2083 compress_where: bool, // Try single line where clause instead of vertical layout
2086 impl WhereClauseOption {
2087 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2089 suppress_comma: suppress_comma,
2091 compress_where: false,
2095 pub fn compressed() -> WhereClauseOption {
2097 suppress_comma: true,
2099 compress_where: true,
2103 pub fn snuggled(current: &str) -> WhereClauseOption {
2105 suppress_comma: false,
2106 snuggle: trimmed_last_line_width(current) == 1,
2107 compress_where: false,
2112 fn last_line_contains_single_line_comment(s: &str) -> bool {
2113 s.lines().last().map_or(false, |l| l.contains("//"))
2117 context: &RewriteContext,
2119 explicit_self: Option<&ast::ExplicitSelf>,
2120 one_line_budget: usize,
2121 multi_line_budget: usize,
2126 generics_str_contains_newline: bool,
2127 ) -> Option<String> {
2128 let mut arg_item_strs = try_opt!(
2131 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2133 .collect::<Option<Vec<_>>>()
2136 // Account for sugary self.
2137 // FIXME: the comment for the self argument is dropped. This is blocked
2138 // on rust issue #27522.
2139 let min_args = explicit_self
2140 .and_then(|explicit_self| {
2141 rewrite_explicit_self(explicit_self, args, context)
2143 .map_or(1, |self_str| {
2144 arg_item_strs[0] = self_str;
2148 // Comments between args.
2149 let mut arg_items = Vec::new();
2151 arg_items.push(ListItem::from_str(""));
2154 // FIXME(#21): if there are no args, there might still be a comment, but
2155 // without spans for the comment or parens, there is no chance of
2156 // getting it right. You also don't get to put a comment on self, unless
2158 if args.len() >= min_args || variadic {
2159 let comment_span_start = if min_args == 2 {
2160 let second_arg_start = if arg_has_pattern(&args[1]) {
2165 let reduced_span = mk_sp(span.lo, second_arg_start);
2167 context.codemap.span_after_last(reduced_span, ",")
2172 enum ArgumentKind<'a> {
2173 Regular(&'a ast::Arg),
2177 let variadic_arg = if variadic {
2178 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2179 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2180 Some(ArgumentKind::Variadic(variadic_start))
2185 let more_items = itemize_list(
2187 args[min_args - 1..]
2189 .map(ArgumentKind::Regular)
2190 .chain(variadic_arg),
2193 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2194 ArgumentKind::Variadic(start) => start,
2197 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2198 ArgumentKind::Variadic(start) => start + BytePos(3),
2201 ArgumentKind::Regular(..) => None,
2202 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2208 arg_items.extend(more_items);
2211 let fits_in_one_line = !generics_str_contains_newline &&
2212 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2214 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2215 item.item = Some(arg);
2218 let last_line_ends_with_comment = arg_items
2221 .and_then(|item| item.post_comment.as_ref())
2222 .map_or(false, |s| s.trim().starts_with("//"));
2224 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2225 IndentStyle::Block if fits_in_one_line => {
2226 (indent.block_indent(context.config), SeparatorTactic::Never)
2228 IndentStyle::Block => (
2229 indent.block_indent(context.config),
2230 context.config.trailing_comma(),
2232 IndentStyle::Visual if last_line_ends_with_comment => {
2233 (arg_indent, context.config.trailing_comma())
2235 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2238 let tactic = definitive_tactic(
2240 context.config.fn_args_density().to_list_tactic(),
2244 let budget = match tactic {
2245 DefinitiveListTactic::Horizontal => one_line_budget,
2246 _ => multi_line_budget,
2249 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2251 let fmt = ListFormatting {
2254 trailing_separator: if variadic {
2255 SeparatorTactic::Never
2259 shape: Shape::legacy(budget, indent),
2260 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2261 preserve_newline: true,
2262 config: context.config,
2265 write_list(&arg_items, &fmt)
2268 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2269 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2270 ident.node != symbol::keywords::Invalid.ident()
2276 fn compute_budgets_for_args(
2277 context: &RewriteContext,
2281 newline_brace: bool,
2283 force_vertical_layout: bool,
2284 ) -> Option<((usize, usize, Indent))> {
2286 "compute_budgets_for_args {} {:?}, {}, {}",
2292 // Try keeping everything on the same line.
2293 if !result.contains('\n') && !force_vertical_layout {
2294 // 2 = `()`, 3 = `() `, space is before ret_string.
2295 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2296 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2306 let one_line_budget = context
2309 .checked_sub(used_space)
2312 if one_line_budget > 0 {
2314 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2315 IndentStyle::Block => {
2316 let indent = indent.block_indent(context.config);
2318 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2321 IndentStyle::Visual => {
2322 let indent = indent + result.len() + 1;
2323 let multi_line_overhead =
2324 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2326 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2331 return Some((one_line_budget, multi_line_budget, indent));
2335 // Didn't work. we must force vertical layout and put args on a newline.
2336 let new_indent = indent.block_indent(context.config);
2337 let used_space = match context.config.fn_args_layout() {
2339 IndentStyle::Block => new_indent.width() + 1,
2340 // Account for `)` and possibly ` {`.
2341 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2343 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2344 Some((0, max_space, new_indent))
2347 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2348 match (config.fn_brace_style(), config.where_density()) {
2349 (BraceStyle::AlwaysNextLine, _) => true,
2350 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2351 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2352 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2357 fn rewrite_generics(
2358 context: &RewriteContext,
2359 generics: &ast::Generics,
2362 ) -> Option<String> {
2363 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2364 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2365 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2366 rewrite_generics_inner(context, generics, g_shape, 0, span)
2370 fn rewrite_generics_inner(
2371 context: &RewriteContext,
2372 generics: &ast::Generics,
2374 one_line_width: usize,
2376 ) -> Option<String> {
2377 // FIXME: convert bounds to where clauses where they get too big or if
2378 // there is a where clause at all.
2379 let lifetimes: &[_] = &generics.lifetimes;
2380 let tys: &[_] = &generics.ty_params;
2381 if lifetimes.is_empty() && tys.is_empty() {
2382 return Some(String::new());
2385 // Strings for the generics.
2386 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2387 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2389 // Extract comments between generics.
2390 let lt_spans = lifetimes.iter().map(|l| {
2391 let hi = if l.bounds.is_empty() {
2394 l.bounds[l.bounds.len() - 1].span.hi
2396 mk_sp(l.lifetime.span.lo, hi)
2398 let ty_spans = tys.iter().map(|ty| ty.span());
2400 let items = itemize_list(
2402 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2406 // FIXME: don't clone
2407 |&(_, ref str)| str.clone(),
2408 context.codemap.span_after(span, "<"),
2411 format_generics_item_list(context, items, shape, one_line_width)
2414 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2415 match config.generics_indent() {
2416 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2417 IndentStyle::Block => {
2421 .block_indent(config.tab_spaces())
2422 .with_max_width(config)
2428 pub fn format_generics_item_list<I>(
2429 context: &RewriteContext,
2432 one_line_budget: usize,
2435 I: Iterator<Item = ListItem>,
2437 let item_vec = items.collect::<Vec<_>>();
2439 let tactic = definitive_tactic(
2441 ListTactic::HorizontalVertical,
2445 let fmt = ListFormatting {
2448 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2449 SeparatorTactic::Never
2451 context.config.trailing_comma()
2454 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2455 preserve_newline: true,
2456 config: context.config,
2459 let list_str = try_opt!(write_list(&item_vec, &fmt));
2461 Some(wrap_generics_with_angle_brackets(
2468 pub fn wrap_generics_with_angle_brackets(
2469 context: &RewriteContext,
2471 list_offset: Indent,
2473 if context.config.generics_indent() == IndentStyle::Block &&
2474 (list_str.contains('\n') || list_str.ends_with(','))
2478 list_offset.to_string(context.config),
2481 .block_unindent(context.config)
2482 .to_string(context.config)
2484 } else if context.config.spaces_within_angle_brackets() {
2485 format!("< {} >", list_str)
2487 format!("<{}>", list_str)
2491 fn rewrite_trait_bounds(
2492 context: &RewriteContext,
2493 type_param_bounds: &ast::TyParamBounds,
2495 ) -> Option<String> {
2496 let bounds: &[_] = type_param_bounds;
2498 if bounds.is_empty() {
2499 return Some(String::new());
2501 let bound_str = try_opt!(
2504 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2505 .collect::<Option<Vec<_>>>()
2507 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2510 fn rewrite_where_clause_rfc_style(
2511 context: &RewriteContext,
2512 where_clause: &ast::WhereClause,
2515 span_end: Option<BytePos>,
2516 span_end_before_where: BytePos,
2517 where_clause_option: WhereClauseOption,
2518 ) -> Option<String> {
2519 let block_shape = shape.block().with_max_width(context.config);
2521 let (span_before, span_after) =
2522 missing_span_before_after_where(span_end_before_where, where_clause);
2523 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2530 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2533 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2536 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2537 // each clause on one line, trailing comma (except if suppress_comma)
2538 let span_start = where_clause.predicates[0].span().lo;
2539 // If we don't have the start of the next span, then use the end of the
2540 // predicates, but that means we miss comments.
2541 let len = where_clause.predicates.len();
2542 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2543 let span_end = span_end.unwrap_or(end_of_preds);
2544 let items = itemize_list(
2546 where_clause.predicates.iter(),
2548 |pred| pred.span().lo,
2549 |pred| pred.span().hi,
2550 |pred| pred.rewrite(context, block_shape),
2554 let comma_tactic = if where_clause_option.suppress_comma {
2555 SeparatorTactic::Never
2557 context.config.trailing_comma()
2560 let fmt = ListFormatting {
2561 tactic: DefinitiveListTactic::Vertical,
2563 trailing_separator: comma_tactic,
2564 shape: clause_shape,
2565 ends_with_newline: true,
2566 preserve_newline: true,
2567 config: context.config,
2569 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2571 let newline_before_where = if comment_before.is_empty() || comment_before.ends_with('\n') {
2574 "\n".to_owned() + &shape.indent.to_string(context.config)
2576 let newline_after_where = if comment_after.is_empty() {
2579 "\n".to_owned() + &clause_shape.indent.to_string(context.config)
2582 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2583 comment_after.is_empty() && !preds_str.contains('\n') &&
2584 6 + preds_str.len() <= shape.width
2588 format!("\n{}", clause_shape.indent.to_string(context.config))
2591 "{}{}{}where{}{}{}{}",
2594 newline_before_where,
2595 newline_after_where,
2602 fn rewrite_where_clause(
2603 context: &RewriteContext,
2604 where_clause: &ast::WhereClause,
2605 brace_style: BraceStyle,
2609 span_end: Option<BytePos>,
2610 span_end_before_where: BytePos,
2611 where_clause_option: WhereClauseOption,
2612 ) -> Option<String> {
2613 if where_clause.predicates.is_empty() {
2614 return Some(String::new());
2617 if context.config.where_style() == Style::Rfc {
2618 return rewrite_where_clause_rfc_style(
2624 span_end_before_where,
2625 where_clause_option,
2629 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2631 let offset = match context.config.where_pred_indent() {
2632 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2633 // 6 = "where ".len()
2634 IndentStyle::Visual => shape.indent + extra_indent + 6,
2636 // FIXME: if where_pred_indent != Visual, then the budgets below might
2637 // be out by a char or two.
2639 let budget = context.config.max_width() - offset.width();
2640 let span_start = where_clause.predicates[0].span().lo;
2641 // If we don't have the start of the next span, then use the end of the
2642 // predicates, but that means we miss comments.
2643 let len = where_clause.predicates.len();
2644 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2645 let span_end = span_end.unwrap_or(end_of_preds);
2646 let items = itemize_list(
2648 where_clause.predicates.iter(),
2650 |pred| pred.span().lo,
2651 |pred| pred.span().hi,
2652 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2656 let item_vec = items.collect::<Vec<_>>();
2657 // FIXME: we don't need to collect here if the where_layout isn't
2658 // HorizontalVertical.
2659 let tactic = definitive_tactic(
2661 context.config.where_layout(),
2666 let mut comma_tactic = context.config.trailing_comma();
2667 // Kind of a hack because we don't usually have trailing commas in where clauses.
2668 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2669 comma_tactic = SeparatorTactic::Never;
2672 let fmt = ListFormatting {
2675 trailing_separator: comma_tactic,
2676 shape: Shape::legacy(budget, offset),
2677 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2678 preserve_newline: true,
2679 config: context.config,
2681 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2683 let end_length = if terminator == "{" {
2684 // If the brace is on the next line we don't need to count it otherwise it needs two
2687 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2688 BraceStyle::PreferSameLine => 2,
2690 } else if terminator == "=" {
2695 if density == Density::Tall || preds_str.contains('\n') ||
2696 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2700 (shape.indent + extra_indent).to_string(context.config),
2704 Some(format!(" where {}", preds_str))
2708 fn missing_span_before_after_where(
2709 before_item_span_end: BytePos,
2710 where_clause: &ast::WhereClause,
2712 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo);
2714 let pos_after_where = where_clause.span.lo + BytePos(5);
2715 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2716 (missing_span_before, missing_span_after)
2719 fn rewrite_missing_comment_in_where(
2720 context: &RewriteContext,
2723 ) -> Option<String> {
2724 let comment = comment.trim();
2725 if comment.is_empty() {
2728 rewrite_comment(comment, false, shape, context.config)
2732 fn rewrite_comments_before_after_where(
2733 context: &RewriteContext,
2734 span_before_where: Span,
2735 span_after_where: Span,
2737 ) -> Option<(String, String)> {
2738 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2740 &context.snippet(span_before_where),
2743 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2745 &context.snippet(span_after_where),
2746 shape.block_indent(context.config.tab_spaces()),
2748 Some((before_comment, after_comment))
2751 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2752 format!("{}{}{}", format_visibility(vis), item_name, ident)
2756 context: &RewriteContext,
2757 generics: &ast::Generics,
2760 brace_style: BraceStyle,
2761 force_same_line_brace: bool,
2765 ) -> Option<String> {
2766 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2767 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2769 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2770 let budget = context
2773 .checked_sub(last_line_used_width(&result, offset.width()))
2775 let option = WhereClauseOption::snuggled(&result);
2776 let where_clause_str = try_opt!(rewrite_where_clause(
2778 &generics.where_clause,
2780 Shape::legacy(budget, offset.block_only()),
2787 result.push_str(&where_clause_str);
2788 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2789 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2791 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2792 brace_style != BraceStyle::AlwaysNextLine
2794 let total_used_width = last_line_used_width(&result, used_width);
2795 let remaining_budget = context
2798 .checked_sub(total_used_width)
2800 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2801 // and hence we take the closer into account as well for one line budget.
2802 // We assume that the closer has the same length as the opener.
2803 let overhead = if force_same_line_brace {
2804 1 + opener.len() + opener.len()
2808 let forbid_same_line_brace = overhead > remaining_budget;
2809 if !forbid_same_line_brace && same_line_brace {
2813 result.push_str(&offset.block_only().to_string(context.config));
2815 result.push_str(opener);