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),
475 let shape = Shape::indented(self.block_indent, self.config)
478 let fmt = ListFormatting {
479 tactic: DefinitiveListTactic::Vertical,
481 trailing_separator: self.config.trailing_comma(),
483 ends_with_newline: true,
484 preserve_newline: true,
488 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
489 result.push_str(&list);
494 // Variant of an enum.
495 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
496 if contains_skip(&field.node.attrs) {
497 let lo = field.node.attrs[0].span.lo;
498 let span = mk_sp(lo, field.span.hi);
499 return Some(self.snippet(span));
502 let context = self.get_context();
503 let indent = self.block_indent;
504 let mut result = try_opt!(
508 .rewrite(&context, Shape::indented(indent, self.config))
510 if !result.is_empty() {
512 width: context.config.max_width(),
513 indent: self.block_indent,
514 offset: self.block_indent.alignment,
516 let missing_comment = rewrite_missing_comment_on_field(
519 field.node.attrs[field.node.attrs.len() - 1].span.hi,
522 ).unwrap_or(String::new());
523 result.push_str(&missing_comment);
526 let variant_body = match field.node.data {
527 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
528 // FIXME: Should limit the width, as we have a trailing comma
533 &ast::Visibility::Inherited,
538 Some(self.config.struct_variant_width()),
541 ast::VariantData::Unit(..) => {
542 let tag = if let Some(ref expr) = field.node.disr_expr {
543 format!("{} = {}", field.node.name, self.snippet(expr.span))
545 field.node.name.to_string()
550 self.config.max_width(),
551 Shape::indented(indent, self.config),
556 if let Some(variant_str) = variant_body {
557 result.push_str(&variant_str);
566 context: &RewriteContext,
569 where_span_end: Option<BytePos>,
570 ) -> Option<String> {
571 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
572 let mut result = String::new();
573 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
574 result.push_str(&ref_and_type);
576 let where_budget = if result.contains('\n') {
577 context.config.max_width()
582 .checked_sub(last_line_width(&result))
585 let option = WhereClauseOption::snuggled(&ref_and_type);
586 let where_clause_str = try_opt!(rewrite_where_clause(
588 &generics.where_clause,
589 context.config.item_brace_style(),
590 Shape::legacy(where_budget, offset.block_only()),
591 context.config.where_density(),
598 if try_opt!(is_impl_single_line(
605 result.push_str(&where_clause_str);
606 if where_clause_str.contains('\n') {
607 let white_space = offset.to_string(context.config);
608 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
610 result.push_str(" {}");
615 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
617 let width = offset.block_indent + context.config.tab_spaces() - 1;
618 let where_indent = Indent::new(0, width);
619 result.push_str(&where_indent.to_string(context.config));
621 result.push_str(&where_clause_str);
623 match context.config.item_brace_style() {
624 BraceStyle::AlwaysNextLine => {
626 result.push_str(&offset.to_string(context.config));
628 BraceStyle::PreferSameLine => result.push(' '),
629 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
631 result.push_str(&offset.to_string(context.config));
639 let snippet = context.snippet(item.span);
640 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
642 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
643 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
644 visitor.block_indent = offset.block_only().block_indent(context.config);
645 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
647 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
649 visitor.visit_impl_item(item);
652 visitor.format_missing(item.span.hi - BytePos(1));
654 let inner_indent_str = visitor.block_indent.to_string(context.config);
655 let outer_indent_str = offset.block_only().to_string(context.config);
658 result.push_str(&inner_indent_str);
659 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
661 result.push_str(&outer_indent_str);
664 if result.chars().last().unwrap() == '{' {
666 result.push_str(&offset.to_string(context.config));
676 fn is_impl_single_line(
677 context: &RewriteContext,
680 where_clause_str: &str,
683 let snippet = context.snippet(item.span);
684 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
687 context.config.impl_empty_single_line() && items.is_empty() &&
688 result.len() + where_clause_str.len() <= context.config.max_width() &&
689 !contains_comment(&snippet[open_pos..]),
693 fn format_impl_ref_and_type(
694 context: &RewriteContext,
697 ) -> Option<String> {
698 if let ast::ItemKind::Impl(
708 let mut result = String::new();
710 result.push_str(&format_visibility(&item.vis));
711 result.push_str(&format_defaultness(defaultness));
712 result.push_str(format_unsafety(unsafety));
713 result.push_str("impl");
715 let lo = context.codemap.span_after(item.span, "impl");
716 let hi = match *trait_ref {
717 Some(ref tr) => tr.path.span.lo,
718 None => self_ty.span.lo,
720 let shape = try_opt!(generics_shape_from_config(
722 Shape::indented(offset + last_line_width(&result), context.config),
725 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
726 let generics_str = try_opt!(rewrite_generics_inner(
734 let polarity_str = if polarity == ast::ImplPolarity::Negative {
740 if let Some(ref trait_ref) = *trait_ref {
741 let result_len = result.len();
742 if let Some(trait_ref_str) = rewrite_trait_ref(
751 result.push_str(&trait_ref_str);
753 let generics_str = try_opt!(rewrite_generics_inner(
760 result.push_str(&try_opt!(rewrite_trait_ref(
771 result.push_str(&generics_str);
774 // Try to put the self type in a single line.
776 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
777 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
778 // If there is no where clause adapt budget for type formatting to take space and curly
779 // brace into account.
780 match context.config.item_brace_style() {
781 BraceStyle::AlwaysNextLine => 0,
787 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
788 // 1 = space before the type.
792 .checked_sub(used_space + 1)
794 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
795 if !self_ty_str.contains('\n') {
796 if trait_ref.is_some() {
797 result.push_str(" for ");
801 result.push_str(&self_ty_str);
806 // Couldn't fit the self type on a single line, put it on a new line.
808 // Add indentation of one additional tab.
809 let new_line_offset = offset.block_indent(context.config);
810 result.push_str(&new_line_offset.to_string(context.config));
811 if trait_ref.is_some() {
812 result.push_str("for ");
814 let budget = context.config.max_width() - last_line_width(&result);
815 let type_offset = match context.config.where_style() {
816 Style::Legacy => new_line_offset + trait_ref_overhead,
817 Style::Rfc => new_line_offset,
819 result.push_str(&*try_opt!(
820 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
828 fn rewrite_trait_ref(
829 context: &RewriteContext,
830 trait_ref: &ast::TraitRef,
836 ) -> Option<String> {
837 // 1 = space between generics and trait_ref
838 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
839 let shape = Shape::indented(offset + used_space, context.config);
840 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
841 if !(retry && trait_ref_str.contains('\n')) {
850 // We could not make enough space for trait_ref, so put it on new line.
852 let offset = offset.block_indent(context.config);
853 let shape = Shape::indented(offset, context.config);
854 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
858 &offset.to_string(context.config),
867 pub fn format_struct(
868 context: &RewriteContext,
871 vis: &ast::Visibility,
872 struct_def: &ast::VariantData,
873 generics: Option<&ast::Generics>,
876 one_line_width: Option<usize>,
877 ) -> Option<String> {
879 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
880 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
890 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
904 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
905 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
908 let mut result = String::new();
909 let header = format!(
911 format_visibility(&item.vis),
912 format_unsafety(unsafety),
916 result.push_str(&header);
918 let body_lo = context.codemap.span_after(item.span, "{");
920 let shape = Shape::indented(offset + last_line_width(&result), context.config);
921 let generics_str = try_opt!(rewrite_generics(
925 mk_sp(item.span.lo, body_lo),
927 result.push_str(&generics_str);
929 let trait_bound_str = try_opt!(rewrite_trait_bounds(
932 Shape::indented(offset, context.config),
934 // If the trait, generics, and trait bound cannot fit on the same line,
935 // put the trait bounds on an indented new line
936 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
937 context.config.comment_width()
940 let trait_indent = offset.block_only().block_indent(context.config);
941 result.push_str(&trait_indent.to_string(context.config));
943 result.push_str(&trait_bound_str);
945 let has_body = !trait_items.is_empty();
947 let where_density = if (context.config.where_density() == Density::Compressed &&
948 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
949 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
950 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
951 !result.contains('\n'))
958 let where_budget = try_opt!(
962 .checked_sub(last_line_width(&result))
964 let pos_before_where = if type_param_bounds.is_empty() {
965 if generics.where_clause.predicates.is_empty() {
966 // We do not use this, so it does not matter
969 let snippet = context.snippet(item.span);
970 let where_pos = snippet.find_uncommented("where");
971 item.span.lo + where_pos.map_or(BytePos(0), |p| BytePos(p as u32))
974 type_param_bounds[type_param_bounds.len() - 1].span().hi
976 let option = WhereClauseOption::snuggled(&generics_str);
977 let where_clause_str = try_opt!(rewrite_where_clause(
979 &generics.where_clause,
980 context.config.item_brace_style(),
981 Shape::legacy(where_budget, offset.block_only()),
988 // If the where clause cannot fit on the same line,
989 // put the where clause on a new line
990 if !where_clause_str.contains('\n') &&
991 last_line_width(&result) + where_clause_str.len() + offset.width() >
992 context.config.comment_width()
995 let width = offset.block_indent + context.config.tab_spaces() - 1;
996 let where_indent = Indent::new(0, width);
997 result.push_str(&where_indent.to_string(context.config));
999 result.push_str(&where_clause_str);
1001 match context.config.item_brace_style() {
1002 BraceStyle::AlwaysNextLine => {
1004 result.push_str(&offset.to_string(context.config));
1006 BraceStyle::PreferSameLine => result.push(' '),
1007 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1008 (!trait_items.is_empty() || result.contains('\n'))
1011 result.push_str(&offset.to_string(context.config));
1018 let snippet = context.snippet(item.span);
1019 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1021 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1022 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1023 visitor.block_indent = offset.block_only().block_indent(context.config);
1024 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1026 for item in trait_items {
1027 visitor.visit_trait_item(item);
1030 visitor.format_missing(item.span.hi - BytePos(1));
1032 let inner_indent_str = visitor.block_indent.to_string(context.config);
1033 let outer_indent_str = offset.block_only().to_string(context.config);
1036 result.push_str(&inner_indent_str);
1037 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1039 result.push_str(&outer_indent_str);
1040 } else if result.contains('\n') {
1051 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1052 format!("{};", format_header(item_name, ident, vis))
1055 pub fn format_struct_struct(
1056 context: &RewriteContext,
1059 vis: &ast::Visibility,
1060 fields: &[ast::StructField],
1061 generics: Option<&ast::Generics>,
1064 one_line_width: Option<usize>,
1065 ) -> Option<String> {
1066 let mut result = String::with_capacity(1024);
1068 let header_str = format_header(item_name, ident, vis);
1069 result.push_str(&header_str);
1071 let body_lo = context.codemap.span_after(span, "{");
1073 let generics_str = match generics {
1074 Some(g) => try_opt!(format_generics(
1079 context.config.item_brace_style(),
1082 mk_sp(span.lo, body_lo),
1083 last_line_width(&result),
1086 // 3 = ` {}`, 2 = ` {`.
1087 let overhead = if fields.is_empty() { 3 } else { 2 };
1088 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1089 !fields.is_empty()) ||
1093 .checked_sub(result.len())
1094 .unwrap_or(0) < overhead
1096 format!("\n{}{{", offset.block_only().to_string(context.config))
1103 let overhead = if fields.is_empty() { 1 } else { 0 };
1104 let max_len = context
1107 .checked_sub(offset.width())
1109 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1111 result.push_str(&offset.to_string(context.config));
1112 result.push_str(&generics_str.trim_left());
1114 result.push_str(&generics_str);
1117 if fields.is_empty() {
1118 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1119 if snippet.trim().is_empty() {
1121 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1123 result.push_str(&snippet.trim_right());
1125 result.push_str(&offset.to_string(context.config));
1127 result.push_str(&snippet);
1130 return Some(result);
1134 let one_line_budget = context
1137 .checked_sub(result.len() + 3 + offset.width())
1139 let one_line_budget =
1140 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1142 let items_str = try_opt!(rewrite_with_alignment(
1145 Shape::indented(offset, context.config),
1146 mk_sp(body_lo, span.hi),
1150 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1151 Some(format!("{} {} }}", result, items_str))
1157 .block_indent(context.config)
1158 .to_string(context.config),
1160 offset.to_string(context.config)
1165 fn format_tuple_struct(
1166 context: &RewriteContext,
1169 vis: &ast::Visibility,
1170 fields: &[ast::StructField],
1171 generics: Option<&ast::Generics>,
1174 ) -> Option<String> {
1175 let mut result = String::with_capacity(1024);
1177 let header_str = format_header(item_name, ident, vis);
1178 result.push_str(&header_str);
1180 let body_lo = if fields.is_empty() {
1181 context.codemap.span_after(span, "(")
1185 let body_hi = if fields.is_empty() {
1186 context.codemap.span_after(span, ")")
1188 // This is a dirty hack to work around a missing `)` from the span of the last field.
1189 let last_arg_span = fields[fields.len() - 1].span;
1190 if context.snippet(last_arg_span).ends_with(")") {
1195 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1199 let where_clause_str = match generics {
1201 let budget = context.budget(last_line_width(&header_str));
1202 let shape = Shape::legacy(budget, offset);
1203 let g_span = mk_sp(span.lo, body_lo);
1204 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1205 result.push_str(&generics_str);
1207 let where_budget = context.budget(last_line_width(&result));
1208 let option = WhereClauseOption::new(true, false);
1209 try_opt!(rewrite_where_clause(
1211 &generics.where_clause,
1212 context.config.item_brace_style(),
1213 Shape::legacy(where_budget, offset.block_only()),
1214 Density::Compressed,
1221 None => "".to_owned(),
1224 if fields.is_empty() {
1226 let used_width = last_line_used_width(&result, offset.width()) + 3;
1227 if used_width > context.config.max_width() {
1229 result.push_str(&offset
1230 .block_indent(context.config)
1231 .to_string(context.config))
1234 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1235 if snippet.is_empty() {
1237 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1238 result.push_str(&snippet.trim_right());
1240 result.push_str(&offset.to_string(context.config));
1242 result.push_str(&snippet);
1247 let body = try_opt!(
1251 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1253 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1254 context.config.fn_call_width(),
1258 result.push_str(&body);
1261 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1262 (result.contains('\n') ||
1263 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1264 context.config.max_width())
1266 // We need to put the where clause on a new line, but we didn't
1267 // know that earlier, so the where clause will not be indented properly.
1269 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1270 .to_string(context.config));
1272 result.push_str(&where_clause_str);
1277 pub fn rewrite_type_alias(
1278 context: &RewriteContext,
1282 generics: &ast::Generics,
1283 vis: &ast::Visibility,
1285 ) -> Option<String> {
1286 let mut result = String::new();
1288 result.push_str(&format_visibility(vis));
1289 result.push_str("type ");
1290 result.push_str(&ident.to_string());
1293 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1294 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1295 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1296 result.push_str(&generics_str);
1298 let where_budget = try_opt!(
1302 .checked_sub(last_line_width(&result))
1304 let option = WhereClauseOption::snuggled(&result);
1305 let where_clause_str = try_opt!(rewrite_where_clause(
1307 &generics.where_clause,
1308 context.config.item_brace_style(),
1309 Shape::legacy(where_budget, indent),
1310 context.config.where_density(),
1316 result.push_str(&where_clause_str);
1317 if where_clause_str.is_empty() {
1318 result.push_str(" = ");
1320 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1323 let line_width = last_line_width(&result);
1324 // This checked_sub may fail as the extra space after '=' is not taken into account
1325 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1326 let budget = context
1329 .checked_sub(indent.width() + line_width + ";".len())
1331 let type_indent = indent + line_width;
1332 // Try to fit the type on the same line
1333 let ty_str = try_opt!(
1334 ty.rewrite(context, Shape::legacy(budget, type_indent))
1336 // The line was too short, try to put the type on the next line
1338 // Remove the space after '='
1340 let type_indent = indent.block_indent(context.config);
1342 result.push_str(&type_indent.to_string(context.config));
1343 let budget = try_opt!(
1347 .checked_sub(type_indent.width() + ";".len())
1349 ty.rewrite(context, Shape::legacy(budget, type_indent))
1352 result.push_str(&ty_str);
1353 result.push_str(";");
1357 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1359 if config.space_before_type_annotation() {
1364 if config.space_after_type_annotation_colon() {
1372 fn rewrite_missing_comment_on_field(
1373 context: &RewriteContext,
1377 result: &mut String,
1378 ) -> Option<String> {
1379 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1380 let newline_index = possibly_comment_snippet.find('\n');
1381 let comment_index = possibly_comment_snippet.find('/');
1382 match (newline_index, comment_index) {
1383 (Some(i), Some(j)) if i > j => result.push(' '),
1386 result.push_str(&shape.indent.to_string(context.config));
1389 let trimmed = possibly_comment_snippet.trim();
1390 if trimmed.is_empty() {
1393 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1394 format!("{}\n{}", s, shape.indent.to_string(context.config))
1399 pub fn rewrite_struct_field_prefix(
1400 context: &RewriteContext,
1401 field: &ast::StructField,
1403 ) -> Option<String> {
1404 let vis = format_visibility(&field.vis);
1405 let mut attr_str = try_opt!(
1408 .rewrite(context, Shape::indented(shape.indent, context.config))
1410 // Try format missing comments after attributes
1411 let missing_comment = if !field.attrs.is_empty() {
1412 rewrite_missing_comment_on_field(
1415 field.attrs[field.attrs.len() - 1].span.hi,
1418 ).unwrap_or(String::new())
1423 let type_annotation_spacing = type_annotation_spacing(context.config);
1424 Some(match field.ident {
1425 Some(name) => format!(
1431 type_annotation_spacing.0
1433 None => format!("{}{}{}", attr_str, missing_comment, vis),
1437 fn rewrite_struct_field_type(
1438 context: &RewriteContext,
1439 last_line_width: usize,
1440 field: &ast::StructField,
1443 ) -> Option<String> {
1444 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1447 .rewrite(context, ty_shape)
1448 .map(|ty| format!("{}{}", spacing, ty))
1451 impl Rewrite for ast::StructField {
1452 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1453 rewrite_struct_field(context, self, shape, 0)
1457 pub fn rewrite_struct_field(
1458 context: &RewriteContext,
1459 field: &ast::StructField,
1461 lhs_max_width: usize,
1462 ) -> Option<String> {
1463 if contains_skip(&field.attrs) {
1464 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1465 return wrap_str(span, context.config.max_width(), shape);
1468 let type_annotation_spacing = type_annotation_spacing(context.config);
1469 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1471 // Try to put everything on a single line.
1472 let last_line_width = last_line_width(&prefix);
1473 let mut spacing = String::from(if field.ident.is_some() {
1474 type_annotation_spacing.1
1478 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1479 for _ in 0..lhs_offset {
1482 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1483 if let Some(ref ty) = ty_rewritten {
1484 if !ty.contains('\n') {
1485 return Some(prefix + &ty);
1489 // We must use multiline.
1490 let type_offset = shape.indent.block_indent(context.config);
1491 let rewrite_type_in_next_line = || {
1494 .rewrite(context, Shape::indented(type_offset, context.config))
1497 match ty_rewritten {
1498 // If we start from the next line and type fits in a single line, then do so.
1499 Some(ref ty) => match rewrite_type_in_next_line() {
1500 Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
1503 type_offset.to_string(&context.config),
1506 _ => Some(prefix + &ty),
1509 let ty = try_opt!(rewrite_type_in_next_line());
1513 type_offset.to_string(&context.config),
1520 pub fn rewrite_static(
1522 vis: &ast::Visibility,
1525 mutability: ast::Mutability,
1526 expr_opt: Option<&ptr::P<ast::Expr>>,
1529 context: &RewriteContext,
1530 ) -> Option<String> {
1531 let colon = colon_spaces(
1532 context.config.space_before_type_annotation(),
1533 context.config.space_after_type_annotation_colon(),
1535 let prefix = format!(
1537 format_visibility(vis),
1539 format_mutability(mutability),
1544 let ty_str = try_opt!(ty.rewrite(
1547 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1551 if let Some(expr) = expr_opt {
1552 let lhs = format!("{}{} =", prefix, ty_str);
1554 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1559 Shape::legacy(remaining_width, offset.block_only()),
1561 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1563 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1565 Some(format!("{}{};", prefix, ty_str))
1569 pub fn rewrite_associated_type(
1571 ty_opt: Option<&ptr::P<ast::Ty>>,
1572 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1573 context: &RewriteContext,
1575 ) -> Option<String> {
1576 let prefix = format!("type {}", ident);
1578 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1579 let shape = Shape::indented(indent, context.config);
1580 let bounds: &[_] = ty_param_bounds;
1581 let bound_str = try_opt!(
1584 .map(|ty_bound| ty_bound.rewrite(context, shape))
1585 .collect::<Option<Vec<_>>>()
1587 if bounds.len() > 0 {
1588 format!(": {}", join_bounds(context, shape, &bound_str))
1596 if let Some(ty) = ty_opt {
1597 let ty_str = try_opt!(ty.rewrite(
1600 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1601 indent.block_only(),
1604 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1606 Some(format!("{}{};", prefix, type_bounds_str))
1610 pub fn rewrite_associated_impl_type(
1612 defaultness: ast::Defaultness,
1613 ty_opt: Option<&ptr::P<ast::Ty>>,
1614 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1615 context: &RewriteContext,
1617 ) -> Option<String> {
1618 let result = try_opt!(rewrite_associated_type(
1621 ty_param_bounds_opt,
1627 ast::Defaultness::Default => Some(format!("default {}", result)),
1632 impl Rewrite for ast::FunctionRetTy {
1633 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1635 ast::FunctionRetTy::Default(_) => Some(String::new()),
1636 ast::FunctionRetTy::Ty(ref ty) => {
1637 let inner_width = try_opt!(shape.width.checked_sub(3));
1638 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1639 .map(|r| format!("-> {}", r))
1645 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1647 ast::TyKind::Infer => {
1648 let original = context.snippet(ty.span);
1655 impl Rewrite for ast::Arg {
1656 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1657 if is_named_arg(self) {
1658 let mut result = try_opt!(
1660 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1663 if !is_empty_infer(context, &*self.ty) {
1664 if context.config.space_before_type_annotation() {
1665 result.push_str(" ");
1667 result.push_str(":");
1668 if context.config.space_after_type_annotation_colon() {
1669 result.push_str(" ");
1671 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1672 let ty_str = try_opt!(self.ty.rewrite(
1674 Shape::legacy(max_width, shape.indent + result.len()),
1676 result.push_str(&ty_str);
1681 self.ty.rewrite(context, shape)
1686 fn rewrite_explicit_self(
1687 explicit_self: &ast::ExplicitSelf,
1689 context: &RewriteContext,
1690 ) -> Option<String> {
1691 match explicit_self.node {
1692 ast::SelfKind::Region(lt, m) => {
1693 let mut_str = format_mutability(m);
1696 let lifetime_str = try_opt!(l.rewrite(
1698 Shape::legacy(context.config.max_width(), Indent::empty()),
1700 Some(format!("&{} {}self", lifetime_str, mut_str))
1702 None => Some(format!("&{}self", mut_str)),
1705 ast::SelfKind::Explicit(ref ty, _) => {
1706 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1708 let mutability = explicit_self_mutability(&args[0]);
1709 let type_str = try_opt!(ty.rewrite(
1711 Shape::legacy(context.config.max_width(), Indent::empty()),
1716 format_mutability(mutability),
1720 ast::SelfKind::Value(_) => {
1721 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1723 let mutability = explicit_self_mutability(&args[0]);
1725 Some(format!("{}self", format_mutability(mutability)))
1730 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1731 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1732 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1733 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1740 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1741 if is_named_arg(arg) {
1748 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1750 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1751 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1752 _ => arg.ty.span.hi,
1756 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1757 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1758 ident.node != symbol::keywords::Invalid.ident()
1764 // Return type is (result, force_new_line_for_brace)
1766 context: &RewriteContext,
1770 generics: &ast::Generics,
1771 unsafety: ast::Unsafety,
1772 constness: ast::Constness,
1773 defaultness: ast::Defaultness,
1775 vis: &ast::Visibility,
1777 newline_brace: bool,
1780 ) -> Option<(String, bool)> {
1781 let mut force_new_line_for_brace = false;
1783 let where_clause = &generics.where_clause;
1785 let mut result = String::with_capacity(1024);
1786 // Vis defaultness constness unsafety abi.
1787 result.push_str(&*format_visibility(vis));
1788 result.push_str(format_defaultness(defaultness));
1789 result.push_str(format_constness(constness));
1790 result.push_str(format_unsafety(unsafety));
1791 if abi != abi::Abi::Rust {
1792 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1796 result.push_str("fn ");
1797 result.push_str(&ident.to_string());
1800 let overhead = if has_braces && !newline_brace {
1807 let used_width = last_line_used_width(&result, indent.width());
1808 let one_line_budget = context
1811 .checked_sub(used_width + overhead)
1814 width: one_line_budget,
1818 let g_span = mk_sp(span.lo, fd.output.span().lo);
1819 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1820 result.push_str(&generics_str);
1822 let snuggle_angle_bracket = generics_str
1825 .map_or(false, |l| l.trim_left().len() == 1);
1827 // Note that the width and indent don't really matter, we'll re-layout the
1828 // return type later anyway.
1829 let ret_str = try_opt!(
1831 .rewrite(&context, Shape::indented(indent, context.config))
1834 let multi_line_ret_str = ret_str.contains('\n');
1835 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1838 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1849 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1855 // Check if vertical layout was forced.
1856 if one_line_budget == 0 {
1857 if snuggle_angle_bracket {
1860 if context.config.fn_args_paren_newline() {
1862 result.push_str(&arg_indent.to_string(context.config));
1863 if context.config.fn_args_layout() == IndentStyle::Visual {
1864 arg_indent = arg_indent + 1; // extra space for `(`
1868 result.push_str("(");
1869 if context.config.fn_args_layout() == IndentStyle::Visual {
1871 result.push_str(&arg_indent.to_string(context.config));
1878 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1882 // A conservative estimation, to goal is to be over all parens in generics
1883 let args_start = generics
1886 .map_or(span.lo, |tp| end_typaram(tp));
1887 let args_end = if fd.inputs.is_empty() {
1888 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1890 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1891 context.codemap.span_after(last_span, ")")
1893 let args_span = mk_sp(
1894 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1897 let arg_str = try_opt!(rewrite_args(
1900 fd.get_self().as_ref(),
1907 generics_str.contains('\n'),
1910 let put_args_in_block = match context.config.fn_args_layout() {
1911 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1913 } && !fd.inputs.is_empty();
1915 let mut args_last_line_contains_comment = false;
1916 if put_args_in_block {
1917 arg_indent = indent.block_indent(context.config);
1919 result.push_str(&arg_indent.to_string(context.config));
1920 result.push_str(&arg_str);
1922 result.push_str(&indent.to_string(context.config));
1925 result.push_str(&arg_str);
1926 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1927 // Put the closing brace on the next line if it overflows the max width.
1929 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1932 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1935 // If the last line of args contains comment, we cannot put the closing paren
1936 // on the same line.
1940 .map_or(false, |last_line| last_line.contains("//"))
1942 args_last_line_contains_comment = true;
1944 result.push_str(&arg_indent.to_string(context.config));
1950 if let ast::FunctionRetTy::Ty(..) = fd.output {
1951 let ret_should_indent = match context.config.fn_args_layout() {
1952 // If our args are block layout then we surely must have space.
1953 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1954 _ if args_last_line_contains_comment => false,
1955 _ if result.contains('\n') || multi_line_ret_str => true,
1957 // If the return type would push over the max width, then put the return type on
1958 // a new line. With the +1 for the signature length an additional space between
1959 // the closing parenthesis of the argument and the arrow '->' is considered.
1960 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1962 // If there is no where clause, take into account the space after the return type
1964 if where_clause.predicates.is_empty() {
1968 sig_length > context.config.max_width()
1971 let ret_indent = if ret_should_indent {
1972 let indent = match context.config.fn_return_indent() {
1973 ReturnIndent::WithWhereClause => indent + 4,
1974 // Aligning with non-existent args looks silly.
1975 _ if arg_str.is_empty() => {
1976 force_new_line_for_brace = true;
1979 // FIXME: we might want to check that using the arg indent
1980 // doesn't blow our budget, and if it does, then fallback to
1981 // the where clause indent.
1986 result.push_str(&indent.to_string(context.config));
1990 Indent::new(indent.block_indent, last_line_width(&result))
1993 if multi_line_ret_str || ret_should_indent {
1994 // Now that we know the proper indent and width, we need to
1995 // re-layout the return type.
1996 let ret_str = try_opt!(
1998 .rewrite(context, Shape::indented(ret_indent, context.config))
2000 result.push_str(&ret_str);
2002 result.push_str(&ret_str);
2005 // Comment between return type and the end of the decl.
2006 let snippet_lo = fd.output.span().hi;
2007 if where_clause.predicates.is_empty() {
2008 let snippet_hi = span.hi;
2009 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2010 // Try to preserve the layout of the original snippet.
2011 let original_starts_with_newline = snippet
2013 .map_or(false, |i| snippet[i..].starts_with('\n'));
2014 let original_ends_with_newline = snippet
2015 .rfind(|c| c != ' ')
2016 .map_or(false, |i| snippet[i..].ends_with('\n'));
2017 let snippet = snippet.trim();
2018 if !snippet.is_empty() {
2019 result.push(if original_starts_with_newline {
2024 result.push_str(snippet);
2025 if original_ends_with_newline {
2026 force_new_line_for_brace = true;
2032 let should_compress_where = match context.config.where_density() {
2033 Density::Compressed => !result.contains('\n'),
2034 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2038 let pos_before_where = match fd.output {
2039 ast::FunctionRetTy::Default(..) => args_span.hi,
2040 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2043 if where_clause.predicates.len() == 1 && should_compress_where {
2044 let budget = context
2047 .checked_sub(last_line_used_width(&result, indent.width()))
2049 if let Some(where_clause_str) = rewrite_where_clause(
2052 context.config.fn_brace_style(),
2053 Shape::legacy(budget, indent),
2054 Density::Compressed,
2058 WhereClauseOption::compressed(),
2060 result.push_str(&where_clause_str);
2061 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2062 return Some((result, force_new_line_for_brace));
2066 let option = WhereClauseOption::new(!has_braces, put_args_in_block && ret_str.is_empty());
2067 let where_clause_str = try_opt!(rewrite_where_clause(
2070 context.config.fn_brace_style(),
2071 Shape::indented(indent, context.config),
2078 // If there are neither where clause nor return type, we may be missing comments between
2080 if where_clause_str.is_empty() {
2081 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2082 let sp = mk_sp(args_span.hi, ret_span.hi);
2083 let missing_snippet = context.snippet(sp);
2084 let trimmed_snippet = missing_snippet.trim();
2085 let missing_comment = if trimmed_snippet.is_empty() {
2088 try_opt!(rewrite_comment(
2091 Shape::indented(indent, context.config),
2095 if !missing_comment.is_empty() {
2096 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
2098 let total_width = missing_comment.len() + last_line_width(&result) + 1;
2099 let force_new_line_before_comment = missing_snippet[..pos].contains('\n') ||
2100 total_width > context.config.max_width();
2101 let sep = if force_new_line_before_comment {
2102 format!("\n{}", indent.to_string(context.config))
2106 result.push_str(&sep);
2107 result.push_str(&missing_comment);
2108 force_new_line_for_brace = true;
2113 result.push_str(&where_clause_str);
2115 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2116 return Some((result, force_new_line_for_brace));
2119 struct WhereClauseOption {
2120 suppress_comma: bool, // Force no trailing comma
2121 snuggle: bool, // Do not insert newline before `where`
2122 compress_where: bool, // Try single line where clause instead of vertical layout
2125 impl WhereClauseOption {
2126 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2128 suppress_comma: suppress_comma,
2130 compress_where: false,
2134 pub fn compressed() -> WhereClauseOption {
2136 suppress_comma: true,
2138 compress_where: true,
2142 pub fn snuggled(current: &str) -> WhereClauseOption {
2144 suppress_comma: false,
2145 snuggle: trimmed_last_line_width(current) == 1,
2146 compress_where: false,
2151 fn last_line_contains_single_line_comment(s: &str) -> bool {
2152 s.lines().last().map_or(false, |l| l.contains("//"))
2156 context: &RewriteContext,
2158 explicit_self: Option<&ast::ExplicitSelf>,
2159 one_line_budget: usize,
2160 multi_line_budget: usize,
2165 generics_str_contains_newline: bool,
2166 ) -> Option<String> {
2167 let mut arg_item_strs = try_opt!(
2170 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2172 .collect::<Option<Vec<_>>>()
2175 // Account for sugary self.
2176 // FIXME: the comment for the self argument is dropped. This is blocked
2177 // on rust issue #27522.
2178 let min_args = explicit_self
2179 .and_then(|explicit_self| {
2180 rewrite_explicit_self(explicit_self, args, context)
2182 .map_or(1, |self_str| {
2183 arg_item_strs[0] = self_str;
2187 // Comments between args.
2188 let mut arg_items = Vec::new();
2190 arg_items.push(ListItem::from_str(""));
2193 // FIXME(#21): if there are no args, there might still be a comment, but
2194 // without spans for the comment or parens, there is no chance of
2195 // getting it right. You also don't get to put a comment on self, unless
2197 if args.len() >= min_args || variadic {
2198 let comment_span_start = if min_args == 2 {
2199 let second_arg_start = if arg_has_pattern(&args[1]) {
2204 let reduced_span = mk_sp(span.lo, second_arg_start);
2206 context.codemap.span_after_last(reduced_span, ",")
2211 enum ArgumentKind<'a> {
2212 Regular(&'a ast::Arg),
2216 let variadic_arg = if variadic {
2217 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2218 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2219 Some(ArgumentKind::Variadic(variadic_start))
2224 let more_items = itemize_list(
2226 args[min_args - 1..]
2228 .map(ArgumentKind::Regular)
2229 .chain(variadic_arg),
2232 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2233 ArgumentKind::Variadic(start) => start,
2236 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2237 ArgumentKind::Variadic(start) => start + BytePos(3),
2240 ArgumentKind::Regular(..) => None,
2241 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2248 arg_items.extend(more_items);
2251 let fits_in_one_line = !generics_str_contains_newline &&
2252 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2254 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2255 item.item = Some(arg);
2258 let last_line_ends_with_comment = arg_items
2261 .and_then(|item| item.post_comment.as_ref())
2262 .map_or(false, |s| s.trim().starts_with("//"));
2264 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2265 IndentStyle::Block if fits_in_one_line => {
2266 (indent.block_indent(context.config), SeparatorTactic::Never)
2268 IndentStyle::Block => (
2269 indent.block_indent(context.config),
2270 context.config.trailing_comma(),
2272 IndentStyle::Visual if last_line_ends_with_comment => {
2273 (arg_indent, context.config.trailing_comma())
2275 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2278 let tactic = definitive_tactic(
2280 context.config.fn_args_density().to_list_tactic(),
2284 let budget = match tactic {
2285 DefinitiveListTactic::Horizontal => one_line_budget,
2286 _ => multi_line_budget,
2289 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2291 let fmt = ListFormatting {
2294 trailing_separator: if variadic {
2295 SeparatorTactic::Never
2299 shape: Shape::legacy(budget, indent),
2300 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2301 preserve_newline: true,
2302 config: context.config,
2305 write_list(&arg_items, &fmt)
2308 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2309 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2310 ident.node != symbol::keywords::Invalid.ident()
2316 fn compute_budgets_for_args(
2317 context: &RewriteContext,
2321 newline_brace: bool,
2323 force_vertical_layout: bool,
2324 ) -> Option<((usize, usize, Indent))> {
2326 "compute_budgets_for_args {} {:?}, {}, {}",
2332 // Try keeping everything on the same line.
2333 if !result.contains('\n') && !force_vertical_layout {
2334 // 2 = `()`, 3 = `() `, space is before ret_string.
2335 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2336 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2346 let one_line_budget = context
2349 .checked_sub(used_space)
2352 if one_line_budget > 0 {
2354 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2355 IndentStyle::Block => {
2356 let indent = indent.block_indent(context.config);
2358 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2361 IndentStyle::Visual => {
2362 let indent = indent + result.len() + 1;
2363 let multi_line_overhead =
2364 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2366 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2371 return Some((one_line_budget, multi_line_budget, indent));
2375 // Didn't work. we must force vertical layout and put args on a newline.
2376 let new_indent = indent.block_indent(context.config);
2377 let used_space = match context.config.fn_args_layout() {
2379 IndentStyle::Block => new_indent.width() + 1,
2380 // Account for `)` and possibly ` {`.
2381 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2383 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2384 Some((0, max_space, new_indent))
2387 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2388 match (config.fn_brace_style(), config.where_density()) {
2389 (BraceStyle::AlwaysNextLine, _) => true,
2390 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2391 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2392 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2397 fn rewrite_generics(
2398 context: &RewriteContext,
2399 generics: &ast::Generics,
2402 ) -> Option<String> {
2403 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2404 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2405 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2406 rewrite_generics_inner(context, generics, g_shape, 0, span)
2410 fn rewrite_generics_inner(
2411 context: &RewriteContext,
2412 generics: &ast::Generics,
2414 one_line_width: usize,
2416 ) -> Option<String> {
2417 // FIXME: convert bounds to where clauses where they get too big or if
2418 // there is a where clause at all.
2419 let lifetimes: &[_] = &generics.lifetimes;
2420 let tys: &[_] = &generics.ty_params;
2421 if lifetimes.is_empty() && tys.is_empty() {
2422 return Some(String::new());
2425 // Strings for the generics.
2426 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2427 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2429 // Extract comments between generics.
2430 let lt_spans = lifetimes.iter().map(|l| {
2431 let hi = if l.bounds.is_empty() {
2434 l.bounds[l.bounds.len() - 1].span.hi
2436 mk_sp(l.lifetime.span.lo, hi)
2438 let ty_spans = tys.iter().map(|ty| ty.span());
2440 let items = itemize_list(
2442 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2446 // FIXME: don't clone
2447 |&(_, ref str)| str.clone(),
2448 context.codemap.span_after(span, "<"),
2452 format_generics_item_list(context, items, shape, one_line_width)
2455 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2456 match config.generics_indent() {
2457 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2458 IndentStyle::Block => {
2462 .block_indent(config.tab_spaces())
2463 .with_max_width(config)
2469 pub fn format_generics_item_list<I>(
2470 context: &RewriteContext,
2473 one_line_budget: usize,
2476 I: Iterator<Item = ListItem>,
2478 let item_vec = items.collect::<Vec<_>>();
2480 let tactic = definitive_tactic(
2482 ListTactic::HorizontalVertical,
2486 let fmt = ListFormatting {
2489 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2490 SeparatorTactic::Never
2492 context.config.trailing_comma()
2495 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2496 preserve_newline: true,
2497 config: context.config,
2500 let list_str = try_opt!(write_list(&item_vec, &fmt));
2502 Some(wrap_generics_with_angle_brackets(
2509 pub fn wrap_generics_with_angle_brackets(
2510 context: &RewriteContext,
2512 list_offset: Indent,
2514 if context.config.generics_indent() == IndentStyle::Block &&
2515 (list_str.contains('\n') || list_str.ends_with(','))
2519 list_offset.to_string(context.config),
2522 .block_unindent(context.config)
2523 .to_string(context.config)
2525 } else if context.config.spaces_within_angle_brackets() {
2526 format!("< {} >", list_str)
2528 format!("<{}>", list_str)
2532 fn rewrite_trait_bounds(
2533 context: &RewriteContext,
2534 type_param_bounds: &ast::TyParamBounds,
2536 ) -> Option<String> {
2537 let bounds: &[_] = type_param_bounds;
2539 if bounds.is_empty() {
2540 return Some(String::new());
2542 let bound_str = try_opt!(
2545 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2546 .collect::<Option<Vec<_>>>()
2548 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2551 fn rewrite_where_clause_rfc_style(
2552 context: &RewriteContext,
2553 where_clause: &ast::WhereClause,
2556 span_end: Option<BytePos>,
2557 span_end_before_where: BytePos,
2558 where_clause_option: WhereClauseOption,
2559 ) -> Option<String> {
2560 let block_shape = shape.block().with_max_width(context.config);
2562 let (span_before, span_after) =
2563 missing_span_before_after_where(span_end_before_where, where_clause);
2564 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2571 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2574 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2577 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2578 // each clause on one line, trailing comma (except if suppress_comma)
2579 let span_start = where_clause.predicates[0].span().lo;
2580 // If we don't have the start of the next span, then use the end of the
2581 // predicates, but that means we miss comments.
2582 let len = where_clause.predicates.len();
2583 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2584 let span_end = span_end.unwrap_or(end_of_preds);
2585 let items = itemize_list(
2587 where_clause.predicates.iter(),
2589 |pred| pred.span().lo,
2590 |pred| pred.span().hi,
2591 |pred| pred.rewrite(context, block_shape),
2596 let comma_tactic = if where_clause_option.suppress_comma {
2597 SeparatorTactic::Never
2599 context.config.trailing_comma()
2602 let fmt = ListFormatting {
2603 tactic: DefinitiveListTactic::Vertical,
2605 trailing_separator: comma_tactic,
2606 shape: clause_shape,
2607 ends_with_newline: true,
2608 preserve_newline: true,
2609 config: context.config,
2611 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2613 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2616 format!("\n{}", shape.indent.to_string(context.config))
2618 let newline_before_where = comment_separator(&comment_before, shape);
2619 let newline_after_where = comment_separator(&comment_after, clause_shape);
2622 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty() &&
2623 comment_after.is_empty() && !preds_str.contains('\n') &&
2624 6 + preds_str.len() <= shape.width
2628 format!("\n{}", clause_shape.indent.to_string(context.config))
2631 "{}{}{}where{}{}{}{}",
2634 newline_before_where,
2635 newline_after_where,
2642 fn rewrite_where_clause(
2643 context: &RewriteContext,
2644 where_clause: &ast::WhereClause,
2645 brace_style: BraceStyle,
2649 span_end: Option<BytePos>,
2650 span_end_before_where: BytePos,
2651 where_clause_option: WhereClauseOption,
2652 ) -> Option<String> {
2653 if where_clause.predicates.is_empty() {
2654 return Some(String::new());
2657 if context.config.where_style() == Style::Rfc {
2658 return rewrite_where_clause_rfc_style(
2664 span_end_before_where,
2665 where_clause_option,
2669 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2671 let offset = match context.config.where_pred_indent() {
2672 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2673 // 6 = "where ".len()
2674 IndentStyle::Visual => shape.indent + extra_indent + 6,
2676 // FIXME: if where_pred_indent != Visual, then the budgets below might
2677 // be out by a char or two.
2679 let budget = context.config.max_width() - offset.width();
2680 let span_start = where_clause.predicates[0].span().lo;
2681 // If we don't have the start of the next span, then use the end of the
2682 // predicates, but that means we miss comments.
2683 let len = where_clause.predicates.len();
2684 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2685 let span_end = span_end.unwrap_or(end_of_preds);
2686 let items = itemize_list(
2688 where_clause.predicates.iter(),
2690 |pred| pred.span().lo,
2691 |pred| pred.span().hi,
2692 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2697 let item_vec = items.collect::<Vec<_>>();
2698 // FIXME: we don't need to collect here if the where_layout isn't
2699 // HorizontalVertical.
2700 let tactic = definitive_tactic(
2702 context.config.where_layout(),
2707 let mut comma_tactic = context.config.trailing_comma();
2708 // Kind of a hack because we don't usually have trailing commas in where clauses.
2709 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2710 comma_tactic = SeparatorTactic::Never;
2713 let fmt = ListFormatting {
2716 trailing_separator: comma_tactic,
2717 shape: Shape::legacy(budget, offset),
2718 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2719 preserve_newline: true,
2720 config: context.config,
2722 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2724 let end_length = if terminator == "{" {
2725 // If the brace is on the next line we don't need to count it otherwise it needs two
2728 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2729 BraceStyle::PreferSameLine => 2,
2731 } else if terminator == "=" {
2736 if density == Density::Tall || preds_str.contains('\n') ||
2737 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2741 (shape.indent + extra_indent).to_string(context.config),
2745 Some(format!(" where {}", preds_str))
2749 fn missing_span_before_after_where(
2750 before_item_span_end: BytePos,
2751 where_clause: &ast::WhereClause,
2753 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo);
2755 let pos_after_where = where_clause.span.lo + BytePos(5);
2756 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2757 (missing_span_before, missing_span_after)
2760 fn rewrite_missing_comment_in_where(
2761 context: &RewriteContext,
2764 ) -> Option<String> {
2765 let comment = comment.trim();
2766 if comment.is_empty() {
2769 rewrite_comment(comment, false, shape, context.config)
2773 fn rewrite_comments_before_after_where(
2774 context: &RewriteContext,
2775 span_before_where: Span,
2776 span_after_where: Span,
2778 ) -> Option<(String, String)> {
2779 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2781 &context.snippet(span_before_where),
2784 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2786 &context.snippet(span_after_where),
2787 shape.block_indent(context.config.tab_spaces()),
2789 Some((before_comment, after_comment))
2792 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2793 format!("{}{}{}", format_visibility(vis), item_name, ident)
2797 context: &RewriteContext,
2798 generics: &ast::Generics,
2801 brace_style: BraceStyle,
2802 force_same_line_brace: bool,
2806 ) -> Option<String> {
2807 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2808 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2810 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2811 let budget = context
2814 .checked_sub(last_line_used_width(&result, offset.width()))
2816 let option = WhereClauseOption::snuggled(&result);
2817 let where_clause_str = try_opt!(rewrite_where_clause(
2819 &generics.where_clause,
2821 Shape::legacy(budget, offset.block_only()),
2828 result.push_str(&where_clause_str);
2829 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2830 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2832 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2833 brace_style != BraceStyle::AlwaysNextLine
2835 let total_used_width = last_line_used_width(&result, used_width);
2836 let remaining_budget = context
2839 .checked_sub(total_used_width)
2841 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2842 // and hence we take the closer into account as well for one line budget.
2843 // We assume that the closer has the same length as the opener.
2844 let overhead = if force_same_line_brace {
2845 1 + opener.len() + opener.len()
2849 let forbid_same_line_brace = overhead > remaining_budget;
2850 if !forbid_same_line_brace && same_line_brace {
2854 result.push_str(&offset.block_only().to_string(context.config));
2856 result.push_str(opener);