1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
15 use syntax::{abi, ast, ptr, symbol};
16 use syntax::ast::ImplItem;
17 use syntax::codemap::{BytePos, Span};
19 use {Indent, Shape, Spanned};
20 use codemap::SpanUtils;
21 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
22 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
23 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
24 rewrite_call_inner, ExprType};
25 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
26 ListItem, ListTactic, SeparatorTactic};
27 use rewrite::{Rewrite, RewriteContext};
28 use types::join_bounds;
29 use utils::{colon_spaces, contains_skip, end_typaram, format_mutability, format_unsafety,
30 format_visibility, last_line_width, mk_sp, semicolon_for_expr, stmt_expr,
31 trim_newlines, trimmed_last_line_width, wrap_str};
32 use vertical::rewrite_with_alignment;
33 use visitor::FmtVisitor;
35 fn type_annotation_separator(config: &Config) -> &str {
37 config.space_before_type_annotation(),
38 config.space_after_type_annotation_colon(),
43 // Statements of the form
44 // let pat: ty = init;
45 impl Rewrite for ast::Local {
46 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
48 "Local::rewrite {:?} {} {:?}",
53 let mut result = "let ".to_owned();
56 let pat_shape = try_opt!(shape.offset_left(4));
58 let pat_shape = try_opt!(pat_shape.sub_width(1));
59 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
60 result.push_str(&pat_str);
62 // String that is placed within the assignment pattern and expression.
64 let mut infix = String::new();
66 if let Some(ref ty) = self.ty {
67 let separator = type_annotation_separator(context.config);
68 let indent = shape.indent + last_line_width(&result) + separator.len();
70 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
71 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
73 infix.push_str(separator);
74 infix.push_str(&rewrite);
77 if self.init.is_some() {
84 result.push_str(&infix);
86 if let Some(ref ex) = self.init {
87 // 1 = trailing semicolon;
88 let nested_shape = try_opt!(shape.sub_width(1));
90 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
98 // TODO convert to using rewrite style rather than visitor
99 // TODO format modules in this style
102 keyword: &'static str,
104 vis: Option<&'a ast::Visibility>,
105 body: Vec<BodyElement<'a>>,
110 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
111 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
114 format!("extern {}", fm.abi)
122 .map(|i| BodyElement::ForeignItem(i))
129 enum BodyElement<'a> {
130 // Stmt(&'a ast::Stmt),
131 // Field(&'a ast::Field),
132 // Variant(&'a ast::Variant),
133 // Item(&'a ast::Item),
134 ForeignItem(&'a ast::ForeignItem),
137 impl<'a> FmtVisitor<'a> {
138 fn format_item(&mut self, item: Item) {
139 self.buffer.push_str(&item.abi);
140 self.buffer.push_str(" ");
142 let snippet = self.snippet(item.span);
143 let brace_pos = snippet.find_uncommented("{").unwrap();
145 self.buffer.push_str("{");
146 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
147 // FIXME: this skips comments between the extern keyword and the opening
149 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
150 self.block_indent = self.block_indent.block_indent(self.config);
152 if item.body.is_empty() {
153 self.format_missing_no_indent(item.span.hi - BytePos(1));
154 self.block_indent = self.block_indent.block_unindent(self.config);
157 .push_str(&self.block_indent.to_string(self.config));
159 for item in &item.body {
160 self.format_body_element(item);
163 self.block_indent = self.block_indent.block_unindent(self.config);
164 self.format_missing_with_indent(item.span.hi - BytePos(1));
168 self.buffer.push_str("}");
169 self.last_pos = item.span.hi;
172 fn format_body_element(&mut self, element: &BodyElement) {
174 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
178 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
179 let item = Item::from_foreign_mod(fm, span, self.config);
180 self.format_item(item);
183 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
184 self.format_missing_with_indent(item.span.lo);
185 // Drop semicolon or it will be interpreted as comment.
186 // FIXME: this may be a faulty span from libsyntax.
187 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
190 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
191 let indent = self.block_indent;
192 let rewrite = rewrite_fn_base(
198 ast::Unsafety::Normal,
199 ast::Constness::NotConst,
200 ast::Defaultness::Final,
201 // These are not actually rust functions,
202 // but we format them as such.
212 Some((new_fn, _)) => {
213 self.buffer.push_str(&new_fn);
214 self.buffer.push_str(";");
216 None => self.format_missing(item.span.hi),
219 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
220 // FIXME(#21): we're dropping potential comments in between the
221 // function keywords here.
222 let vis = format_visibility(&item.vis);
223 let mut_str = if is_mutable { "mut " } else { "" };
224 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
225 let offset = self.block_indent + prefix.len();
227 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
228 let rewrite = ty.rewrite(&self.get_context(), shape);
232 self.buffer.push_str(&prefix);
233 self.buffer.push_str(&result);
234 self.buffer.push_str(";");
236 None => self.format_missing(item.span.hi),
241 self.last_pos = item.span.hi;
249 generics: &ast::Generics,
250 unsafety: ast::Unsafety,
251 constness: ast::Constness,
252 defaultness: ast::Defaultness,
254 vis: &ast::Visibility,
257 ) -> Option<String> {
258 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
259 let context = self.get_context();
261 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
262 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
263 !context.config.fn_empty_single_line();
265 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
282 if force_newline_brace {
283 newline_brace = true;
284 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
285 !result.contains('\n')
287 newline_brace = false;
290 // Prepare for the function body by possibly adding a newline and
292 // FIXME we'll miss anything between the end of the signature and the
293 // start of the body, but we need more spans from the compiler to solve
297 result.push_str(&indent.to_string(self.config));
302 self.single_line_fn(&result, block).or_else(|| Some(result))
305 pub fn rewrite_required_fn(
309 sig: &ast::MethodSig,
311 ) -> Option<String> {
312 // Drop semicolon or it will be interpreted as comment.
313 let span = mk_sp(span.lo, span.hi - BytePos(1));
314 let context = self.get_context();
316 let (mut result, _) = try_opt!(rewrite_fn_base(
324 ast::Defaultness::Final,
326 &ast::Visibility::Inherited,
333 // Re-attach semicolon
339 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
340 if fn_str.contains('\n') {
344 let codemap = self.get_context().codemap;
346 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
347 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
349 return Some(format!("{}{{}}", fn_str));
352 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
354 if let Some(ref stmt) = block.stmts.first() {
355 match stmt_expr(stmt) {
357 let suffix = if semicolon_for_expr(&self.get_context(), e) {
367 Shape::indented(self.block_indent, self.config),
368 ).map(|s| s + suffix)
369 .or_else(|| Some(self.snippet(e.span)))
371 None => stmt.rewrite(
373 Shape::indented(self.block_indent, self.config),
381 if let Some(res) = rewrite {
382 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
383 if !res.contains('\n') && width <= self.config.max_width() {
384 return Some(format!("{}{{ {} }}", fn_str, res));
395 vis: &ast::Visibility,
396 enum_def: &ast::EnumDef,
397 generics: &ast::Generics,
400 let enum_header = format_header("enum ", ident, vis);
401 self.buffer.push_str(&enum_header);
403 let enum_snippet = self.snippet(span);
404 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
405 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
406 let generics_str = format_generics(
411 self.config.item_brace_style(),
412 enum_def.variants.is_empty(),
414 mk_sp(span.lo, body_start),
415 last_line_width(&enum_header),
417 self.buffer.push_str(&generics_str);
419 self.last_pos = body_start;
421 self.block_indent = self.block_indent.block_indent(self.config);
422 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
424 Some(ref body_str) => self.buffer.push_str(body_str),
425 None => if contains_comment(&enum_snippet[brace_pos..]) {
426 self.format_missing_no_indent(span.hi - BytePos(1))
428 self.format_missing(span.hi - BytePos(1))
431 self.block_indent = self.block_indent.block_unindent(self.config);
433 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
435 .push_str(&self.block_indent.to_string(self.config));
437 self.buffer.push_str("}");
438 self.last_pos = span.hi;
441 // Format the body of an enum definition
442 fn format_variant_list(
444 enum_def: &ast::EnumDef,
447 ) -> Option<String> {
448 if enum_def.variants.is_empty() {
451 let mut result = String::with_capacity(1024);
453 let indentation = self.block_indent.to_string(self.config);
454 result.push_str(&indentation);
456 let items = itemize_list(
458 enum_def.variants.iter(),
460 |f| if !f.node.attrs.is_empty() {
461 f.node.attrs[0].span.lo
466 |f| self.format_variant(f),
471 let shape = Shape::indented(self.block_indent, self.config)
474 let fmt = ListFormatting {
475 tactic: DefinitiveListTactic::Vertical,
477 trailing_separator: self.config.trailing_comma(),
479 ends_with_newline: true,
483 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
484 result.push_str(&list);
489 // Variant of an enum.
490 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
491 if contains_skip(&field.node.attrs) {
492 let lo = field.node.attrs[0].span.lo;
493 let span = mk_sp(lo, field.span.hi);
494 return Some(self.snippet(span));
497 let context = self.get_context();
498 let indent = self.block_indent;
499 let mut result = try_opt!(
503 .rewrite(&context, Shape::indented(indent, self.config))
505 if !result.is_empty() {
507 width: context.config.max_width(),
508 indent: self.block_indent,
509 offset: self.block_indent.alignment,
511 let missing_comment = rewrite_missing_comment_on_field(
514 field.node.attrs[field.node.attrs.len() - 1].span.hi,
517 ).unwrap_or(String::new());
518 result.push_str(&missing_comment);
521 let variant_body = match field.node.data {
522 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
523 // FIXME: Should limit the width, as we have a trailing comma
528 &ast::Visibility::Inherited,
533 Some(self.config.struct_variant_width()),
536 ast::VariantData::Unit(..) => {
537 let tag = if let Some(ref expr) = field.node.disr_expr {
538 format!("{} = {}", field.node.name, self.snippet(expr.span))
540 field.node.name.to_string()
545 self.config.max_width(),
546 Shape::indented(indent, self.config),
551 if let Some(variant_str) = variant_body {
552 result.push_str(&variant_str);
561 context: &RewriteContext,
564 where_span_end: Option<BytePos>,
565 ) -> Option<String> {
566 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
567 let mut result = String::new();
568 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
569 result.push_str(&ref_and_type);
571 let where_budget = if result.contains('\n') {
572 context.config.max_width()
577 .checked_sub(last_line_width(&result))
580 let where_clause_str = try_opt!(rewrite_where_clause(
582 &generics.where_clause,
583 context.config.item_brace_style(),
584 Shape::legacy(where_budget, offset.block_only()),
585 context.config.where_density(),
588 last_line_width(&ref_and_type) == 1,
594 if try_opt!(is_impl_single_line(
601 result.push_str(&where_clause_str);
602 if where_clause_str.contains('\n') {
603 let white_space = offset.to_string(context.config);
604 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
606 result.push_str(" {}");
611 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
613 let width = offset.block_indent + context.config.tab_spaces() - 1;
614 let where_indent = Indent::new(0, width);
615 result.push_str(&where_indent.to_string(context.config));
617 result.push_str(&where_clause_str);
619 match context.config.item_brace_style() {
620 BraceStyle::AlwaysNextLine => {
622 result.push_str(&offset.to_string(context.config));
624 BraceStyle::PreferSameLine => result.push(' '),
625 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
627 result.push_str(&offset.to_string(context.config));
635 let snippet = context.snippet(item.span);
636 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
638 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
639 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
640 visitor.block_indent = offset.block_only().block_indent(context.config);
641 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
644 visitor.visit_impl_item(item);
647 visitor.format_missing(item.span.hi - BytePos(1));
649 let inner_indent_str = visitor.block_indent.to_string(context.config);
650 let outer_indent_str = offset.block_only().to_string(context.config);
653 result.push_str(&inner_indent_str);
654 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
656 result.push_str(&outer_indent_str);
659 if result.chars().last().unwrap() == '{' {
661 result.push_str(&offset.to_string(context.config));
671 fn is_impl_single_line(
672 context: &RewriteContext,
675 where_clause_str: &str,
678 let snippet = context.snippet(item.span);
679 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
682 context.config.impl_empty_single_line() && items.is_empty() &&
683 result.len() + where_clause_str.len() <= context.config.max_width() &&
684 !contains_comment(&snippet[open_pos..]),
688 fn format_impl_ref_and_type(
689 context: &RewriteContext,
692 ) -> Option<String> {
693 if let ast::ItemKind::Impl(
703 let mut result = String::new();
705 result.push_str(&format_visibility(&item.vis));
706 result.push_str(format_unsafety(unsafety));
707 result.push_str("impl");
709 let lo = context.codemap.span_after(item.span, "impl");
710 let hi = match *trait_ref {
711 Some(ref tr) => tr.path.span.lo,
712 None => self_ty.span.lo,
714 let shape = try_opt!(generics_shape_from_config(
716 Shape::indented(offset + last_line_width(&result), context.config),
719 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
720 let generics_str = try_opt!(rewrite_generics_inner(
728 let polarity_str = if polarity == ast::ImplPolarity::Negative {
734 if let Some(ref trait_ref) = *trait_ref {
735 let result_len = result.len();
736 if let Some(trait_ref_str) = rewrite_trait_ref(
745 result.push_str(&trait_ref_str);
747 let generics_str = try_opt!(rewrite_generics_inner(
754 result.push_str(&try_opt!(rewrite_trait_ref(
765 result.push_str(&generics_str);
768 // Try to put the self type in a single line.
770 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
771 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
772 // If there is no where clause adapt budget for type formatting to take space and curly
773 // brace into account.
774 match context.config.item_brace_style() {
775 BraceStyle::AlwaysNextLine => 0,
781 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
782 // 1 = space before the type.
786 .checked_sub(used_space + 1)
788 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
789 if !self_ty_str.contains('\n') {
790 if trait_ref.is_some() {
791 result.push_str(" for ");
795 result.push_str(&self_ty_str);
800 // Couldn't fit the self type on a single line, put it on a new line.
802 // Add indentation of one additional tab.
803 let new_line_offset = offset.block_indent(context.config);
804 result.push_str(&new_line_offset.to_string(context.config));
805 if trait_ref.is_some() {
806 result.push_str("for ");
808 let budget = context.config.max_width() - last_line_width(&result);
809 let type_offset = match context.config.where_style() {
810 Style::Legacy => new_line_offset + trait_ref_overhead,
811 Style::Rfc => new_line_offset,
813 result.push_str(&*try_opt!(
814 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
822 fn rewrite_trait_ref(
823 context: &RewriteContext,
824 trait_ref: &ast::TraitRef,
830 ) -> Option<String> {
831 // 1 = space between generics and trait_ref
832 let used_space = 1 + polarity_str.len() +
833 if generics_str.contains('\n') {
834 last_line_width(&generics_str)
836 result_len + generics_str.len()
838 let shape = Shape::indented(offset + used_space, context.config);
839 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
840 if !(retry && trait_ref_str.contains('\n')) {
849 // We could not make enough space for trait_ref, so put it on new line.
851 let offset = offset.block_indent(context.config);
852 let shape = Shape::indented(offset, context.config);
853 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
857 &offset.to_string(context.config),
866 pub fn format_struct(
867 context: &RewriteContext,
870 vis: &ast::Visibility,
871 struct_def: &ast::VariantData,
872 generics: Option<&ast::Generics>,
875 one_line_width: Option<usize>,
876 ) -> Option<String> {
878 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
879 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
889 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
903 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
904 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
907 let mut result = String::new();
908 let header = format!(
910 format_visibility(&item.vis),
911 format_unsafety(unsafety),
915 result.push_str(&header);
917 let body_lo = context.codemap.span_after(item.span, "{");
919 let shape = Shape::indented(offset + last_line_width(&result), context.config);
920 let generics_str = try_opt!(rewrite_generics(
924 mk_sp(item.span.lo, body_lo),
926 result.push_str(&generics_str);
928 let trait_bound_str = try_opt!(rewrite_trait_bounds(
931 Shape::indented(offset, context.config),
933 // If the trait, generics, and trait bound cannot fit on the same line,
934 // put the trait bounds on an indented new line
935 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
936 context.config.comment_width()
939 let trait_indent = offset.block_only().block_indent(context.config);
940 result.push_str(&trait_indent.to_string(context.config));
942 result.push_str(&trait_bound_str);
944 let has_body = !trait_items.is_empty();
946 let where_density = if (context.config.where_density() == Density::Compressed &&
947 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
948 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
949 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
950 !result.contains('\n'))
957 let where_budget = try_opt!(
961 .checked_sub(last_line_width(&result))
963 let pos_before_where = if type_param_bounds.is_empty() {
964 // We do not use this, so it does not matter
967 type_param_bounds[type_param_bounds.len() - 1].span().hi
969 let where_clause_str = try_opt!(rewrite_where_clause(
971 &generics.where_clause,
972 context.config.item_brace_style(),
973 Shape::legacy(where_budget, offset.block_only()),
977 trait_bound_str.is_empty() && last_line_width(&generics_str) == 1,
982 // If the where clause cannot fit on the same line,
983 // put the where clause on a new line
984 if !where_clause_str.contains('\n') &&
985 last_line_width(&result) + where_clause_str.len() + offset.width() >
986 context.config.comment_width()
989 let width = offset.block_indent + context.config.tab_spaces() - 1;
990 let where_indent = Indent::new(0, width);
991 result.push_str(&where_indent.to_string(context.config));
993 result.push_str(&where_clause_str);
995 match context.config.item_brace_style() {
996 BraceStyle::AlwaysNextLine => {
998 result.push_str(&offset.to_string(context.config));
1000 BraceStyle::PreferSameLine => result.push(' '),
1001 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1002 (!trait_items.is_empty() || result.contains('\n'))
1005 result.push_str(&offset.to_string(context.config));
1012 let snippet = context.snippet(item.span);
1013 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1015 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1016 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1017 visitor.block_indent = offset.block_only().block_indent(context.config);
1018 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1020 for item in trait_items {
1021 visitor.visit_trait_item(item);
1024 visitor.format_missing(item.span.hi - BytePos(1));
1026 let inner_indent_str = visitor.block_indent.to_string(context.config);
1027 let outer_indent_str = offset.block_only().to_string(context.config);
1030 result.push_str(&inner_indent_str);
1031 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1033 result.push_str(&outer_indent_str);
1034 } else if result.contains('\n') {
1045 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1046 format!("{};", format_header(item_name, ident, vis))
1049 pub fn format_struct_struct(
1050 context: &RewriteContext,
1053 vis: &ast::Visibility,
1054 fields: &[ast::StructField],
1055 generics: Option<&ast::Generics>,
1058 one_line_width: Option<usize>,
1059 ) -> Option<String> {
1060 let mut result = String::with_capacity(1024);
1062 let header_str = format_header(item_name, ident, vis);
1063 result.push_str(&header_str);
1065 let body_lo = context.codemap.span_after(span, "{");
1067 let generics_str = match generics {
1068 Some(g) => try_opt!(format_generics(
1073 context.config.item_brace_style(),
1076 mk_sp(span.lo, body_lo),
1077 last_line_width(&result),
1080 // 3 = ` {}`, 2 = ` {`.
1081 let overhead = if fields.is_empty() { 3 } else { 2 };
1082 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1083 !fields.is_empty()) ||
1087 .checked_sub(result.len())
1088 .unwrap_or(0) < overhead
1090 format!("\n{}{{", offset.block_only().to_string(context.config))
1097 let overhead = if fields.is_empty() { 1 } else { 0 };
1098 let max_len = context.config.max_width() - offset.width();
1099 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1101 result.push_str(&offset
1102 .block_indent(context.config)
1103 .to_string(context.config));
1104 result.push_str(&generics_str.trim_left());
1106 result.push_str(&generics_str);
1109 if fields.is_empty() {
1110 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1111 if snippet.trim().is_empty() {
1113 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1115 result.push_str(&snippet.trim_right());
1117 result.push_str(&offset.to_string(context.config));
1119 result.push_str(&snippet);
1122 return Some(result);
1126 let one_line_budget = context
1129 .checked_sub(result.len() + 3 + offset.width())
1132 let items_str = try_opt!(rewrite_with_alignment(
1135 Shape::indented(offset, context.config),
1136 mk_sp(body_lo, span.hi),
1137 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget)),
1140 if one_line_width.is_some() && !items_str.contains('\n') && !result.contains('\n') {
1141 Some(format!("{} {} }}", result, items_str))
1147 .block_indent(context.config)
1148 .to_string(context.config),
1150 offset.to_string(context.config)
1155 fn format_tuple_struct(
1156 context: &RewriteContext,
1159 vis: &ast::Visibility,
1160 fields: &[ast::StructField],
1161 generics: Option<&ast::Generics>,
1164 ) -> Option<String> {
1165 let mut result = String::with_capacity(1024);
1167 let header_str = format_header(item_name, ident, vis);
1168 result.push_str(&header_str);
1170 let body_lo = if fields.is_empty() {
1171 context.codemap.span_after(span, "(")
1175 let body_hi = if fields.is_empty() {
1176 context.codemap.span_after(span, ")")
1178 // This is a dirty hack to work around a missing `)` from the span of the last field.
1179 let last_arg_span = fields[fields.len() - 1].span;
1180 if context.snippet(last_arg_span).ends_with(")") {
1185 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1189 let where_clause_str = match generics {
1191 let budget = context.budget(last_line_width(&header_str));
1192 let shape = Shape::legacy(budget, offset);
1193 let g_span = mk_sp(span.lo, body_lo);
1194 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1195 result.push_str(&generics_str);
1197 let where_budget = context.budget(last_line_width(&result));
1198 try_opt!(rewrite_where_clause(
1200 &generics.where_clause,
1201 context.config.item_brace_style(),
1202 Shape::legacy(where_budget, offset.block_only()),
1203 Density::Compressed,
1212 None => "".to_owned(),
1215 if fields.is_empty() {
1217 let used_width = if result.contains('\n') {
1218 last_line_width(&result) + 3
1220 offset.width() + result.len() + 3
1222 if used_width > context.config.max_width() {
1224 result.push_str(&offset
1225 .block_indent(context.config)
1226 .to_string(context.config))
1229 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1230 if snippet.is_empty() {
1232 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1233 result.push_str(&snippet.trim_right());
1235 result.push_str(&offset.to_string(context.config));
1237 result.push_str(&snippet);
1242 let body = try_opt!(
1246 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1248 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1249 context.config.fn_call_width(),
1253 result.push_str(&body);
1256 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1257 (result.contains('\n') ||
1258 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1259 context.config.max_width())
1261 // We need to put the where clause on a new line, but we didn't
1262 // know that earlier, so the where clause will not be indented properly.
1264 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1265 .to_string(context.config));
1267 result.push_str(&where_clause_str);
1272 pub fn rewrite_type_alias(
1273 context: &RewriteContext,
1277 generics: &ast::Generics,
1278 vis: &ast::Visibility,
1280 ) -> Option<String> {
1281 let mut result = String::new();
1283 result.push_str(&format_visibility(vis));
1284 result.push_str("type ");
1285 result.push_str(&ident.to_string());
1288 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1289 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1290 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1291 result.push_str(&generics_str);
1293 let where_budget = try_opt!(
1297 .checked_sub(last_line_width(&result))
1299 let where_clause_str = try_opt!(rewrite_where_clause(
1301 &generics.where_clause,
1302 context.config.item_brace_style(),
1303 Shape::legacy(where_budget, indent),
1304 context.config.where_density(),
1312 result.push_str(&where_clause_str);
1313 result.push_str(" = ");
1315 let line_width = last_line_width(&result);
1316 // This checked_sub may fail as the extra space after '=' is not taken into account
1317 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1318 let budget = context
1321 .checked_sub(indent.width() + line_width + ";".len())
1323 let type_indent = indent + line_width;
1324 // Try to fit the type on the same line
1325 let ty_str = try_opt!(
1326 ty.rewrite(context, Shape::legacy(budget, type_indent))
1328 // The line was too short, try to put the type on the next line
1330 // Remove the space after '='
1332 let type_indent = indent.block_indent(context.config);
1334 result.push_str(&type_indent.to_string(context.config));
1335 let budget = try_opt!(
1339 .checked_sub(type_indent.width() + ";".len())
1341 ty.rewrite(context, Shape::legacy(budget, type_indent))
1344 result.push_str(&ty_str);
1345 result.push_str(";");
1349 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1351 if config.space_before_type_annotation() {
1356 if config.space_after_type_annotation_colon() {
1364 fn rewrite_missing_comment_on_field(
1365 context: &RewriteContext,
1369 result: &mut String,
1370 ) -> Option<String> {
1371 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1372 let newline_index = possibly_comment_snippet.find('\n');
1373 let comment_index = possibly_comment_snippet.find('/');
1374 match (newline_index, comment_index) {
1375 (Some(i), Some(j)) if i > j => result.push(' '),
1378 result.push_str(&shape.indent.to_string(context.config));
1381 let trimmed = possibly_comment_snippet.trim();
1382 if trimmed.is_empty() {
1385 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1386 format!("{}\n{}", s, shape.indent.to_string(context.config))
1391 pub fn rewrite_struct_field_prefix(
1392 context: &RewriteContext,
1393 field: &ast::StructField,
1395 ) -> Option<String> {
1396 let vis = format_visibility(&field.vis);
1397 let mut attr_str = try_opt!(
1400 .rewrite(context, Shape::indented(shape.indent, context.config))
1402 // Try format missing comments after attributes
1403 let missing_comment = if !field.attrs.is_empty() {
1404 rewrite_missing_comment_on_field(
1407 field.attrs[field.attrs.len() - 1].span.hi,
1410 ).unwrap_or(String::new())
1415 let type_annotation_spacing = type_annotation_spacing(context.config);
1416 Some(match field.ident {
1417 Some(name) => format!(
1423 type_annotation_spacing.0
1425 None => format!("{}{}{}", attr_str, missing_comment, vis),
1429 fn rewrite_struct_field_type(
1430 context: &RewriteContext,
1431 last_line_width: usize,
1432 field: &ast::StructField,
1435 ) -> Option<String> {
1436 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1439 .rewrite(context, ty_shape)
1440 .map(|ty| format!("{}{}", spacing, ty))
1443 impl Rewrite for ast::StructField {
1444 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1445 rewrite_struct_field(context, self, shape, 0)
1449 pub fn rewrite_struct_field(
1450 context: &RewriteContext,
1451 field: &ast::StructField,
1453 lhs_max_width: usize,
1454 ) -> Option<String> {
1455 if contains_skip(&field.attrs) {
1456 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1457 return wrap_str(span, context.config.max_width(), shape);
1460 let type_annotation_spacing = type_annotation_spacing(context.config);
1461 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1463 // Try to put everything on a single line.
1464 let last_line_width = last_line_width(&prefix);
1465 let mut spacing = String::from(if field.ident.is_some() {
1466 type_annotation_spacing.1
1470 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1471 for _ in 0..lhs_offset {
1474 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1475 if let Some(ref ty) = ty_rewritten {
1476 if !ty.contains('\n') {
1477 return Some(prefix + &ty);
1481 // We must use multiline.
1482 let type_offset = shape.indent.block_indent(context.config);
1483 let rewrite_type_in_next_line = || {
1486 .rewrite(context, Shape::indented(type_offset, context.config))
1489 match ty_rewritten {
1490 // If we start from the next line and type fits in a single line, then do so.
1491 Some(ref ty) => match rewrite_type_in_next_line() {
1492 Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
1495 type_offset.to_string(&context.config),
1498 _ => Some(prefix + &ty),
1501 let ty = try_opt!(rewrite_type_in_next_line());
1505 type_offset.to_string(&context.config),
1512 pub fn rewrite_static(
1514 vis: &ast::Visibility,
1517 mutability: ast::Mutability,
1518 expr_opt: Option<&ptr::P<ast::Expr>>,
1521 context: &RewriteContext,
1522 ) -> Option<String> {
1523 let colon = colon_spaces(
1524 context.config.space_before_type_annotation(),
1525 context.config.space_after_type_annotation_colon(),
1527 let prefix = format!(
1529 format_visibility(vis),
1531 format_mutability(mutability),
1536 let ty_str = try_opt!(ty.rewrite(
1539 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1543 if let Some(expr) = expr_opt {
1544 let lhs = format!("{}{} =", prefix, ty_str);
1546 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1551 Shape::legacy(remaining_width, offset.block_only()),
1553 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1555 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1557 Some(format!("{}{};", prefix, ty_str))
1561 pub fn rewrite_associated_type(
1563 ty_opt: Option<&ptr::P<ast::Ty>>,
1564 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1565 context: &RewriteContext,
1567 ) -> Option<String> {
1568 let prefix = format!("type {}", ident);
1570 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1571 let shape = Shape::indented(indent, context.config);
1572 let bounds: &[_] = ty_param_bounds;
1573 let bound_str = try_opt!(
1576 .map(|ty_bound| ty_bound.rewrite(context, shape))
1577 .collect::<Option<Vec<_>>>()
1579 if bounds.len() > 0 {
1580 format!(": {}", join_bounds(context, shape, &bound_str))
1588 if let Some(ty) = ty_opt {
1589 let ty_str = try_opt!(ty.rewrite(
1592 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1593 indent.block_only(),
1596 Some(format!("{} = {};", prefix, ty_str))
1598 Some(format!("{}{};", prefix, type_bounds_str))
1602 pub fn rewrite_associated_impl_type(
1604 defaultness: ast::Defaultness,
1605 ty_opt: Option<&ptr::P<ast::Ty>>,
1606 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1607 context: &RewriteContext,
1609 ) -> Option<String> {
1610 let result = try_opt!(rewrite_associated_type(
1613 ty_param_bounds_opt,
1619 ast::Defaultness::Default => Some(format!("default {}", result)),
1624 impl Rewrite for ast::FunctionRetTy {
1625 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1627 ast::FunctionRetTy::Default(_) => Some(String::new()),
1628 ast::FunctionRetTy::Ty(ref ty) => {
1629 let inner_width = try_opt!(shape.width.checked_sub(3));
1630 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1631 .map(|r| format!("-> {}", r))
1637 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1639 ast::TyKind::Infer => {
1640 let original = context.snippet(ty.span);
1647 impl Rewrite for ast::Arg {
1648 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1649 if is_named_arg(self) {
1650 let mut result = try_opt!(
1652 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1655 if !is_empty_infer(context, &*self.ty) {
1656 if context.config.space_before_type_annotation() {
1657 result.push_str(" ");
1659 result.push_str(":");
1660 if context.config.space_after_type_annotation_colon() {
1661 result.push_str(" ");
1663 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1664 let ty_str = try_opt!(self.ty.rewrite(
1666 Shape::legacy(max_width, shape.indent + result.len()),
1668 result.push_str(&ty_str);
1673 self.ty.rewrite(context, shape)
1678 fn rewrite_explicit_self(
1679 explicit_self: &ast::ExplicitSelf,
1681 context: &RewriteContext,
1682 ) -> Option<String> {
1683 match explicit_self.node {
1684 ast::SelfKind::Region(lt, m) => {
1685 let mut_str = format_mutability(m);
1688 let lifetime_str = try_opt!(l.rewrite(
1690 Shape::legacy(context.config.max_width(), Indent::empty()),
1692 Some(format!("&{} {}self", lifetime_str, mut_str))
1694 None => Some(format!("&{}self", mut_str)),
1697 ast::SelfKind::Explicit(ref ty, _) => {
1698 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1700 let mutability = explicit_self_mutability(&args[0]);
1701 let type_str = try_opt!(ty.rewrite(
1703 Shape::legacy(context.config.max_width(), Indent::empty()),
1708 format_mutability(mutability),
1712 ast::SelfKind::Value(_) => {
1713 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1715 let mutability = explicit_self_mutability(&args[0]);
1717 Some(format!("{}self", format_mutability(mutability)))
1722 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1723 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1724 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1725 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1732 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1733 if is_named_arg(arg) {
1740 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1742 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1743 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1744 _ => arg.ty.span.hi,
1748 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1749 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1750 ident.node != symbol::keywords::Invalid.ident()
1756 // Return type is (result, force_new_line_for_brace)
1758 context: &RewriteContext,
1762 generics: &ast::Generics,
1763 unsafety: ast::Unsafety,
1764 constness: ast::Constness,
1765 defaultness: ast::Defaultness,
1767 vis: &ast::Visibility,
1769 newline_brace: bool,
1772 ) -> Option<(String, bool)> {
1773 let mut force_new_line_for_brace = false;
1775 let where_clause = &generics.where_clause;
1777 let mut result = String::with_capacity(1024);
1778 // Vis unsafety abi.
1779 result.push_str(&*format_visibility(vis));
1781 if let ast::Defaultness::Default = defaultness {
1782 result.push_str("default ");
1785 if let ast::Constness::Const = constness {
1786 result.push_str("const ");
1789 result.push_str(::utils::format_unsafety(unsafety));
1791 if abi != abi::Abi::Rust {
1792 result.push_str(&::utils::format_abi(
1794 context.config.force_explicit_abi(),
1799 result.push_str("fn ");
1800 result.push_str(&ident.to_string());
1803 let overhead = if has_braces && !newline_brace {
1810 let shape = try_opt!(
1811 Shape::indented(indent + last_line_width(&result), context.config).sub_width(overhead)
1813 let g_span = mk_sp(span.lo, fd.output.span().lo);
1814 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1815 result.push_str(&generics_str);
1817 let snuggle_angle_bracket = generics_str
1820 .map_or(false, |l| l.trim_left().len() == 1);
1822 // Note that the width and indent don't really matter, we'll re-layout the
1823 // return type later anyway.
1824 let ret_str = try_opt!(
1826 .rewrite(&context, Shape::indented(indent, context.config))
1829 let multi_line_ret_str = ret_str.contains('\n');
1830 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1833 let (mut one_line_budget, mut multi_line_budget, mut arg_indent) =
1834 try_opt!(compute_budgets_for_args(
1843 if context.config.fn_args_layout() == IndentStyle::Block {
1844 arg_indent = indent.block_indent(context.config);
1846 multi_line_budget = context.config.max_width() - (arg_indent.width() + 1);
1850 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1856 // Check if vertical layout was forced.
1857 if one_line_budget == 0 {
1858 if snuggle_angle_bracket {
1861 if context.config.fn_args_paren_newline() {
1863 result.push_str(&arg_indent.to_string(context.config));
1864 if context.config.fn_args_layout() == IndentStyle::Visual {
1865 arg_indent = arg_indent + 1; // extra space for `(`
1869 result.push_str("(");
1870 if context.config.fn_args_layout() == IndentStyle::Visual {
1872 result.push_str(&arg_indent.to_string(context.config));
1879 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1883 if multi_line_ret_str {
1884 one_line_budget = 0;
1887 // A conservative estimation, to goal is to be over all parens in generics
1888 let args_start = generics
1891 .map_or(span.lo, |tp| end_typaram(tp));
1892 let args_end = if fd.inputs.is_empty() {
1893 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1895 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1896 context.codemap.span_after(last_span, ")")
1898 let args_span = mk_sp(
1899 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1902 let arg_str = try_opt!(rewrite_args(
1905 fd.get_self().as_ref(),
1912 generics_str.contains('\n'),
1915 let multi_line_arg_str =
1916 arg_str.contains('\n') || arg_str.chars().last().map_or(false, |c| c == ',');
1918 let put_args_in_block = match context.config.fn_args_layout() {
1919 IndentStyle::Block => multi_line_arg_str || generics_str.contains('\n'),
1921 } && !fd.inputs.is_empty();
1923 let mut args_last_line_contains_comment = false;
1924 if put_args_in_block {
1925 arg_indent = indent.block_indent(context.config);
1927 result.push_str(&arg_indent.to_string(context.config));
1928 result.push_str(&arg_str);
1930 result.push_str(&indent.to_string(context.config));
1933 result.push_str(&arg_str);
1934 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1937 // If the last line of args contains comment, we cannot put the closing paren
1938 // on the same line.
1942 .map_or(false, |last_line| last_line.contains("//"))
1944 args_last_line_contains_comment = true;
1946 result.push_str(&arg_indent.to_string(context.config));
1952 if !ret_str.is_empty() {
1953 let ret_should_indent = match context.config.fn_args_layout() {
1954 // If our args are block layout then we surely must have space.
1955 IndentStyle::Block if put_args_in_block => false,
1957 // If we've already gone multi-line, or the return type would push over the max
1958 // width, then put the return type on a new line. With the +1 for the signature
1959 // length an additional space between the closing parenthesis of the argument and
1960 // the arrow '->' is considered.
1961 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1963 // If there is no where clause, take into account the space after the return type
1965 if where_clause.predicates.is_empty() {
1969 let overlong_sig = sig_length > context.config.max_width();
1971 (!args_last_line_contains_comment) &&
1972 (result.contains('\n') || multi_line_ret_str || overlong_sig)
1975 let ret_indent = if ret_should_indent {
1976 let indent = match context.config.fn_return_indent() {
1977 ReturnIndent::WithWhereClause => indent + 4,
1978 // Aligning with non-existent args looks silly.
1979 _ if arg_str.is_empty() => {
1980 force_new_line_for_brace = true;
1983 // FIXME: we might want to check that using the arg indent
1984 // doesn't blow our budget, and if it does, then fallback to
1985 // the where clause indent.
1990 result.push_str(&indent.to_string(context.config));
1994 Indent::new(indent.block_indent, last_line_width(&result))
1997 if multi_line_ret_str || ret_should_indent {
1998 // Now that we know the proper indent and width, we need to
1999 // re-layout the return type.
2000 let ret_str = try_opt!(
2002 .rewrite(context, Shape::indented(ret_indent, context.config))
2004 result.push_str(&ret_str);
2006 result.push_str(&ret_str);
2009 // Comment between return type and the end of the decl.
2010 let snippet_lo = fd.output.span().hi;
2011 if where_clause.predicates.is_empty() {
2012 let snippet_hi = span.hi;
2013 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2014 // Try to preserve the layout of the original snippet.
2015 let original_starts_with_newline = snippet
2017 .map_or(false, |i| snippet[i..].starts_with('\n'));
2018 let original_ends_with_newline = snippet
2019 .rfind(|c| c != ' ')
2020 .map_or(false, |i| snippet[i..].ends_with('\n'));
2021 let snippet = snippet.trim();
2022 if !snippet.is_empty() {
2023 result.push(if original_starts_with_newline {
2028 result.push_str(snippet);
2029 if original_ends_with_newline {
2030 force_new_line_for_brace = true;
2034 // FIXME it would be nice to catch comments between the return type
2035 // and the where clause, but we don't have a span for the where
2040 let should_compress_where = match context.config.where_density() {
2041 Density::Compressed => !result.contains('\n') || put_args_in_block,
2042 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2044 } || (put_args_in_block && ret_str.is_empty());
2046 let pos_before_where = match fd.output {
2047 ast::FunctionRetTy::Default(..) => args_span.hi,
2048 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2050 if where_clause.predicates.len() == 1 && should_compress_where {
2051 let budget = try_opt!(
2055 .checked_sub(last_line_width(&result))
2057 if let Some(where_clause_str) = rewrite_where_clause(
2060 context.config.fn_brace_style(),
2061 Shape::legacy(budget, indent),
2062 Density::Compressed,
2065 put_args_in_block && ret_str.is_empty(),
2070 if !where_clause_str.contains('\n') {
2071 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
2075 result.push_str(&where_clause_str);
2077 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2078 return Some((result, force_new_line_for_brace));
2083 let where_clause_str = try_opt!(rewrite_where_clause(
2086 context.config.fn_brace_style(),
2087 Shape::indented(indent, context.config),
2091 put_args_in_block && ret_str.is_empty(),
2097 result.push_str(&where_clause_str);
2099 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2100 return Some((result, force_new_line_for_brace));
2103 fn last_line_contains_single_line_comment(s: &str) -> bool {
2104 s.lines().last().map_or(false, |l| l.contains("//"))
2108 context: &RewriteContext,
2110 explicit_self: Option<&ast::ExplicitSelf>,
2111 one_line_budget: usize,
2112 multi_line_budget: usize,
2117 generics_str_contains_newline: bool,
2118 ) -> Option<String> {
2119 let mut arg_item_strs = try_opt!(
2122 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2124 .collect::<Option<Vec<_>>>()
2127 // Account for sugary self.
2128 // FIXME: the comment for the self argument is dropped. This is blocked
2129 // on rust issue #27522.
2130 let min_args = explicit_self
2131 .and_then(|explicit_self| {
2132 rewrite_explicit_self(explicit_self, args, context)
2134 .map_or(1, |self_str| {
2135 arg_item_strs[0] = self_str;
2139 // Comments between args.
2140 let mut arg_items = Vec::new();
2142 arg_items.push(ListItem::from_str(""));
2145 // FIXME(#21): if there are no args, there might still be a comment, but
2146 // without spans for the comment or parens, there is no chance of
2147 // getting it right. You also don't get to put a comment on self, unless
2149 if args.len() >= min_args || variadic {
2150 let comment_span_start = if min_args == 2 {
2151 let second_arg_start = if arg_has_pattern(&args[1]) {
2156 let reduced_span = mk_sp(span.lo, second_arg_start);
2158 context.codemap.span_after_last(reduced_span, ",")
2163 enum ArgumentKind<'a> {
2164 Regular(&'a ast::Arg),
2168 let variadic_arg = if variadic {
2169 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2170 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2171 Some(ArgumentKind::Variadic(variadic_start))
2176 let more_items = itemize_list(
2178 args[min_args - 1..]
2180 .map(ArgumentKind::Regular)
2181 .chain(variadic_arg),
2184 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2185 ArgumentKind::Variadic(start) => start,
2188 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2189 ArgumentKind::Variadic(start) => start + BytePos(3),
2192 ArgumentKind::Regular(..) => None,
2193 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2199 arg_items.extend(more_items);
2202 let fits_in_one_line = !generics_str_contains_newline &&
2203 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2205 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2206 item.item = Some(arg);
2209 let last_line_ends_with_comment = arg_items
2212 .and_then(|item| item.post_comment.as_ref())
2213 .map_or(false, |s| s.trim().starts_with("//"));
2215 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2216 IndentStyle::Block if fits_in_one_line => {
2217 (indent.block_indent(context.config), SeparatorTactic::Never)
2219 IndentStyle::Block => (
2220 indent.block_indent(context.config),
2221 context.config.trailing_comma(),
2223 IndentStyle::Visual if last_line_ends_with_comment => {
2224 (arg_indent, context.config.trailing_comma())
2226 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2229 let tactic = definitive_tactic(
2231 context.config.fn_args_density().to_list_tactic(),
2234 let budget = match tactic {
2235 DefinitiveListTactic::Horizontal => one_line_budget,
2236 _ => multi_line_budget,
2239 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2241 let fmt = ListFormatting {
2244 trailing_separator: if variadic {
2245 SeparatorTactic::Never
2249 shape: Shape::legacy(budget, indent),
2250 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2251 config: context.config,
2254 write_list(&arg_items, &fmt)
2257 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2258 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2259 ident.node != symbol::keywords::Invalid.ident()
2265 fn compute_budgets_for_args(
2266 context: &RewriteContext,
2270 newline_brace: bool,
2272 ) -> Option<((usize, usize, Indent))> {
2274 "compute_budgets_for_args {} {:?}, {}, {}",
2280 // Try keeping everything on the same line.
2281 if !result.contains('\n') {
2282 // 2 = `()`, 3 = `() `, space is before ret_string.
2283 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2284 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2294 let one_line_budget = context
2297 .checked_sub(used_space)
2300 if one_line_budget > 0 {
2302 let multi_line_overhead =
2303 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2304 let multi_line_budget =
2305 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2310 indent + result.len() + 1,
2315 // Didn't work. we must force vertical layout and put args on a newline.
2316 let new_indent = indent.block_indent(context.config);
2317 // Account for `)` and possibly ` {`.
2318 let used_space = new_indent.width() + if ret_str_len == 0 { 1 } else { 3 };
2319 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2320 Some((0, max_space, new_indent))
2323 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2324 match config.fn_brace_style() {
2325 BraceStyle::AlwaysNextLine => true,
2326 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
2331 fn rewrite_generics(
2332 context: &RewriteContext,
2333 generics: &ast::Generics,
2336 ) -> Option<String> {
2337 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2338 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2339 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2340 rewrite_generics_inner(context, generics, g_shape, 0, span)
2344 fn rewrite_generics_inner(
2345 context: &RewriteContext,
2346 generics: &ast::Generics,
2348 one_line_width: usize,
2350 ) -> Option<String> {
2351 // FIXME: convert bounds to where clauses where they get too big or if
2352 // there is a where clause at all.
2353 let lifetimes: &[_] = &generics.lifetimes;
2354 let tys: &[_] = &generics.ty_params;
2355 if lifetimes.is_empty() && tys.is_empty() {
2356 return Some(String::new());
2359 // Strings for the generics.
2360 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2361 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2363 // Extract comments between generics.
2364 let lt_spans = lifetimes.iter().map(|l| {
2365 let hi = if l.bounds.is_empty() {
2368 l.bounds[l.bounds.len() - 1].span.hi
2370 mk_sp(l.lifetime.span.lo, hi)
2372 let ty_spans = tys.iter().map(|ty| ty.span());
2374 let items = itemize_list(
2376 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2380 // FIXME: don't clone
2381 |&(_, ref str)| str.clone(),
2382 context.codemap.span_after(span, "<"),
2385 format_generics_item_list(context, items, shape, one_line_width)
2388 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2389 match config.generics_indent() {
2390 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2391 IndentStyle::Block => {
2395 .block_indent(config.tab_spaces())
2396 .with_max_width(config)
2402 pub fn format_generics_item_list<I>(
2403 context: &RewriteContext,
2406 one_line_budget: usize,
2409 I: Iterator<Item = ListItem>,
2411 let item_vec = items.collect::<Vec<_>>();
2413 let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, one_line_budget);
2414 let fmt = ListFormatting {
2417 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2418 SeparatorTactic::Never
2420 context.config.trailing_comma()
2423 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2424 config: context.config,
2427 let list_str = try_opt!(write_list(&item_vec, &fmt));
2429 Some(wrap_generics_with_angle_brackets(
2436 pub fn wrap_generics_with_angle_brackets(
2437 context: &RewriteContext,
2439 list_offset: Indent,
2441 if context.config.generics_indent() == IndentStyle::Block &&
2442 (list_str.contains('\n') || list_str.ends_with(','))
2446 list_offset.to_string(context.config),
2449 .block_unindent(context.config)
2450 .to_string(context.config)
2452 } else if context.config.spaces_within_angle_brackets() {
2453 format!("< {} >", list_str)
2455 format!("<{}>", list_str)
2459 fn rewrite_trait_bounds(
2460 context: &RewriteContext,
2461 type_param_bounds: &ast::TyParamBounds,
2463 ) -> Option<String> {
2464 let bounds: &[_] = type_param_bounds;
2466 if bounds.is_empty() {
2467 return Some(String::new());
2469 let bound_str = try_opt!(
2472 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2473 .collect::<Option<Vec<_>>>()
2475 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2478 fn rewrite_where_clause_rfc_style(
2479 context: &RewriteContext,
2480 where_clause: &ast::WhereClause,
2483 suppress_comma: bool,
2484 // where clause can be kept on the current line.
2486 span_end: Option<BytePos>,
2488 span_end_before_where: BytePos,
2489 ) -> Option<String> {
2490 let block_shape = shape.block().with_max_width(context.config);
2492 let (span_before, span_after) =
2493 missing_span_before_after_where(context, span.hi, span_end_before_where, where_clause);
2494 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2501 let starting_newline = if snuggle && comment_before.is_empty() {
2504 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2507 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2508 // each clause on one line, trailing comma (except if suppress_comma)
2509 let span_start = where_clause.predicates[0].span().lo;
2510 // If we don't have the start of the next span, then use the end of the
2511 // predicates, but that means we miss comments.
2512 let len = where_clause.predicates.len();
2513 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2514 let span_end = span_end.unwrap_or(end_of_preds);
2515 let items = itemize_list(
2517 where_clause.predicates.iter(),
2519 |pred| pred.span().lo,
2520 |pred| pred.span().hi,
2521 |pred| pred.rewrite(context, block_shape),
2525 let comma_tactic = if suppress_comma {
2526 SeparatorTactic::Never
2528 context.config.trailing_comma()
2531 let fmt = ListFormatting {
2532 tactic: DefinitiveListTactic::Vertical,
2534 trailing_separator: comma_tactic,
2535 shape: clause_shape,
2536 ends_with_newline: true,
2537 config: context.config,
2539 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2541 let newline_before_where = if comment_before.is_empty() || comment_before.ends_with('\n') {
2544 "\n".to_owned() + &shape.indent.to_string(context.config)
2546 let newline_after_where = if comment_after.is_empty() {
2549 "\n".to_owned() + &clause_shape.indent.to_string(context.config)
2552 "{}{}{}where{}{}\n{}{}",
2555 newline_before_where,
2556 newline_after_where,
2558 clause_shape.indent.to_string(context.config),
2563 fn rewrite_where_clause(
2564 context: &RewriteContext,
2565 where_clause: &ast::WhereClause,
2566 brace_style: BraceStyle,
2570 suppress_comma: bool,
2572 span_end: Option<BytePos>,
2574 span_end_before_where: BytePos,
2575 ) -> Option<String> {
2576 if where_clause.predicates.is_empty() {
2577 return Some(String::new());
2580 if context.config.where_style() == Style::Rfc {
2581 return rewrite_where_clause_rfc_style(
2590 span_end_before_where,
2594 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2596 let offset = match context.config.where_pred_indent() {
2597 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2598 // 6 = "where ".len()
2599 IndentStyle::Visual => shape.indent + extra_indent + 6,
2601 // FIXME: if where_pred_indent != Visual, then the budgets below might
2602 // be out by a char or two.
2604 let budget = context.config.max_width() - offset.width();
2605 let span_start = where_clause.predicates[0].span().lo;
2606 // If we don't have the start of the next span, then use the end of the
2607 // predicates, but that means we miss comments.
2608 let len = where_clause.predicates.len();
2609 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2610 let span_end = span_end.unwrap_or(end_of_preds);
2611 let items = itemize_list(
2613 where_clause.predicates.iter(),
2615 |pred| pred.span().lo,
2616 |pred| pred.span().hi,
2617 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2621 let item_vec = items.collect::<Vec<_>>();
2622 // FIXME: we don't need to collect here if the where_layout isn't
2623 // HorizontalVertical.
2624 let tactic = definitive_tactic(&item_vec, context.config.where_layout(), budget);
2626 let mut comma_tactic = context.config.trailing_comma();
2627 // Kind of a hack because we don't usually have trailing commas in where clauses.
2628 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2629 comma_tactic = SeparatorTactic::Never;
2632 let fmt = ListFormatting {
2635 trailing_separator: comma_tactic,
2636 shape: Shape::legacy(budget, offset),
2637 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2638 config: context.config,
2640 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2642 let end_length = if terminator == "{" {
2643 // If the brace is on the next line we don't need to count it otherwise it needs two
2646 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2647 BraceStyle::PreferSameLine => 2,
2649 } else if terminator == "=" {
2654 if density == Density::Tall || preds_str.contains('\n') ||
2655 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2659 (shape.indent + extra_indent).to_string(context.config),
2663 Some(format!(" where {}", preds_str))
2667 fn missing_span_before_after_where(
2668 context: &RewriteContext,
2670 before_item_span_end: BytePos,
2671 where_clause: &ast::WhereClause,
2673 let snippet = context.snippet(mk_sp(before_item_span_end, item_end));
2674 let pos_before_where =
2675 before_item_span_end + BytePos(snippet.find_uncommented("where").unwrap() as u32);
2676 let missing_span_before = mk_sp(before_item_span_end, pos_before_where);
2678 let pos_after_where = pos_before_where + BytePos(5);
2679 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2680 (missing_span_before, missing_span_after)
2683 fn rewrite_missing_comment_in_where(
2684 context: &RewriteContext,
2687 ) -> Option<String> {
2688 let comment = comment.trim();
2689 if comment.is_empty() {
2692 rewrite_comment(comment, false, shape, context.config)
2696 fn rewrite_comments_before_after_where(
2697 context: &RewriteContext,
2698 span_before_where: Span,
2699 span_after_where: Span,
2701 ) -> Option<(String, String)> {
2702 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2704 &context.snippet(span_before_where),
2707 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2709 &context.snippet(span_after_where),
2710 shape.block_indent(context.config.tab_spaces()),
2712 Some((before_comment, after_comment))
2715 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2716 format!("{}{}{}", format_visibility(vis), item_name, ident)
2720 context: &RewriteContext,
2721 generics: &ast::Generics,
2724 brace_style: BraceStyle,
2725 force_same_line_brace: bool,
2729 ) -> Option<String> {
2730 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2731 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2733 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2734 let budget = try_opt!(
2738 .checked_sub(last_line_width(&result))
2740 let where_clause_str = try_opt!(rewrite_where_clause(
2742 &generics.where_clause,
2744 Shape::legacy(budget, offset.block_only()),
2748 trimmed_last_line_width(&result) == 1,
2753 result.push_str(&where_clause_str);
2754 let same_line_brace = force_same_line_brace ||
2755 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1);
2756 if !same_line_brace &&
2757 (brace_style == BraceStyle::SameLineWhere ||
2758 brace_style == BraceStyle::AlwaysNextLine)
2761 result.push_str(&offset.block_only().to_string(context.config));
2765 result.push_str(opener);
2767 if force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2768 brace_style != BraceStyle::AlwaysNextLine
2773 result.push_str(&offset.block_only().to_string(context.config));
2775 result.push_str(opener);