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.
14 use codemap::SpanUtils;
15 use utils::{format_mutability, format_visibility, contains_skip, end_typaram, wrap_str,
16 last_line_width, format_unsafety, trim_newlines, stmt_expr, semicolon_for_expr,
17 trimmed_last_line_width, colon_spaces, mk_sp};
18 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, list_helper,
19 DefinitiveListTactic, ListTactic, definitive_tactic};
20 use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
21 use comment::{FindUncommented, contains_comment, rewrite_comment, recover_comment_removed};
22 use visitor::FmtVisitor;
23 use rewrite::{Rewrite, RewriteContext};
24 use config::{Config, IndentStyle, Density, ReturnIndent, BraceStyle, Style};
25 use types::join_bounds;
27 use syntax::{ast, abi, ptr, symbol};
28 use syntax::codemap::{Span, BytePos};
29 use syntax::ast::ImplItem;
31 fn type_annotation_separator(config: &Config) -> &str {
33 config.space_before_type_annotation(),
34 config.space_after_type_annotation_colon(),
39 // Statements of the form
40 // let pat: ty = init;
41 impl Rewrite for ast::Local {
42 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
44 "Local::rewrite {:?} {} {:?}",
49 let mut result = "let ".to_owned();
52 let pat_shape = try_opt!(shape.offset_left(4));
54 let pat_shape = try_opt!(pat_shape.sub_width(1));
55 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
56 result.push_str(&pat_str);
58 // String that is placed within the assignment pattern and expression.
60 let mut infix = String::new();
62 if let Some(ref ty) = self.ty {
63 let separator = type_annotation_separator(context.config);
64 let indent = shape.indent + last_line_width(&result) + separator.len();
66 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
67 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
69 infix.push_str(separator);
70 infix.push_str(&rewrite);
73 if self.init.is_some() {
80 result.push_str(&infix);
82 if let Some(ref ex) = self.init {
83 // 1 = trailing semicolon;
84 let nested_shape = try_opt!(shape.sub_width(1));
86 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
94 // TODO convert to using rewrite style rather than visitor
95 // TODO format modules in this style
98 keyword: &'static str,
100 vis: Option<&'a ast::Visibility>,
101 body: Vec<BodyElement<'a>>,
106 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
107 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
110 format!("extern {}", fm.abi)
118 .map(|i| BodyElement::ForeignItem(i))
125 enum BodyElement<'a> {
126 // Stmt(&'a ast::Stmt),
127 // Field(&'a ast::Field),
128 // Variant(&'a ast::Variant),
129 // Item(&'a ast::Item),
130 ForeignItem(&'a ast::ForeignItem),
133 impl<'a> FmtVisitor<'a> {
134 fn format_item(&mut self, item: Item) {
135 self.buffer.push_str(&item.abi);
136 self.buffer.push_str(" ");
138 let snippet = self.snippet(item.span);
139 let brace_pos = snippet.find_uncommented("{").unwrap();
141 self.buffer.push_str("{");
142 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
143 // FIXME: this skips comments between the extern keyword and the opening
145 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
146 self.block_indent = self.block_indent.block_indent(self.config);
148 if item.body.is_empty() {
149 self.format_missing_no_indent(item.span.hi - BytePos(1));
150 self.block_indent = self.block_indent.block_unindent(self.config);
153 .push_str(&self.block_indent.to_string(self.config));
155 for item in &item.body {
156 self.format_body_element(item);
159 self.block_indent = self.block_indent.block_unindent(self.config);
160 self.format_missing_with_indent(item.span.hi - BytePos(1));
164 self.buffer.push_str("}");
165 self.last_pos = item.span.hi;
168 fn format_body_element(&mut self, element: &BodyElement) {
170 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
174 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
175 let item = Item::from_foreign_mod(fm, span, self.config);
176 self.format_item(item);
179 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
180 self.format_missing_with_indent(item.span.lo);
181 // Drop semicolon or it will be interpreted as comment.
182 // FIXME: this may be a faulty span from libsyntax.
183 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
186 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
187 let indent = self.block_indent;
188 let rewrite = rewrite_fn_base(
194 ast::Unsafety::Normal,
195 ast::Constness::NotConst,
196 ast::Defaultness::Final,
197 // These are not actually rust functions,
198 // but we format them as such.
208 Some((new_fn, _)) => {
209 self.buffer.push_str(&new_fn);
210 self.buffer.push_str(";");
212 None => self.format_missing(item.span.hi),
215 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
216 // FIXME(#21): we're dropping potential comments in between the
217 // function keywords here.
218 let vis = format_visibility(&item.vis);
219 let mut_str = if is_mutable { "mut " } else { "" };
220 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
221 let offset = self.block_indent + prefix.len();
223 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
224 let rewrite = ty.rewrite(&self.get_context(), shape);
228 self.buffer.push_str(&prefix);
229 self.buffer.push_str(&result);
230 self.buffer.push_str(";");
232 None => self.format_missing(item.span.hi),
237 self.last_pos = item.span.hi;
245 generics: &ast::Generics,
246 unsafety: ast::Unsafety,
247 constness: ast::Constness,
248 defaultness: ast::Defaultness,
250 vis: &ast::Visibility,
253 ) -> Option<String> {
254 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
255 let context = self.get_context();
257 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
258 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
259 !context.config.fn_empty_single_line();
261 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
278 if force_newline_brace {
279 newline_brace = true;
280 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
281 !result.contains('\n')
283 newline_brace = false;
286 // Prepare for the function body by possibly adding a newline and
288 // FIXME we'll miss anything between the end of the signature and the
289 // start of the body, but we need more spans from the compiler to solve
293 result.push_str(&indent.to_string(self.config));
298 self.single_line_fn(&result, block).or_else(|| Some(result))
301 pub fn rewrite_required_fn(
305 sig: &ast::MethodSig,
307 ) -> Option<String> {
308 // Drop semicolon or it will be interpreted as comment.
309 let span = mk_sp(span.lo, span.hi - BytePos(1));
310 let context = self.get_context();
312 let (mut result, _) = try_opt!(rewrite_fn_base(
320 ast::Defaultness::Final,
322 &ast::Visibility::Inherited,
329 // Re-attach semicolon
335 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
336 if fn_str.contains('\n') {
340 let codemap = self.get_context().codemap;
342 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
343 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
345 return Some(format!("{}{{}}", fn_str));
348 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
350 if let Some(ref stmt) = block.stmts.first() {
351 match stmt_expr(stmt) {
353 let suffix = if semicolon_for_expr(e) { ";" } else { "" };
357 Shape::indented(self.block_indent, self.config),
358 ).map(|s| s + suffix)
359 .or_else(|| Some(self.snippet(e.span)))
364 Shape::indented(self.block_indent, self.config),
373 if let Some(res) = rewrite {
374 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
375 if !res.contains('\n') && width <= self.config.max_width() {
376 return Some(format!("{}{{ {} }}", fn_str, res));
387 vis: &ast::Visibility,
388 enum_def: &ast::EnumDef,
389 generics: &ast::Generics,
392 self.buffer.push_str(&format_header("enum ", ident, vis));
394 let enum_snippet = self.snippet(span);
395 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
396 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
397 let generics_str = format_generics(
402 self.config.item_brace_style(),
403 enum_def.variants.is_empty(),
405 mk_sp(span.lo, body_start),
407 self.buffer.push_str(&generics_str);
409 self.last_pos = body_start;
411 self.block_indent = self.block_indent.block_indent(self.config);
412 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
414 Some(ref body_str) => self.buffer.push_str(body_str),
416 if contains_comment(&enum_snippet[brace_pos..]) {
417 self.format_missing_no_indent(span.hi - BytePos(1))
419 self.format_missing(span.hi - BytePos(1))
423 self.block_indent = self.block_indent.block_unindent(self.config);
425 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
427 .push_str(&self.block_indent.to_string(self.config));
429 self.buffer.push_str("}");
430 self.last_pos = span.hi;
433 // Format the body of an enum definition
434 fn format_variant_list(
436 enum_def: &ast::EnumDef,
439 ) -> Option<String> {
440 if enum_def.variants.is_empty() {
443 let mut result = String::with_capacity(1024);
445 let indentation = self.block_indent.to_string(self.config);
446 result.push_str(&indentation);
448 let items = itemize_list(
450 enum_def.variants.iter(),
452 |f| if !f.node.attrs.is_empty() {
453 f.node.attrs[0].span.lo
458 |f| self.format_variant(f),
463 let shape = Shape::indented(self.block_indent, self.config)
466 let fmt = ListFormatting {
467 tactic: DefinitiveListTactic::Vertical,
469 trailing_separator: self.config.trailing_comma(),
471 ends_with_newline: true,
475 let list = try_opt!(write_list(items, &fmt));
476 result.push_str(&list);
481 // Variant of an enum.
482 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
483 if contains_skip(&field.node.attrs) {
484 let lo = field.node.attrs[0].span.lo;
485 let span = mk_sp(lo, field.span.hi);
486 return Some(self.snippet(span));
489 let context = self.get_context();
490 let indent = self.block_indent;
491 let mut result = try_opt!(field.node.attrs.rewrite(
493 Shape::indented(indent, self.config),
495 if !result.is_empty() {
497 width: context.config.max_width(),
498 indent: self.block_indent,
499 offset: self.block_indent.alignment,
501 let missing_comment = rewrite_missing_comment_on_field(
504 field.node.attrs[field.node.attrs.len() - 1].span.hi,
507 ).unwrap_or(String::new());
508 result.push_str(&missing_comment);
511 let variant_body = match field.node.data {
512 ast::VariantData::Tuple(..) |
513 ast::VariantData::Struct(..) => {
514 // FIXME: Should limit the width, as we have a trailing comma
519 &ast::Visibility::Inherited,
524 Some(self.config.struct_variant_width()),
527 ast::VariantData::Unit(..) => {
528 let tag = if let Some(ref expr) = field.node.disr_expr {
529 format!("{} = {}", field.node.name, self.snippet(expr.span))
531 field.node.name.to_string()
536 self.config.max_width(),
537 Shape::indented(indent, self.config),
542 if let Some(variant_str) = variant_body {
543 result.push_str(&variant_str);
552 context: &RewriteContext,
555 where_span_end: Option<BytePos>,
556 ) -> Option<String> {
557 if let ast::ItemKind::Impl(_, _, _, ref generics, _, _, ref items) = item.node {
558 let mut result = String::new();
559 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
560 result.push_str(&ref_and_type);
562 let where_budget = if result.contains('\n') {
563 context.config.max_width()
568 .checked_sub(last_line_width(&result))
571 let where_clause_str = try_opt!(rewrite_where_clause(
573 &generics.where_clause,
574 context.config.item_brace_style(),
575 Shape::legacy(where_budget, offset.block_only()),
576 context.config.where_density(),
579 last_line_width(&ref_and_type) == 1,
583 if try_opt!(is_impl_single_line(
591 result.push_str(&where_clause_str);
592 if where_clause_str.contains('\n') {
593 let white_space = offset.to_string(context.config);
594 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
596 result.push_str(" {}");
601 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
603 let width = offset.block_indent + context.config.tab_spaces() - 1;
604 let where_indent = Indent::new(0, width);
605 result.push_str(&where_indent.to_string(context.config));
607 result.push_str(&where_clause_str);
609 match context.config.item_brace_style() {
610 BraceStyle::AlwaysNextLine => {
612 result.push_str(&offset.to_string(context.config));
614 BraceStyle::PreferSameLine => result.push(' '),
615 BraceStyle::SameLineWhere => {
616 if !where_clause_str.is_empty() {
618 result.push_str(&offset.to_string(context.config));
627 let snippet = context.snippet(item.span);
628 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
630 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
631 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
632 visitor.block_indent = offset.block_only().block_indent(context.config);
633 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
636 visitor.visit_impl_item(item);
639 visitor.format_missing(item.span.hi - BytePos(1));
641 let inner_indent_str = visitor.block_indent.to_string(context.config);
642 let outer_indent_str = offset.block_only().to_string(context.config);
645 result.push_str(&inner_indent_str);
646 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
648 result.push_str(&outer_indent_str);
651 if result.chars().last().unwrap() == '{' {
653 result.push_str(&offset.to_string(context.config));
663 fn is_impl_single_line(
664 context: &RewriteContext,
667 where_clause_str: &str,
670 let snippet = context.snippet(item.span);
671 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
674 context.config.impl_empty_single_line() && items.is_empty() &&
675 result.len() + where_clause_str.len() <= context.config.max_width() &&
676 !contains_comment(&snippet[open_pos..]),
680 fn format_impl_ref_and_type(
681 context: &RewriteContext,
684 ) -> Option<String> {
685 if let ast::ItemKind::Impl(
695 let mut result = String::new();
697 result.push_str(&format_visibility(&item.vis));
698 result.push_str(format_unsafety(unsafety));
699 result.push_str("impl");
701 let lo = context.codemap.span_after(item.span, "impl");
702 let hi = match *trait_ref {
703 Some(ref tr) => tr.path.span.lo,
704 None => self_ty.span.lo,
706 let shape = generics_shape_from_config(
708 Shape::indented(offset + last_line_width(&result), context.config),
711 let generics_str = try_opt!(rewrite_generics_inner(
719 let polarity_str = if polarity == ast::ImplPolarity::Negative {
725 if let Some(ref trait_ref) = *trait_ref {
726 let result_len = result.len();
727 if let Some(trait_ref_str) =
738 result.push_str(&trait_ref_str);
740 let generics_str = try_opt!(rewrite_generics_inner(
747 result.push_str(&try_opt!(rewrite_trait_ref(
758 result.push_str(&generics_str);
761 // Try to put the self type in a single line.
763 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
764 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
765 // If there is no where clause adapt budget for type formatting to take space and curly
766 // brace into account.
767 match context.config.item_brace_style() {
768 BraceStyle::AlwaysNextLine => 0,
774 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
775 // 1 = space before the type.
779 .checked_sub(used_space + 1)
781 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
782 if !self_ty_str.contains('\n') {
783 if trait_ref.is_some() {
784 result.push_str(" for ");
788 result.push_str(&self_ty_str);
793 // Couldn't fit the self type on a single line, put it on a new line.
795 // Add indentation of one additional tab.
796 let new_line_offset = offset.block_indent(context.config);
797 result.push_str(&new_line_offset.to_string(context.config));
798 if trait_ref.is_some() {
799 result.push_str("for ");
801 let budget = context.config.max_width() - last_line_width(&result);
802 let type_offset = match context.config.where_style() {
803 Style::Legacy => new_line_offset + trait_ref_overhead,
804 Style::Rfc => new_line_offset,
806 result.push_str(&*try_opt!(
807 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
815 fn rewrite_trait_ref(
816 context: &RewriteContext,
817 trait_ref: &ast::TraitRef,
823 ) -> Option<String> {
824 // 1 = space between generics and trait_ref
825 let used_space = 1 + polarity_str.len() +
826 if generics_str.contains('\n') {
827 last_line_width(&generics_str)
829 result_len + generics_str.len()
831 let shape = Shape::indented(offset + used_space, context.config);
832 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
833 if !(retry && trait_ref_str.contains('\n')) {
842 // We could not make enough space for trait_ref, so put it on new line.
844 let offset = offset.block_indent(context.config);
845 let shape = Shape::indented(offset, context.config);
846 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
850 &offset.to_string(context.config),
859 pub fn format_struct(
860 context: &RewriteContext,
863 vis: &ast::Visibility,
864 struct_def: &ast::VariantData,
865 generics: Option<&ast::Generics>,
868 one_line_width: Option<usize>,
869 ) -> Option<String> {
871 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
872 ast::VariantData::Tuple(ref fields, _) => {
884 ast::VariantData::Struct(ref fields, _) => {
885 format_struct_struct(
900 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
901 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
904 let mut result = String::new();
905 let header = format!(
907 format_visibility(&item.vis),
908 format_unsafety(unsafety),
912 result.push_str(&header);
914 let body_lo = context.codemap.span_after(item.span, "{");
916 let shape = Shape::indented(offset + last_line_width(&result), context.config);
917 let generics_str = try_opt!(rewrite_generics(
921 mk_sp(item.span.lo, body_lo),
923 result.push_str(&generics_str);
925 let trait_bound_str = try_opt!(rewrite_trait_bounds(
928 Shape::legacy(context.config.max_width(), offset),
930 // If the trait, generics, and trait bound cannot fit on the same line,
931 // put the trait bounds on an indented new line
932 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
933 context.config.comment_width()
936 let trait_indent = offset.block_only().block_indent(context.config);
937 result.push_str(&trait_indent.to_string(context.config));
939 result.push_str(&trait_bound_str);
941 let has_body = !trait_items.is_empty();
943 let where_density = if (context.config.where_density() == Density::Compressed &&
944 (!result.contains('\n') ||
945 context.config.fn_args_layout() == IndentStyle::Block)) ||
946 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
947 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
948 !result.contains('\n'))
955 let where_budget = try_opt!(
959 .checked_sub(last_line_width(&result))
961 let where_clause_str = try_opt!(rewrite_where_clause(
963 &generics.where_clause,
964 context.config.item_brace_style(),
965 Shape::legacy(where_budget, offset.block_only()),
969 trait_bound_str.is_empty() && last_line_width(&generics_str) == 1,
972 // If the where clause cannot fit on the same line,
973 // put the where clause on a new line
974 if !where_clause_str.contains('\n') &&
975 last_line_width(&result) + where_clause_str.len() + offset.width() >
976 context.config.comment_width()
979 let width = offset.block_indent + context.config.tab_spaces() - 1;
980 let where_indent = Indent::new(0, width);
981 result.push_str(&where_indent.to_string(context.config));
983 result.push_str(&where_clause_str);
985 match context.config.item_brace_style() {
986 BraceStyle::AlwaysNextLine => {
988 result.push_str(&offset.to_string(context.config));
990 BraceStyle::PreferSameLine => result.push(' '),
991 BraceStyle::SameLineWhere => {
992 if !where_clause_str.is_empty() &&
993 (!trait_items.is_empty() || result.contains('\n'))
996 result.push_str(&offset.to_string(context.config));
1004 let snippet = context.snippet(item.span);
1005 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1007 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1008 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1009 visitor.block_indent = offset.block_only().block_indent(context.config);
1010 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1012 for item in trait_items {
1013 visitor.visit_trait_item(item);
1016 visitor.format_missing(item.span.hi - BytePos(1));
1018 let inner_indent_str = visitor.block_indent.to_string(context.config);
1019 let outer_indent_str = offset.block_only().to_string(context.config);
1022 result.push_str(&inner_indent_str);
1023 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1025 result.push_str(&outer_indent_str);
1026 } else if result.contains('\n') {
1037 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1038 format!("{};", format_header(item_name, ident, vis))
1041 fn format_struct_struct(
1042 context: &RewriteContext,
1045 vis: &ast::Visibility,
1046 fields: &[ast::StructField],
1047 generics: Option<&ast::Generics>,
1050 one_line_width: Option<usize>,
1051 ) -> Option<String> {
1052 let mut result = String::with_capacity(1024);
1054 let header_str = format_header(item_name, ident, vis);
1055 result.push_str(&header_str);
1057 let body_lo = context.codemap.span_after(span, "{");
1059 let generics_str = match generics {
1061 try_opt!(format_generics(
1066 context.config.item_brace_style(),
1069 mk_sp(span.lo, body_lo),
1073 if context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1076 format!("\n{}{{", offset.block_only().to_string(context.config))
1082 result.push_str(&generics_str);
1084 if fields.is_empty() {
1085 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1086 if snippet.trim().is_empty() {
1088 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1090 result.push_str(&snippet.trim_right());
1092 result.push_str(&offset.to_string(context.config));
1094 result.push_str(&snippet);
1097 return Some(result);
1100 let item_indent = offset.block_indent(context.config);
1102 let item_budget = try_opt!(
1106 .checked_sub(item_indent.width() + 1)
1109 let items = itemize_list(
1114 // Include attributes and doc comments, if present
1115 if !field.attrs.is_empty() {
1116 field.attrs[0].span.lo
1121 |field| field.ty.span.hi,
1122 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1123 context.codemap.span_after(span, "{"),
1125 ).collect::<Vec<_>>();
1127 let budget = context.config.max_width() - offset.width() + context.config.tab_spaces() - 1;
1129 let tactic = match one_line_width {
1130 Some(w) => definitive_tactic(&items, ListTactic::LimitedHorizontalVertical(w), budget),
1131 None => DefinitiveListTactic::Vertical,
1134 let fmt = ListFormatting {
1137 trailing_separator: context.config.trailing_comma(),
1138 shape: Shape::legacy(budget, item_indent),
1139 ends_with_newline: true,
1140 config: context.config,
1142 let items_str = try_opt!(write_list(&items, &fmt));
1143 if one_line_width.is_some() && !items_str.contains('\n') {
1144 Some(format!("{} {} }}", result, items_str))
1150 .block_indent(context.config)
1151 .to_string(context.config),
1153 offset.to_string(context.config)
1158 fn format_tuple_struct(
1159 context: &RewriteContext,
1162 vis: &ast::Visibility,
1163 fields: &[ast::StructField],
1164 generics: Option<&ast::Generics>,
1167 ) -> Option<String> {
1168 let mut result = String::with_capacity(1024);
1170 let header_str = format_header(item_name, ident, vis);
1171 result.push_str(&header_str);
1173 let body_lo = if fields.is_empty() {
1174 context.codemap.span_after(span, "(")
1179 let where_clause_str = match generics {
1181 let shape = Shape::indented(offset + last_line_width(&header_str), context.config);
1182 let g_span = mk_sp(span.lo, body_lo);
1183 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1184 result.push_str(&generics_str);
1186 let where_budget = try_opt!(
1190 .checked_sub(last_line_width(&result))
1192 try_opt!(rewrite_where_clause(
1194 &generics.where_clause,
1195 context.config.item_brace_style(),
1196 Shape::legacy(where_budget, offset.block_only()),
1197 Density::Compressed,
1204 None => "".to_owned(),
1207 if fields.is_empty() {
1209 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1210 if snippet.is_empty() {
1212 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1213 result.push_str(&snippet.trim_right());
1215 result.push_str(&offset.to_string(context.config));
1217 result.push_str(&snippet);
1221 let (tactic, item_indent) = match context.config.fn_args_layout() {
1222 IndentStyle::Visual => {
1225 ListTactic::HorizontalVertical,
1226 offset.block_only() + result.len() + 1,
1229 IndentStyle::Block => {
1231 ListTactic::HorizontalVertical,
1232 offset.block_only().block_indent(&context.config),
1237 let item_budget = try_opt!(
1241 .checked_sub(item_indent.width() + 3)
1244 let items = itemize_list(
1249 // Include attributes and doc comments, if present
1250 if !field.attrs.is_empty() {
1251 field.attrs[0].span.lo
1256 |field| field.ty.span.hi,
1257 |field| field.rewrite(context, Shape::legacy(item_budget, item_indent)),
1258 context.codemap.span_after(span, "("),
1261 let body_budget = try_opt!(
1265 .checked_sub(offset.block_only().width() + result.len() + 3)
1267 let body = try_opt!(list_helper(
1269 // TODO budget is wrong in block case
1270 Shape::legacy(body_budget, item_indent),
1275 if context.config.fn_args_layout() == IndentStyle::Visual || !body.contains('\n') {
1277 if context.config.spaces_within_parens() && body.len() > 0 {
1281 result.push_str(&body);
1283 if context.config.spaces_within_parens() && body.len() > 0 {
1288 result.push_str("(\n");
1289 result.push_str(&item_indent.to_string(&context.config));
1290 result.push_str(&body);
1292 result.push_str(&offset.block_only().to_string(&context.config));
1297 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1298 (result.contains('\n') ||
1299 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1300 context.config.max_width())
1302 // We need to put the where clause on a new line, but we didn't
1303 // know that earlier, so the where clause will not be indented properly.
1305 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1306 .to_string(context.config));
1308 result.push_str(&where_clause_str);
1313 pub fn rewrite_type_alias(
1314 context: &RewriteContext,
1318 generics: &ast::Generics,
1319 vis: &ast::Visibility,
1321 ) -> Option<String> {
1322 let mut result = String::new();
1324 result.push_str(&format_visibility(vis));
1325 result.push_str("type ");
1326 result.push_str(&ident.to_string());
1329 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1330 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1331 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1332 result.push_str(&generics_str);
1334 let where_budget = try_opt!(
1338 .checked_sub(last_line_width(&result))
1340 let where_clause_str = try_opt!(rewrite_where_clause(
1342 &generics.where_clause,
1343 context.config.item_brace_style(),
1344 Shape::legacy(where_budget, indent),
1345 context.config.where_density(),
1351 result.push_str(&where_clause_str);
1352 result.push_str(" = ");
1354 let line_width = last_line_width(&result);
1355 // This checked_sub may fail as the extra space after '=' is not taken into account
1356 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1357 let budget = context
1360 .checked_sub(indent.width() + line_width + ";".len())
1362 let type_indent = indent + line_width;
1363 // Try to fit the type on the same line
1364 let ty_str = try_opt!(
1365 ty.rewrite(context, Shape::legacy(budget, type_indent))
1367 // The line was too short, try to put the type on the next line
1369 // Remove the space after '='
1371 let type_indent = indent.block_indent(context.config);
1373 result.push_str(&type_indent.to_string(context.config));
1374 let budget = try_opt!(
1378 .checked_sub(type_indent.width() + ";".len())
1380 ty.rewrite(context, Shape::legacy(budget, type_indent))
1383 result.push_str(&ty_str);
1384 result.push_str(";");
1388 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1390 if config.space_before_type_annotation() {
1395 if config.space_after_type_annotation_colon() {
1403 fn rewrite_missing_comment_on_field(
1404 context: &RewriteContext,
1408 result: &mut String,
1409 ) -> Option<String> {
1410 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1411 let newline_index = possibly_comment_snippet.find('\n');
1412 let comment_index = possibly_comment_snippet.find('/');
1413 match (newline_index, comment_index) {
1414 (Some(i), Some(j)) if i > j => result.push(' '),
1417 result.push_str(&shape.indent.to_string(context.config));
1420 let trimmed = possibly_comment_snippet.trim();
1421 if trimmed.is_empty() {
1424 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1425 format!("{}\n{}", s, shape.indent.to_string(context.config))
1430 impl Rewrite for ast::StructField {
1431 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1432 if contains_skip(&self.attrs) {
1433 let span = context.snippet(mk_sp(self.attrs[0].span.lo, self.span.hi));
1434 return wrap_str(span, context.config.max_width(), shape);
1437 let name = self.ident;
1438 let vis = format_visibility(&self.vis);
1439 let mut attr_str = try_opt!(self.attrs.rewrite(
1441 Shape::indented(shape.indent, context.config),
1443 // Try format missing comments after attributes
1444 let missing_comment = if !self.attrs.is_empty() {
1445 rewrite_missing_comment_on_field(
1448 self.attrs[self.attrs.len() - 1].span.hi,
1451 ).unwrap_or(String::new())
1456 let type_annotation_spacing = type_annotation_spacing(context.config);
1457 let mut result = match name {
1465 type_annotation_spacing.0
1468 None => format!("{}{}{}", attr_str, missing_comment, vis),
1471 let type_offset = shape.indent.block_indent(context.config);
1472 let rewrite_type_in_next_line = || {
1475 Shape::indented(type_offset, context.config),
1479 let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len();
1480 let budget = try_opt!(shape.width.checked_sub(last_line_width));
1481 let ty_rewritten = self.ty.rewrite(
1483 Shape::legacy(budget, shape.indent + last_line_width),
1485 match ty_rewritten {
1486 Some(ref ty) if ty.contains('\n') => {
1487 let new_ty = rewrite_type_in_next_line();
1490 if !new_ty.contains('\n') &&
1491 new_ty.len() + type_offset.width() <= context.config.max_width() => {
1495 type_offset.to_string(&context.config),
1501 result.push_str(type_annotation_spacing.1);
1509 result.push_str(type_annotation_spacing.1);
1514 let ty = try_opt!(rewrite_type_in_next_line());
1518 type_offset.to_string(&context.config),
1526 pub fn rewrite_static(
1528 vis: &ast::Visibility,
1531 mutability: ast::Mutability,
1532 expr_opt: Option<&ptr::P<ast::Expr>>,
1535 context: &RewriteContext,
1536 ) -> Option<String> {
1537 let type_annotation_spacing = type_annotation_spacing(context.config);
1538 let prefix = format!(
1540 format_visibility(vis),
1542 format_mutability(mutability),
1544 type_annotation_spacing.0,
1545 type_annotation_spacing.1
1548 let ty_str = try_opt!(ty.rewrite(
1551 context.config.max_width() - offset.block_indent - prefix.len() - 2,
1552 offset.block_only(),
1556 if let Some(expr) = expr_opt {
1557 let lhs = format!("{}{} =", prefix, ty_str);
1559 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1564 Shape::legacy(remaining_width, offset.block_only()),
1566 recover_comment_removed(
1571 width: context.config.max_width(),
1573 offset: offset.alignment,
1577 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1579 let lhs = format!("{}{};", prefix, ty_str);
1584 pub fn rewrite_associated_type(
1586 ty_opt: Option<&ptr::P<ast::Ty>>,
1587 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1588 context: &RewriteContext,
1590 ) -> Option<String> {
1591 let prefix = format!("type {}", ident);
1593 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1594 let shape = Shape::legacy(context.config.max_width(), indent);
1595 let bounds: &[_] = ty_param_bounds;
1596 let bound_str = try_opt!(
1599 .map(|ty_bound| ty_bound.rewrite(context, shape))
1600 .collect::<Option<Vec<_>>>()
1602 if bounds.len() > 0 {
1603 format!(": {}", join_bounds(context, shape, &bound_str))
1611 if let Some(ty) = ty_opt {
1612 let ty_str = try_opt!(ty.rewrite(
1615 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1616 indent.block_only(),
1619 Some(format!("{} = {};", prefix, ty_str))
1621 Some(format!("{}{};", prefix, type_bounds_str))
1625 pub fn rewrite_associated_impl_type(
1627 defaultness: ast::Defaultness,
1628 ty_opt: Option<&ptr::P<ast::Ty>>,
1629 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1630 context: &RewriteContext,
1632 ) -> Option<String> {
1633 let result = try_opt!(rewrite_associated_type(
1636 ty_param_bounds_opt,
1642 ast::Defaultness::Default => Some(format!("default {}", result)),
1647 impl Rewrite for ast::FunctionRetTy {
1648 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1650 ast::FunctionRetTy::Default(_) => Some(String::new()),
1651 ast::FunctionRetTy::Ty(ref ty) => {
1652 let inner_width = try_opt!(shape.width.checked_sub(3));
1653 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1654 .map(|r| format!("-> {}", r))
1660 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1662 ast::TyKind::Infer => {
1663 let original = context.snippet(ty.span);
1670 impl Rewrite for ast::Arg {
1671 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1672 if is_named_arg(self) {
1673 let mut result = try_opt!(self.pat.rewrite(
1675 Shape::legacy(shape.width, shape.indent),
1678 if !is_empty_infer(context, &*self.ty) {
1679 if context.config.space_before_type_annotation() {
1680 result.push_str(" ");
1682 result.push_str(":");
1683 if context.config.space_after_type_annotation_colon() {
1684 result.push_str(" ");
1686 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1687 let ty_str = try_opt!(self.ty.rewrite(
1689 Shape::legacy(max_width, shape.indent + result.len()),
1691 result.push_str(&ty_str);
1696 self.ty.rewrite(context, shape)
1701 fn rewrite_explicit_self(
1702 explicit_self: &ast::ExplicitSelf,
1704 context: &RewriteContext,
1705 ) -> Option<String> {
1706 match explicit_self.node {
1707 ast::SelfKind::Region(lt, m) => {
1708 let mut_str = format_mutability(m);
1711 let lifetime_str = try_opt!(l.rewrite(
1713 Shape::legacy(context.config.max_width(), Indent::empty()),
1715 Some(format!("&{} {}self", lifetime_str, mut_str))
1717 None => Some(format!("&{}self", mut_str)),
1720 ast::SelfKind::Explicit(ref ty, _) => {
1721 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1723 let mutability = explicit_self_mutability(&args[0]);
1724 let type_str = try_opt!(ty.rewrite(
1726 Shape::legacy(context.config.max_width(), Indent::empty()),
1731 format_mutability(mutability),
1735 ast::SelfKind::Value(_) => {
1736 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1738 let mutability = explicit_self_mutability(&args[0]);
1740 Some(format!("{}self", format_mutability(mutability)))
1745 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1746 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1747 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1748 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1755 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1756 if is_named_arg(arg) {
1763 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1765 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1766 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1767 _ => arg.ty.span.hi,
1771 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1772 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1773 ident.node != symbol::keywords::Invalid.ident()
1779 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1781 ast::FunctionRetTy::Default(ref span) => span.clone(),
1782 ast::FunctionRetTy::Ty(ref ty) => ty.span,
1786 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1787 // Note that ty.span is the span for ty.ident, not the whole item.
1788 let lo = if ty.attrs.is_empty() {
1793 if let Some(ref def) = ty.default {
1794 return mk_sp(lo, def.span.hi);
1796 if ty.bounds.is_empty() {
1797 return mk_sp(lo, ty.span.hi);
1799 let hi = match ty.bounds[ty.bounds.len() - 1] {
1800 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1801 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1806 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1808 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1809 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1810 ast::WherePredicate::EqPredicate(ref p) => p.span,
1814 // Return type is (result, force_new_line_for_brace)
1816 context: &RewriteContext,
1820 generics: &ast::Generics,
1821 unsafety: ast::Unsafety,
1822 constness: ast::Constness,
1823 defaultness: ast::Defaultness,
1825 vis: &ast::Visibility,
1827 newline_brace: bool,
1830 ) -> Option<(String, bool)> {
1831 let mut force_new_line_for_brace = false;
1833 let where_clause = &generics.where_clause;
1835 let mut result = String::with_capacity(1024);
1836 // Vis unsafety abi.
1837 result.push_str(&*format_visibility(vis));
1839 if let ast::Defaultness::Default = defaultness {
1840 result.push_str("default ");
1843 if let ast::Constness::Const = constness {
1844 result.push_str("const ");
1847 result.push_str(::utils::format_unsafety(unsafety));
1849 if abi != abi::Abi::Rust {
1850 result.push_str(&::utils::format_abi(
1852 context.config.force_explicit_abi(),
1857 result.push_str("fn ");
1858 result.push_str(&ident.to_string());
1861 let overhead = if has_braces && !newline_brace {
1868 let shape = try_opt!(
1869 Shape::indented(indent + last_line_width(&result), context.config).sub_width(overhead)
1871 let g_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
1872 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1873 result.push_str(&generics_str);
1875 let snuggle_angle_bracket = generics_str.lines().last().map_or(
1877 |l| l.trim_left().len() == 1,
1880 // Note that the width and indent don't really matter, we'll re-layout the
1881 // return type later anyway.
1882 let ret_str = try_opt!(fd.output.rewrite(
1884 Shape::indented(indent, context.config),
1887 let multi_line_ret_str = ret_str.contains('\n');
1888 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1891 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1892 try_opt!(compute_budgets_for_args(
1901 if context.config.fn_args_layout() == IndentStyle::Block {
1902 arg_indent = indent.block_indent(context.config);
1903 multi_line_budget = context.config.max_width() - arg_indent.width();
1907 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1913 // Check if vertical layout was forced.
1914 if one_line_budget == 0 {
1915 if snuggle_angle_bracket {
1918 if context.config.fn_args_paren_newline() {
1920 result.push_str(&arg_indent.to_string(context.config));
1921 if context.config.fn_args_layout() == IndentStyle::Visual {
1922 arg_indent = arg_indent + 1; // extra space for `(`
1926 result.push_str("(");
1927 if context.config.fn_args_layout() == IndentStyle::Visual {
1929 result.push_str(&arg_indent.to_string(context.config));
1936 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1940 if multi_line_ret_str {
1941 one_line_budget = 0;
1944 // A conservative estimation, to goal is to be over all parens in generics
1945 let args_start = generics.ty_params.last().map_or(
1947 |tp| end_typaram(tp),
1949 let args_span = mk_sp(
1950 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1951 span_for_return(&fd.output).lo,
1953 let arg_str = try_opt!(rewrite_args(
1956 fd.get_self().as_ref(),
1963 generics_str.contains('\n'),
1966 let multi_line_arg_str = arg_str.contains('\n') ||
1967 arg_str.chars().last().map_or(false, |c| c == ',');
1969 let put_args_in_block = match context.config.fn_args_layout() {
1970 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1972 } && !fd.inputs.is_empty();
1974 let mut args_last_line_contains_comment = false;
1975 if put_args_in_block {
1976 arg_indent = indent.block_indent(context.config);
1978 result.push_str(&arg_indent.to_string(context.config));
1979 result.push_str(&arg_str);
1981 result.push_str(&indent.to_string(context.config));
1984 result.push_str(&arg_str);
1985 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1988 // If the last line of args contains comment, we cannot put the closing paren
1989 // on the same line.
1990 if arg_str.lines().last().map_or(
1992 |last_line| last_line.contains("//"),
1995 args_last_line_contains_comment = true;
1997 result.push_str(&arg_indent.to_string(context.config));
2003 if !ret_str.is_empty() {
2004 let ret_should_indent = match context.config.fn_args_layout() {
2005 // If our args are block layout then we surely must have space.
2006 IndentStyle::Block if put_args_in_block => false,
2008 // If we've already gone multi-line, or the return type would push over the max
2009 // width, then put the return type on a new line. With the +1 for the signature
2010 // length an additional space between the closing parenthesis of the argument and
2011 // the arrow '->' is considered.
2012 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2014 // If there is no where clause, take into account the space after the return type
2016 if where_clause.predicates.is_empty() {
2020 let overlong_sig = sig_length > context.config.max_width();
2022 (!args_last_line_contains_comment) &&
2023 (result.contains('\n') || multi_line_ret_str || overlong_sig)
2026 let ret_indent = if ret_should_indent {
2027 let indent = match context.config.fn_return_indent() {
2028 ReturnIndent::WithWhereClause => indent + 4,
2029 // Aligning with non-existent args looks silly.
2030 _ if arg_str.is_empty() => {
2031 force_new_line_for_brace = true;
2034 // FIXME: we might want to check that using the arg indent
2035 // doesn't blow our budget, and if it does, then fallback to
2036 // the where clause indent.
2041 result.push_str(&indent.to_string(context.config));
2045 Indent::new(indent.block_indent, last_line_width(&result))
2048 if multi_line_ret_str || ret_should_indent {
2049 // Now that we know the proper indent and width, we need to
2050 // re-layout the return type.
2051 let ret_str = try_opt!(fd.output.rewrite(
2053 Shape::indented(ret_indent, context.config),
2055 result.push_str(&ret_str);
2057 result.push_str(&ret_str);
2060 // Comment between return type and the end of the decl.
2061 let snippet_lo = fd.output.span().hi;
2062 if where_clause.predicates.is_empty() {
2063 let snippet_hi = span.hi;
2064 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2065 // Try to preserve the layout of the original snippet.
2066 let original_starts_with_newline = snippet.find(|c| c != ' ').map_or(
2068 |i| snippet[i..].starts_with('\n'),
2070 let original_ends_with_newline = snippet.rfind(|c| c != ' ').map_or(
2072 |i| snippet[i..].ends_with('\n'),
2074 let snippet = snippet.trim();
2075 if !snippet.is_empty() {
2076 result.push(if original_starts_with_newline {
2081 result.push_str(snippet);
2082 if original_ends_with_newline {
2083 force_new_line_for_brace = true;
2087 // FIXME it would be nice to catch comments between the return type
2088 // and the where clause, but we don't have a span for the where
2093 let should_compress_where = match context.config.where_density() {
2094 Density::Compressed => !result.contains('\n') || put_args_in_block,
2095 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2097 } || (put_args_in_block && ret_str.is_empty());
2099 if where_clause.predicates.len() == 1 && should_compress_where {
2100 let budget = try_opt!(
2104 .checked_sub(last_line_width(&result))
2106 if let Some(where_clause_str) =
2107 rewrite_where_clause(
2110 context.config.fn_brace_style(),
2111 Shape::legacy(budget, indent),
2112 Density::Compressed,
2115 put_args_in_block && ret_str.is_empty(),
2119 if !where_clause_str.contains('\n') {
2120 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
2124 result.push_str(&where_clause_str);
2126 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2127 return Some((result, force_new_line_for_brace));
2132 let where_clause_str = try_opt!(rewrite_where_clause(
2135 context.config.fn_brace_style(),
2136 Shape::indented(indent, context.config),
2140 put_args_in_block && ret_str.is_empty(),
2144 result.push_str(&where_clause_str);
2146 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2147 return Some((result, force_new_line_for_brace));
2150 fn last_line_contains_single_line_comment(s: &str) -> bool {
2151 s.lines().last().map_or(false, |l| l.contains("//"))
2155 context: &RewriteContext,
2157 explicit_self: Option<&ast::ExplicitSelf>,
2158 one_line_budget: usize,
2159 multi_line_budget: usize,
2164 generics_str_contains_newline: bool,
2165 ) -> Option<String> {
2166 let mut arg_item_strs = try_opt!(
2169 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2171 .collect::<Option<Vec<_>>>()
2174 // Account for sugary self.
2175 // FIXME: the comment for the self argument is dropped. This is blocked
2176 // on rust issue #27522.
2177 let min_args = explicit_self
2178 .and_then(|explicit_self| {
2179 rewrite_explicit_self(explicit_self, args, context)
2181 .map_or(1, |self_str| {
2182 arg_item_strs[0] = self_str;
2186 // Comments between args.
2187 let mut arg_items = Vec::new();
2189 arg_items.push(ListItem::from_str(""));
2192 // FIXME(#21): if there are no args, there might still be a comment, but
2193 // without spans for the comment or parens, there is no chance of
2194 // getting it right. You also don't get to put a comment on self, unless
2196 if args.len() >= min_args || variadic {
2197 let comment_span_start = if min_args == 2 {
2198 let second_arg_start = if arg_has_pattern(&args[1]) {
2203 let reduced_span = mk_sp(span.lo, second_arg_start);
2205 context.codemap.span_after_last(reduced_span, ",")
2210 enum ArgumentKind<'a> {
2211 Regular(&'a ast::Arg),
2215 let variadic_arg = if variadic {
2216 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2217 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2218 Some(ArgumentKind::Variadic(variadic_start))
2223 let more_items = itemize_list(
2225 args[min_args - 1..]
2227 .map(ArgumentKind::Regular)
2228 .chain(variadic_arg),
2231 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2232 ArgumentKind::Variadic(start) => start,
2235 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2236 ArgumentKind::Variadic(start) => start + BytePos(3),
2239 ArgumentKind::Regular(..) => None,
2240 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2246 arg_items.extend(more_items);
2249 let fits_in_one_line = !generics_str_contains_newline &&
2250 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2252 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2253 item.item = Some(arg);
2256 let last_line_ends_with_comment = arg_items
2259 .and_then(|item| item.post_comment.as_ref())
2260 .map_or(false, |s| s.trim().starts_with("//"));
2262 let (indent, trailing_comma, end_with_newline) = match context.config.fn_args_layout() {
2263 IndentStyle::Block if fits_in_one_line => {
2265 indent.block_indent(context.config),
2266 SeparatorTactic::Never,
2270 IndentStyle::Block => {
2272 indent.block_indent(context.config),
2273 SeparatorTactic::Vertical,
2277 IndentStyle::Visual if last_line_ends_with_comment => {
2278 (arg_indent, SeparatorTactic::Vertical, true)
2280 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never, false),
2283 let tactic = definitive_tactic(
2285 context.config.fn_args_density().to_list_tactic(),
2288 let budget = match tactic {
2289 DefinitiveListTactic::Horizontal => one_line_budget,
2290 _ => multi_line_budget,
2293 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2295 let fmt = ListFormatting {
2298 trailing_separator: if variadic {
2299 SeparatorTactic::Never
2303 shape: Shape::legacy(budget, indent),
2304 ends_with_newline: end_with_newline,
2305 config: context.config,
2308 write_list(&arg_items, &fmt)
2311 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2312 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2313 ident.node != symbol::keywords::Invalid.ident()
2319 fn compute_budgets_for_args(
2320 context: &RewriteContext,
2324 newline_brace: bool,
2326 ) -> Option<((usize, usize, Indent))> {
2328 "compute_budgets_for_args {} {:?}, {}, {}",
2334 // Try keeping everything on the same line.
2335 if !result.contains('\n') {
2336 // 2 = `()`, 3 = `() `, space is before ret_string.
2337 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2338 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2348 let one_line_budget = context
2351 .checked_sub(used_space)
2354 if one_line_budget > 0 {
2356 let multi_line_overhead = indent.width() + result.len() +
2357 if newline_brace { 2 } else { 4 };
2358 let multi_line_budget =
2359 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2364 indent + result.len() + 1,
2369 // Didn't work. we must force vertical layout and put args on a newline.
2370 let new_indent = indent.block_indent(context.config);
2371 // Account for `)` and possibly ` {`.
2372 let used_space = new_indent.width() + if ret_str_len == 0 { 1 } else { 3 };
2373 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2374 Some((0, max_space, new_indent))
2377 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2378 match config.fn_brace_style() {
2379 BraceStyle::AlwaysNextLine => true,
2380 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
2385 fn rewrite_generics(
2386 context: &RewriteContext,
2387 generics: &ast::Generics,
2390 ) -> Option<String> {
2391 let shape = generics_shape_from_config(context.config, shape, 0);
2392 rewrite_generics_inner(context, generics, shape, shape.width, span)
2393 .or_else(|| rewrite_generics_inner(context, generics, shape, 0, span))
2396 fn rewrite_generics_inner(
2397 context: &RewriteContext,
2398 generics: &ast::Generics,
2400 one_line_width: usize,
2402 ) -> Option<String> {
2403 // FIXME: convert bounds to where clauses where they get too big or if
2404 // there is a where clause at all.
2405 let lifetimes: &[_] = &generics.lifetimes;
2406 let tys: &[_] = &generics.ty_params;
2407 if lifetimes.is_empty() && tys.is_empty() {
2408 return Some(String::new());
2411 // Strings for the generics.
2412 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2413 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2415 // Extract comments between generics.
2416 let lt_spans = lifetimes.iter().map(|l| {
2417 let hi = if l.bounds.is_empty() {
2420 l.bounds[l.bounds.len() - 1].span.hi
2422 mk_sp(l.lifetime.span.lo, hi)
2424 let ty_spans = tys.iter().map(span_for_ty_param);
2426 let items = itemize_list(
2428 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2432 // FIXME: don't clone
2433 |&(_, ref str)| str.clone(),
2434 context.codemap.span_after(span, "<"),
2437 format_generics_item_list(context, items, shape, one_line_width)
2440 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Shape {
2443 width: shape.width.checked_sub(offset + 2).unwrap_or(0),
2444 ..match config.generics_indent() {
2445 IndentStyle::Visual => shape.visual_indent(1 + offset),
2446 IndentStyle::Block => shape.block().block_indent(config.tab_spaces()),
2451 pub fn format_generics_item_list<I>(
2452 context: &RewriteContext,
2455 one_line_budget: usize,
2458 I: Iterator<Item = ListItem>,
2460 let item_vec = items.collect::<Vec<_>>();
2462 let fmt = ListFormatting {
2463 tactic: definitive_tactic(&item_vec, ListTactic::HorizontalVertical, one_line_budget),
2465 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2466 SeparatorTactic::Never
2468 context.config.trailing_comma()
2471 ends_with_newline: false,
2472 config: context.config,
2475 let list_str = try_opt!(write_list(&item_vec, &fmt));
2477 Some(wrap_generics_with_angle_brackets(
2484 pub fn wrap_generics_with_angle_brackets(
2485 context: &RewriteContext,
2487 list_offset: Indent,
2489 if context.config.generics_indent() == IndentStyle::Block &&
2490 (list_str.contains('\n') || list_str.ends_with(','))
2494 list_offset.to_string(context.config),
2497 .block_unindent(context.config)
2498 .to_string(context.config)
2500 } else if context.config.spaces_within_angle_brackets() {
2501 format!("< {} >", list_str)
2503 format!("<{}>", list_str)
2507 fn rewrite_trait_bounds(
2508 context: &RewriteContext,
2509 type_param_bounds: &ast::TyParamBounds,
2511 ) -> Option<String> {
2512 let bounds: &[_] = type_param_bounds;
2514 if bounds.is_empty() {
2515 return Some(String::new());
2517 let bound_str = try_opt!(
2520 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2521 .collect::<Option<Vec<_>>>()
2523 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2526 fn rewrite_where_clause_rfc_style(
2527 context: &RewriteContext,
2528 where_clause: &ast::WhereClause,
2531 suppress_comma: bool,
2532 // where clause can be kept on the current line.
2534 span_end: Option<BytePos>,
2535 ) -> Option<String> {
2536 let block_shape = shape.block();
2538 let starting_newline = if snuggle {
2541 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2544 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2545 // each clause on one line, trailing comma (except if suppress_comma)
2546 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2547 // If we don't have the start of the next span, then use the end of the
2548 // predicates, but that means we miss comments.
2549 let len = where_clause.predicates.len();
2550 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2551 let span_end = span_end.unwrap_or(end_of_preds);
2552 let items = itemize_list(
2554 where_clause.predicates.iter(),
2556 |pred| span_for_where_pred(pred).lo,
2557 |pred| span_for_where_pred(pred).hi,
2558 |pred| pred.rewrite(context, shape),
2562 let comma_tactic = if suppress_comma {
2563 SeparatorTactic::Never
2565 SeparatorTactic::Always
2568 let fmt = ListFormatting {
2569 tactic: DefinitiveListTactic::Vertical,
2571 trailing_separator: comma_tactic,
2572 shape: clause_shape,
2573 ends_with_newline: true,
2574 config: context.config,
2576 let preds_str = try_opt!(write_list(items, &fmt));
2581 clause_shape.indent.to_string(context.config),
2586 fn rewrite_where_clause(
2587 context: &RewriteContext,
2588 where_clause: &ast::WhereClause,
2589 brace_style: BraceStyle,
2593 suppress_comma: bool,
2595 span_end: Option<BytePos>,
2596 ) -> Option<String> {
2597 if where_clause.predicates.is_empty() {
2598 return Some(String::new());
2601 if context.config.where_style() == Style::Rfc {
2602 return rewrite_where_clause_rfc_style(
2613 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2615 let offset = match context.config.where_pred_indent() {
2616 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2617 // 6 = "where ".len()
2618 IndentStyle::Visual => shape.indent + extra_indent + 6,
2620 // FIXME: if where_pred_indent != Visual, then the budgets below might
2621 // be out by a char or two.
2623 let budget = context.config.max_width() - offset.width();
2624 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
2625 // If we don't have the start of the next span, then use the end of the
2626 // predicates, but that means we miss comments.
2627 let len = where_clause.predicates.len();
2628 let end_of_preds = span_for_where_pred(&where_clause.predicates[len - 1]).hi;
2629 let span_end = span_end.unwrap_or(end_of_preds);
2630 let items = itemize_list(
2632 where_clause.predicates.iter(),
2634 |pred| span_for_where_pred(pred).lo,
2635 |pred| span_for_where_pred(pred).hi,
2636 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2640 let item_vec = items.collect::<Vec<_>>();
2641 // FIXME: we don't need to collect here if the where_layout isn't
2642 // HorizontalVertical.
2643 let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget);
2645 let mut comma_tactic = context.config.trailing_comma();
2646 // Kind of a hack because we don't usually have trailing commas in where clauses.
2647 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2648 comma_tactic = SeparatorTactic::Never;
2651 let fmt = ListFormatting {
2654 trailing_separator: comma_tactic,
2655 shape: Shape::legacy(budget, offset),
2656 ends_with_newline: true,
2657 config: context.config,
2659 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2661 let end_length = if terminator == "{" {
2662 // If the brace is on the next line we don't need to count it otherwise it needs two
2665 BraceStyle::AlwaysNextLine |
2666 BraceStyle::SameLineWhere => 0,
2667 BraceStyle::PreferSameLine => 2,
2669 } else if terminator == "=" {
2674 if density == Density::Tall || preds_str.contains('\n') ||
2675 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2679 (shape.indent + extra_indent).to_string(context.config),
2683 Some(format!(" where {}", preds_str))
2687 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2688 format!("{}{}{}", format_visibility(vis), item_name, ident)
2692 context: &RewriteContext,
2693 generics: &ast::Generics,
2696 brace_style: BraceStyle,
2697 force_same_line_brace: bool,
2700 ) -> Option<String> {
2701 let shape = Shape::indented(offset, context.config);
2702 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2704 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2705 let budget = try_opt!(
2709 .checked_sub(last_line_width(&result))
2711 let where_clause_str = try_opt!(rewrite_where_clause(
2713 &generics.where_clause,
2715 Shape::legacy(budget, offset.block_only()),
2719 trimmed_last_line_width(&result) == 1,
2722 result.push_str(&where_clause_str);
2723 let same_line_brace = force_same_line_brace ||
2724 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1);
2725 if !same_line_brace &&
2726 (brace_style == BraceStyle::SameLineWhere ||
2727 brace_style == BraceStyle::AlwaysNextLine)
2730 result.push_str(&offset.block_only().to_string(context.config));
2734 result.push_str(opener);
2736 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2737 brace_style != BraceStyle::AlwaysNextLine
2742 result.push_str(&offset.block_only().to_string(context.config));
2744 result.push_str(opener);