1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
15 use syntax::{abi, ast, ptr, symbol};
16 use syntax::ast::ImplItem;
17 use syntax::codemap::{BytePos, Span};
19 use {Indent, Shape, Spanned};
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{contains_comment, recover_comment_removed, rewrite_comment, FindUncommented};
22 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
23 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
24 rewrite_call_inner, ExprType};
25 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
26 ListItem, ListTactic, Separator, SeparatorTactic};
27 use rewrite::{Rewrite, RewriteContext};
28 use types::join_bounds;
29 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
30 format_constness, format_defaultness, format_mutability, format_unsafety,
31 format_visibility, last_line_used_width, last_line_width, mk_sp, semicolon_for_expr,
32 stmt_expr, trim_newlines, trimmed_last_line_width, wrap_str};
33 use vertical::rewrite_with_alignment;
34 use visitor::FmtVisitor;
36 fn type_annotation_separator(config: &Config) -> &str {
38 config.space_before_type_annotation(),
39 config.space_after_type_annotation_colon(),
44 // Statements of the form
45 // let pat: ty = init;
46 impl Rewrite for ast::Local {
47 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
49 "Local::rewrite {:?} {} {:?}",
55 skip_out_of_file_lines_range!(context, self.span);
57 let mut result = "let ".to_owned();
60 let pat_shape = try_opt!(shape.offset_left(4));
62 let pat_shape = try_opt!(pat_shape.sub_width(1));
63 let pat_str = try_opt!(self.pat.rewrite(&context, pat_shape));
64 result.push_str(&pat_str);
66 // String that is placed within the assignment pattern and expression.
68 let mut infix = String::new();
70 if let Some(ref ty) = self.ty {
71 let separator = type_annotation_separator(context.config);
72 let indent = shape.indent + last_line_width(&result) + separator.len();
74 let budget = try_opt!(shape.width.checked_sub(indent.width() + 1));
75 let rewrite = try_opt!(ty.rewrite(context, Shape::legacy(budget, indent)));
77 infix.push_str(separator);
78 infix.push_str(&rewrite);
81 if self.init.is_some() {
88 result.push_str(&infix);
90 if let Some(ref ex) = self.init {
91 // 1 = trailing semicolon;
92 let nested_shape = try_opt!(shape.sub_width(1));
94 result = try_opt!(rewrite_assign_rhs(&context, result, ex, nested_shape));
102 // TODO convert to using rewrite style rather than visitor
103 // TODO format modules in this style
106 keyword: &'static str,
108 vis: Option<&'a ast::Visibility>,
109 body: Vec<BodyElement<'a>>,
114 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
115 let abi = if fm.abi == abi::Abi::C && !config.force_explicit_abi() {
118 format!("extern {}", fm.abi)
126 .map(|i| BodyElement::ForeignItem(i))
133 enum BodyElement<'a> {
134 // Stmt(&'a ast::Stmt),
135 // Field(&'a ast::Field),
136 // Variant(&'a ast::Variant),
137 // Item(&'a ast::Item),
138 ForeignItem(&'a ast::ForeignItem),
141 impl<'a> FmtVisitor<'a> {
142 fn format_item(&mut self, item: Item) {
143 self.buffer.push_str(&item.abi);
144 self.buffer.push_str(" ");
146 let snippet = self.snippet(item.span);
147 let brace_pos = snippet.find_uncommented("{").unwrap();
149 self.buffer.push_str("{");
150 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
151 // FIXME: this skips comments between the extern keyword and the opening
153 self.last_pos = item.span.lo + BytePos(brace_pos as u32 + 1);
154 self.block_indent = self.block_indent.block_indent(self.config);
156 if item.body.is_empty() {
157 self.format_missing_no_indent(item.span.hi - BytePos(1));
158 self.block_indent = self.block_indent.block_unindent(self.config);
161 .push_str(&self.block_indent.to_string(self.config));
163 for item in &item.body {
164 self.format_body_element(item);
167 self.block_indent = self.block_indent.block_unindent(self.config);
168 self.format_missing_with_indent(item.span.hi - BytePos(1));
172 self.buffer.push_str("}");
173 self.last_pos = item.span.hi;
176 fn format_body_element(&mut self, element: &BodyElement) {
178 BodyElement::ForeignItem(ref item) => self.format_foreign_item(item),
182 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
183 let item = Item::from_foreign_mod(fm, span, self.config);
184 self.format_item(item);
187 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
188 self.format_missing_with_indent(item.span.lo);
189 // Drop semicolon or it will be interpreted as comment.
190 // FIXME: this may be a faulty span from libsyntax.
191 let span = mk_sp(item.span.lo, item.span.hi - BytePos(1));
194 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
195 let indent = self.block_indent;
196 let rewrite = rewrite_fn_base(
202 ast::Unsafety::Normal,
203 ast::Constness::NotConst,
204 ast::Defaultness::Final,
205 // These are not actually rust functions,
206 // but we format them as such.
216 Some((new_fn, _)) => {
217 self.buffer.push_str(&new_fn);
218 self.buffer.push_str(";");
220 None => self.format_missing(item.span.hi),
223 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
224 // FIXME(#21): we're dropping potential comments in between the
225 // function keywords here.
226 let vis = format_visibility(&item.vis);
227 let mut_str = if is_mutable { "mut " } else { "" };
228 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
229 let offset = self.block_indent + prefix.len();
231 let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
232 let rewrite = ty.rewrite(&self.get_context(), shape);
236 self.buffer.push_str(&prefix);
237 self.buffer.push_str(&result);
238 self.buffer.push_str(";");
240 None => self.format_missing(item.span.hi),
245 self.last_pos = item.span.hi;
253 generics: &ast::Generics,
254 unsafety: ast::Unsafety,
255 constness: ast::Constness,
256 defaultness: ast::Defaultness,
258 vis: &ast::Visibility,
261 ) -> Option<String> {
262 let mut newline_brace = newline_for_brace(self.config, &generics.where_clause);
263 let context = self.get_context();
265 let block_snippet = self.snippet(mk_sp(block.span.lo, block.span.hi));
266 let has_body = !block_snippet[1..block_snippet.len() - 1].trim().is_empty() ||
267 !context.config.fn_empty_single_line();
269 let (mut result, force_newline_brace) = try_opt!(rewrite_fn_base(
286 if force_newline_brace {
287 newline_brace = true;
288 } else if self.config.fn_brace_style() != BraceStyle::AlwaysNextLine &&
289 !result.contains('\n')
291 newline_brace = false;
294 // Prepare for the function body by possibly adding a newline and
296 // FIXME we'll miss anything between the end of the signature and the
297 // start of the body, but we need more spans from the compiler to solve
301 result.push_str(&indent.to_string(self.config));
306 self.single_line_fn(&result, block).or_else(|| Some(result))
309 pub fn rewrite_required_fn(
313 sig: &ast::MethodSig,
315 ) -> Option<String> {
316 // Drop semicolon or it will be interpreted as comment.
317 let span = mk_sp(span.lo, span.hi - BytePos(1));
318 let context = self.get_context();
320 let (mut result, _) = try_opt!(rewrite_fn_base(
328 ast::Defaultness::Final,
330 &ast::Visibility::Inherited,
337 // Re-attach semicolon
343 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
344 if fn_str.contains('\n') {
348 let codemap = self.get_context().codemap;
350 if self.config.fn_empty_single_line() && is_empty_block(block, codemap) &&
351 self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
353 return Some(format!("{}{{}}", fn_str));
356 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
358 if let Some(ref stmt) = block.stmts.first() {
359 match stmt_expr(stmt) {
361 let suffix = if semicolon_for_expr(&self.get_context(), e) {
371 Shape::indented(self.block_indent, self.config),
372 ).map(|s| s + suffix)
373 .or_else(|| Some(self.snippet(e.span)))
375 None => stmt.rewrite(
377 Shape::indented(self.block_indent, self.config),
385 if let Some(res) = rewrite {
386 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
387 if !res.contains('\n') && width <= self.config.max_width() {
388 return Some(format!("{}{{ {} }}", fn_str, res));
399 vis: &ast::Visibility,
400 enum_def: &ast::EnumDef,
401 generics: &ast::Generics,
404 let enum_header = format_header("enum ", ident, vis);
405 self.buffer.push_str(&enum_header);
407 let enum_snippet = self.snippet(span);
408 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
409 let body_start = span.lo + BytePos(brace_pos as u32 + 1);
410 let generics_str = format_generics(
415 self.config.item_brace_style(),
416 enum_def.variants.is_empty(),
418 mk_sp(span.lo, body_start),
419 last_line_width(&enum_header),
421 self.buffer.push_str(&generics_str);
423 self.last_pos = body_start;
425 self.block_indent = self.block_indent.block_indent(self.config);
426 let variant_list = self.format_variant_list(enum_def, body_start, span.hi - BytePos(1));
428 Some(ref body_str) => self.buffer.push_str(body_str),
429 None => if contains_comment(&enum_snippet[brace_pos..]) {
430 self.format_missing_no_indent(span.hi - BytePos(1))
432 self.format_missing(span.hi - BytePos(1))
435 self.block_indent = self.block_indent.block_unindent(self.config);
437 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
439 .push_str(&self.block_indent.to_string(self.config));
441 self.buffer.push_str("}");
442 self.last_pos = span.hi;
445 // Format the body of an enum definition
446 fn format_variant_list(
448 enum_def: &ast::EnumDef,
451 ) -> Option<String> {
452 if enum_def.variants.is_empty() {
455 let mut result = String::with_capacity(1024);
457 let indentation = self.block_indent.to_string(self.config);
458 result.push_str(&indentation);
460 let items = itemize_list(
462 enum_def.variants.iter(),
464 |f| if !f.node.attrs.is_empty() {
465 f.node.attrs[0].span.lo
470 |f| self.format_variant(f),
475 let shape = Shape::indented(self.block_indent, self.config)
478 let fmt = ListFormatting {
479 tactic: DefinitiveListTactic::Vertical,
481 trailing_separator: self.config.trailing_comma(),
483 ends_with_newline: true,
484 preserve_newline: true,
488 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
489 result.push_str(&list);
494 // Variant of an enum.
495 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
496 if contains_skip(&field.node.attrs) {
497 let lo = field.node.attrs[0].span.lo;
498 let span = mk_sp(lo, field.span.hi);
499 return Some(self.snippet(span));
502 let context = self.get_context();
503 let indent = self.block_indent;
504 let mut result = try_opt!(
508 .rewrite(&context, Shape::indented(indent, self.config))
510 if !result.is_empty() {
512 width: context.config.max_width(),
513 indent: self.block_indent,
514 offset: self.block_indent.alignment,
516 let missing_comment = rewrite_missing_comment_on_field(
519 field.node.attrs[field.node.attrs.len() - 1].span.hi,
522 ).unwrap_or(String::new());
523 result.push_str(&missing_comment);
526 let variant_body = match field.node.data {
527 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
528 // FIXME: Should limit the width, as we have a trailing comma
533 &ast::Visibility::Inherited,
538 Some(self.config.struct_variant_width()),
541 ast::VariantData::Unit(..) => {
542 let tag = if let Some(ref expr) = field.node.disr_expr {
543 format!("{} = {}", field.node.name, self.snippet(expr.span))
545 field.node.name.to_string()
550 self.config.max_width(),
551 Shape::indented(indent, self.config),
556 if let Some(variant_str) = variant_body {
557 result.push_str(&variant_str);
566 context: &RewriteContext,
569 where_span_end: Option<BytePos>,
570 ) -> Option<String> {
571 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
572 let mut result = String::new();
573 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
574 result.push_str(&ref_and_type);
576 let where_budget = if result.contains('\n') {
577 context.config.max_width()
582 .checked_sub(last_line_width(&result))
585 let where_clause_str = try_opt!(rewrite_where_clause(
587 &generics.where_clause,
588 context.config.item_brace_style(),
589 Shape::legacy(where_budget, offset.block_only()),
590 context.config.where_density(),
593 last_line_width(&ref_and_type) == 1,
599 if try_opt!(is_impl_single_line(
606 result.push_str(&where_clause_str);
607 if where_clause_str.contains('\n') {
608 let white_space = offset.to_string(context.config);
609 result.push_str(&format!("\n{}{{\n{}}}", &white_space, &white_space));
611 result.push_str(" {}");
616 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
618 let width = offset.block_indent + context.config.tab_spaces() - 1;
619 let where_indent = Indent::new(0, width);
620 result.push_str(&where_indent.to_string(context.config));
622 result.push_str(&where_clause_str);
624 match context.config.item_brace_style() {
625 BraceStyle::AlwaysNextLine => {
627 result.push_str(&offset.to_string(context.config));
629 BraceStyle::PreferSameLine => result.push(' '),
630 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
632 result.push_str(&offset.to_string(context.config));
640 let snippet = context.snippet(item.span);
641 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
643 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
644 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
645 visitor.block_indent = offset.block_only().block_indent(context.config);
646 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
648 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
650 visitor.visit_impl_item(item);
653 visitor.format_missing(item.span.hi - BytePos(1));
655 let inner_indent_str = visitor.block_indent.to_string(context.config);
656 let outer_indent_str = offset.block_only().to_string(context.config);
659 result.push_str(&inner_indent_str);
660 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
662 result.push_str(&outer_indent_str);
665 if result.chars().last().unwrap() == '{' {
667 result.push_str(&offset.to_string(context.config));
677 fn is_impl_single_line(
678 context: &RewriteContext,
681 where_clause_str: &str,
684 let snippet = context.snippet(item.span);
685 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
688 context.config.impl_empty_single_line() && items.is_empty() &&
689 result.len() + where_clause_str.len() <= context.config.max_width() &&
690 !contains_comment(&snippet[open_pos..]),
694 fn format_impl_ref_and_type(
695 context: &RewriteContext,
698 ) -> Option<String> {
699 if let ast::ItemKind::Impl(
709 let mut result = String::new();
711 result.push_str(&format_visibility(&item.vis));
712 result.push_str(&format_defaultness(defaultness));
713 result.push_str(format_unsafety(unsafety));
714 result.push_str("impl");
716 let lo = context.codemap.span_after(item.span, "impl");
717 let hi = match *trait_ref {
718 Some(ref tr) => tr.path.span.lo,
719 None => self_ty.span.lo,
721 let shape = try_opt!(generics_shape_from_config(
723 Shape::indented(offset + last_line_width(&result), context.config),
726 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
727 let generics_str = try_opt!(rewrite_generics_inner(
735 let polarity_str = if polarity == ast::ImplPolarity::Negative {
741 if let Some(ref trait_ref) = *trait_ref {
742 let result_len = result.len();
743 if let Some(trait_ref_str) = rewrite_trait_ref(
752 result.push_str(&trait_ref_str);
754 let generics_str = try_opt!(rewrite_generics_inner(
761 result.push_str(&try_opt!(rewrite_trait_ref(
772 result.push_str(&generics_str);
775 // Try to put the self type in a single line.
777 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
778 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
779 // If there is no where clause adapt budget for type formatting to take space and curly
780 // brace into account.
781 match context.config.item_brace_style() {
782 BraceStyle::AlwaysNextLine => 0,
788 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
789 // 1 = space before the type.
793 .checked_sub(used_space + 1)
795 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
796 if !self_ty_str.contains('\n') {
797 if trait_ref.is_some() {
798 result.push_str(" for ");
802 result.push_str(&self_ty_str);
807 // Couldn't fit the self type on a single line, put it on a new line.
809 // Add indentation of one additional tab.
810 let new_line_offset = offset.block_indent(context.config);
811 result.push_str(&new_line_offset.to_string(context.config));
812 if trait_ref.is_some() {
813 result.push_str("for ");
815 let budget = context.config.max_width() - last_line_width(&result);
816 let type_offset = match context.config.where_style() {
817 Style::Legacy => new_line_offset + trait_ref_overhead,
818 Style::Rfc => new_line_offset,
820 result.push_str(&*try_opt!(
821 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
829 fn rewrite_trait_ref(
830 context: &RewriteContext,
831 trait_ref: &ast::TraitRef,
837 ) -> Option<String> {
838 // 1 = space between generics and trait_ref
839 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
840 let shape = Shape::indented(offset + used_space, context.config);
841 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
842 if !(retry && trait_ref_str.contains('\n')) {
851 // We could not make enough space for trait_ref, so put it on new line.
853 let offset = offset.block_indent(context.config);
854 let shape = Shape::indented(offset, context.config);
855 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
859 &offset.to_string(context.config),
868 pub fn format_struct(
869 context: &RewriteContext,
872 vis: &ast::Visibility,
873 struct_def: &ast::VariantData,
874 generics: Option<&ast::Generics>,
877 one_line_width: Option<usize>,
878 ) -> Option<String> {
880 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
881 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
891 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
905 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
906 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
909 let mut result = String::new();
910 let header = format!(
912 format_visibility(&item.vis),
913 format_unsafety(unsafety),
917 result.push_str(&header);
919 let body_lo = context.codemap.span_after(item.span, "{");
921 let shape = Shape::indented(offset + last_line_width(&result), context.config);
922 let generics_str = try_opt!(rewrite_generics(
926 mk_sp(item.span.lo, body_lo),
928 result.push_str(&generics_str);
930 let trait_bound_str = try_opt!(rewrite_trait_bounds(
933 Shape::indented(offset, context.config),
935 // If the trait, generics, and trait bound cannot fit on the same line,
936 // put the trait bounds on an indented new line
937 if offset.width() + last_line_width(&result) + trait_bound_str.len() >
938 context.config.comment_width()
941 let trait_indent = offset.block_only().block_indent(context.config);
942 result.push_str(&trait_indent.to_string(context.config));
944 result.push_str(&trait_bound_str);
946 let has_body = !trait_items.is_empty();
948 let where_density = if (context.config.where_density() == Density::Compressed &&
949 (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block)) ||
950 (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty()) ||
951 (context.config.where_density() == Density::CompressedIfEmpty && !has_body &&
952 !result.contains('\n'))
959 let where_budget = try_opt!(
963 .checked_sub(last_line_width(&result))
965 let pos_before_where = if type_param_bounds.is_empty() {
966 if generics.where_clause.predicates.is_empty() {
967 // We do not use this, so it does not matter
970 let snippet = context.snippet(item.span);
971 let where_pos = snippet.find_uncommented("where");
972 item.span.lo + where_pos.map_or(BytePos(0), |p| BytePos(p as u32))
975 type_param_bounds[type_param_bounds.len() - 1].span().hi
977 let where_clause_str = try_opt!(rewrite_where_clause(
979 &generics.where_clause,
980 context.config.item_brace_style(),
981 Shape::legacy(where_budget, offset.block_only()),
985 trait_bound_str.is_empty() && last_line_width(&generics_str) == 1,
990 // If the where clause cannot fit on the same line,
991 // put the where clause on a new line
992 if !where_clause_str.contains('\n') &&
993 last_line_width(&result) + where_clause_str.len() + offset.width() >
994 context.config.comment_width()
997 let width = offset.block_indent + context.config.tab_spaces() - 1;
998 let where_indent = Indent::new(0, width);
999 result.push_str(&where_indent.to_string(context.config));
1001 result.push_str(&where_clause_str);
1003 match context.config.item_brace_style() {
1004 BraceStyle::AlwaysNextLine => {
1006 result.push_str(&offset.to_string(context.config));
1008 BraceStyle::PreferSameLine => result.push(' '),
1009 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() &&
1010 (!trait_items.is_empty() || result.contains('\n'))
1013 result.push_str(&offset.to_string(context.config));
1020 let snippet = context.snippet(item.span);
1021 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1023 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1024 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1025 visitor.block_indent = offset.block_only().block_indent(context.config);
1026 visitor.last_pos = item.span.lo + BytePos(open_pos as u32);
1028 for item in trait_items {
1029 visitor.visit_trait_item(item);
1032 visitor.format_missing(item.span.hi - BytePos(1));
1034 let inner_indent_str = visitor.block_indent.to_string(context.config);
1035 let outer_indent_str = offset.block_only().to_string(context.config);
1038 result.push_str(&inner_indent_str);
1039 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1041 result.push_str(&outer_indent_str);
1042 } else if result.contains('\n') {
1053 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1054 format!("{};", format_header(item_name, ident, vis))
1057 pub fn format_struct_struct(
1058 context: &RewriteContext,
1061 vis: &ast::Visibility,
1062 fields: &[ast::StructField],
1063 generics: Option<&ast::Generics>,
1066 one_line_width: Option<usize>,
1067 ) -> Option<String> {
1068 let mut result = String::with_capacity(1024);
1070 let header_str = format_header(item_name, ident, vis);
1071 result.push_str(&header_str);
1073 let body_lo = context.codemap.span_after(span, "{");
1075 let generics_str = match generics {
1076 Some(g) => try_opt!(format_generics(
1081 context.config.item_brace_style(),
1084 mk_sp(span.lo, body_lo),
1085 last_line_width(&result),
1088 // 3 = ` {}`, 2 = ` {`.
1089 let overhead = if fields.is_empty() { 3 } else { 2 };
1090 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine &&
1091 !fields.is_empty()) ||
1095 .checked_sub(result.len())
1096 .unwrap_or(0) < overhead
1098 format!("\n{}{{", offset.block_only().to_string(context.config))
1105 let overhead = if fields.is_empty() { 1 } else { 0 };
1106 let max_len = context
1109 .checked_sub(offset.width())
1111 if !generics_str.contains('\n') && result.len() + generics_str.len() + overhead > max_len {
1113 result.push_str(&offset.to_string(context.config));
1114 result.push_str(&generics_str.trim_left());
1116 result.push_str(&generics_str);
1119 if fields.is_empty() {
1120 let snippet = context.snippet(mk_sp(body_lo, span.hi - BytePos(1)));
1121 if snippet.trim().is_empty() {
1123 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1125 result.push_str(&snippet.trim_right());
1127 result.push_str(&offset.to_string(context.config));
1129 result.push_str(&snippet);
1132 return Some(result);
1136 let one_line_budget = context
1139 .checked_sub(result.len() + 3 + offset.width())
1141 let one_line_budget =
1142 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1144 let items_str = try_opt!(rewrite_with_alignment(
1147 Shape::indented(offset, context.config),
1148 mk_sp(body_lo, span.hi),
1152 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1153 Some(format!("{} {} }}", result, items_str))
1159 .block_indent(context.config)
1160 .to_string(context.config),
1162 offset.to_string(context.config)
1167 fn format_tuple_struct(
1168 context: &RewriteContext,
1171 vis: &ast::Visibility,
1172 fields: &[ast::StructField],
1173 generics: Option<&ast::Generics>,
1176 ) -> Option<String> {
1177 let mut result = String::with_capacity(1024);
1179 let header_str = format_header(item_name, ident, vis);
1180 result.push_str(&header_str);
1182 let body_lo = if fields.is_empty() {
1183 context.codemap.span_after(span, "(")
1187 let body_hi = if fields.is_empty() {
1188 context.codemap.span_after(span, ")")
1190 // This is a dirty hack to work around a missing `)` from the span of the last field.
1191 let last_arg_span = fields[fields.len() - 1].span;
1192 if context.snippet(last_arg_span).ends_with(")") {
1197 .span_after(mk_sp(last_arg_span.hi, span.hi), ")")
1201 let where_clause_str = match generics {
1203 let budget = context.budget(last_line_width(&header_str));
1204 let shape = Shape::legacy(budget, offset);
1205 let g_span = mk_sp(span.lo, body_lo);
1206 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1207 result.push_str(&generics_str);
1209 let where_budget = context.budget(last_line_width(&result));
1210 try_opt!(rewrite_where_clause(
1212 &generics.where_clause,
1213 context.config.item_brace_style(),
1214 Shape::legacy(where_budget, offset.block_only()),
1215 Density::Compressed,
1224 None => "".to_owned(),
1227 if fields.is_empty() {
1229 let used_width = last_line_used_width(&result, offset.width()) + 3;
1230 if used_width > context.config.max_width() {
1232 result.push_str(&offset
1233 .block_indent(context.config)
1234 .to_string(context.config))
1237 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1238 if snippet.is_empty() {
1240 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1241 result.push_str(&snippet.trim_right());
1243 result.push_str(&offset.to_string(context.config));
1245 result.push_str(&snippet);
1250 let body = try_opt!(
1254 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1256 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1257 context.config.fn_call_width(),
1261 result.push_str(&body);
1264 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') &&
1265 (result.contains('\n') ||
1266 offset.block_indent + result.len() + where_clause_str.len() + 1 >
1267 context.config.max_width())
1269 // We need to put the where clause on a new line, but we didn't
1270 // know that earlier, so the where clause will not be indented properly.
1272 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1273 .to_string(context.config));
1275 result.push_str(&where_clause_str);
1280 pub fn rewrite_type_alias(
1281 context: &RewriteContext,
1285 generics: &ast::Generics,
1286 vis: &ast::Visibility,
1288 ) -> Option<String> {
1289 let mut result = String::new();
1291 result.push_str(&format_visibility(vis));
1292 result.push_str("type ");
1293 result.push_str(&ident.to_string());
1296 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1297 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
1298 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1299 result.push_str(&generics_str);
1301 let where_budget = try_opt!(
1305 .checked_sub(last_line_width(&result))
1307 let where_clause_str = try_opt!(rewrite_where_clause(
1309 &generics.where_clause,
1310 context.config.item_brace_style(),
1311 Shape::legacy(where_budget, indent),
1312 context.config.where_density(),
1320 result.push_str(&where_clause_str);
1321 result.push_str(" = ");
1323 let line_width = last_line_width(&result);
1324 // This checked_sub may fail as the extra space after '=' is not taken into account
1325 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1326 let budget = context
1329 .checked_sub(indent.width() + line_width + ";".len())
1331 let type_indent = indent + line_width;
1332 // Try to fit the type on the same line
1333 let ty_str = try_opt!(
1334 ty.rewrite(context, Shape::legacy(budget, type_indent))
1336 // The line was too short, try to put the type on the next line
1338 // Remove the space after '='
1340 let type_indent = indent.block_indent(context.config);
1342 result.push_str(&type_indent.to_string(context.config));
1343 let budget = try_opt!(
1347 .checked_sub(type_indent.width() + ";".len())
1349 ty.rewrite(context, Shape::legacy(budget, type_indent))
1352 result.push_str(&ty_str);
1353 result.push_str(";");
1357 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1359 if config.space_before_type_annotation() {
1364 if config.space_after_type_annotation_colon() {
1372 fn rewrite_missing_comment_on_field(
1373 context: &RewriteContext,
1377 result: &mut String,
1378 ) -> Option<String> {
1379 let possibly_comment_snippet = context.snippet(mk_sp(lo, hi));
1380 let newline_index = possibly_comment_snippet.find('\n');
1381 let comment_index = possibly_comment_snippet.find('/');
1382 match (newline_index, comment_index) {
1383 (Some(i), Some(j)) if i > j => result.push(' '),
1386 result.push_str(&shape.indent.to_string(context.config));
1389 let trimmed = possibly_comment_snippet.trim();
1390 if trimmed.is_empty() {
1393 rewrite_comment(trimmed, false, shape, context.config).map(|s| {
1394 format!("{}\n{}", s, shape.indent.to_string(context.config))
1399 pub fn rewrite_struct_field_prefix(
1400 context: &RewriteContext,
1401 field: &ast::StructField,
1403 ) -> Option<String> {
1404 let vis = format_visibility(&field.vis);
1405 let mut attr_str = try_opt!(
1408 .rewrite(context, Shape::indented(shape.indent, context.config))
1410 // Try format missing comments after attributes
1411 let missing_comment = if !field.attrs.is_empty() {
1412 rewrite_missing_comment_on_field(
1415 field.attrs[field.attrs.len() - 1].span.hi,
1418 ).unwrap_or(String::new())
1423 let type_annotation_spacing = type_annotation_spacing(context.config);
1424 Some(match field.ident {
1425 Some(name) => format!(
1431 type_annotation_spacing.0
1433 None => format!("{}{}{}", attr_str, missing_comment, vis),
1437 fn rewrite_struct_field_type(
1438 context: &RewriteContext,
1439 last_line_width: usize,
1440 field: &ast::StructField,
1443 ) -> Option<String> {
1444 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1447 .rewrite(context, ty_shape)
1448 .map(|ty| format!("{}{}", spacing, ty))
1451 impl Rewrite for ast::StructField {
1452 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1453 rewrite_struct_field(context, self, shape, 0)
1457 pub fn rewrite_struct_field(
1458 context: &RewriteContext,
1459 field: &ast::StructField,
1461 lhs_max_width: usize,
1462 ) -> Option<String> {
1463 if contains_skip(&field.attrs) {
1464 let span = context.snippet(mk_sp(field.attrs[0].span.lo, field.span.hi));
1465 return wrap_str(span, context.config.max_width(), shape);
1468 let type_annotation_spacing = type_annotation_spacing(context.config);
1469 let prefix = try_opt!(rewrite_struct_field_prefix(context, field, shape));
1471 // Try to put everything on a single line.
1472 let last_line_width = last_line_width(&prefix);
1473 let mut spacing = String::from(if field.ident.is_some() {
1474 type_annotation_spacing.1
1478 let lhs_offset = lhs_max_width.checked_sub(last_line_width).unwrap_or(0);
1479 for _ in 0..lhs_offset {
1482 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1483 if let Some(ref ty) = ty_rewritten {
1484 if !ty.contains('\n') {
1485 return Some(prefix + &ty);
1489 // We must use multiline.
1490 let type_offset = shape.indent.block_indent(context.config);
1491 let rewrite_type_in_next_line = || {
1494 .rewrite(context, Shape::indented(type_offset, context.config))
1497 match ty_rewritten {
1498 // If we start from the next line and type fits in a single line, then do so.
1499 Some(ref ty) => match rewrite_type_in_next_line() {
1500 Some(ref new_ty) if !new_ty.contains('\n') => Some(format!(
1503 type_offset.to_string(&context.config),
1506 _ => Some(prefix + &ty),
1509 let ty = try_opt!(rewrite_type_in_next_line());
1513 type_offset.to_string(&context.config),
1520 pub fn rewrite_static(
1522 vis: &ast::Visibility,
1525 mutability: ast::Mutability,
1526 expr_opt: Option<&ptr::P<ast::Expr>>,
1529 context: &RewriteContext,
1530 ) -> Option<String> {
1531 let colon = colon_spaces(
1532 context.config.space_before_type_annotation(),
1533 context.config.space_after_type_annotation_colon(),
1535 let prefix = format!(
1537 format_visibility(vis),
1539 format_mutability(mutability),
1544 let ty_str = try_opt!(ty.rewrite(
1547 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1551 if let Some(expr) = expr_opt {
1552 let lhs = format!("{}{} =", prefix, ty_str);
1554 let remaining_width = context.config.max_width() - offset.block_indent - 1;
1559 Shape::legacy(remaining_width, offset.block_only()),
1561 recover_comment_removed(res, span, context, Shape::indented(offset, context.config))
1563 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1565 Some(format!("{}{};", prefix, ty_str))
1569 pub fn rewrite_associated_type(
1571 ty_opt: Option<&ptr::P<ast::Ty>>,
1572 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1573 context: &RewriteContext,
1575 ) -> Option<String> {
1576 let prefix = format!("type {}", ident);
1578 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1579 let shape = Shape::indented(indent, context.config);
1580 let bounds: &[_] = ty_param_bounds;
1581 let bound_str = try_opt!(
1584 .map(|ty_bound| ty_bound.rewrite(context, shape))
1585 .collect::<Option<Vec<_>>>()
1587 if bounds.len() > 0 {
1588 format!(": {}", join_bounds(context, shape, &bound_str))
1596 if let Some(ty) = ty_opt {
1597 let ty_str = try_opt!(ty.rewrite(
1600 context.config.max_width() - indent.block_indent - prefix.len() - 2,
1601 indent.block_only(),
1604 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1606 Some(format!("{}{};", prefix, type_bounds_str))
1610 pub fn rewrite_associated_impl_type(
1612 defaultness: ast::Defaultness,
1613 ty_opt: Option<&ptr::P<ast::Ty>>,
1614 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1615 context: &RewriteContext,
1617 ) -> Option<String> {
1618 let result = try_opt!(rewrite_associated_type(
1621 ty_param_bounds_opt,
1627 ast::Defaultness::Default => Some(format!("default {}", result)),
1632 impl Rewrite for ast::FunctionRetTy {
1633 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1635 ast::FunctionRetTy::Default(_) => Some(String::new()),
1636 ast::FunctionRetTy::Ty(ref ty) => {
1637 let inner_width = try_opt!(shape.width.checked_sub(3));
1638 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1639 .map(|r| format!("-> {}", r))
1645 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1647 ast::TyKind::Infer => {
1648 let original = context.snippet(ty.span);
1655 impl Rewrite for ast::Arg {
1656 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1657 if is_named_arg(self) {
1658 let mut result = try_opt!(
1660 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1663 if !is_empty_infer(context, &*self.ty) {
1664 if context.config.space_before_type_annotation() {
1665 result.push_str(" ");
1667 result.push_str(":");
1668 if context.config.space_after_type_annotation_colon() {
1669 result.push_str(" ");
1671 let max_width = try_opt!(shape.width.checked_sub(result.len()));
1672 let ty_str = try_opt!(self.ty.rewrite(
1674 Shape::legacy(max_width, shape.indent + result.len()),
1676 result.push_str(&ty_str);
1681 self.ty.rewrite(context, shape)
1686 fn rewrite_explicit_self(
1687 explicit_self: &ast::ExplicitSelf,
1689 context: &RewriteContext,
1690 ) -> Option<String> {
1691 match explicit_self.node {
1692 ast::SelfKind::Region(lt, m) => {
1693 let mut_str = format_mutability(m);
1696 let lifetime_str = try_opt!(l.rewrite(
1698 Shape::legacy(context.config.max_width(), Indent::empty()),
1700 Some(format!("&{} {}self", lifetime_str, mut_str))
1702 None => Some(format!("&{}self", mut_str)),
1705 ast::SelfKind::Explicit(ref ty, _) => {
1706 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1708 let mutability = explicit_self_mutability(&args[0]);
1709 let type_str = try_opt!(ty.rewrite(
1711 Shape::legacy(context.config.max_width(), Indent::empty()),
1716 format_mutability(mutability),
1720 ast::SelfKind::Value(_) => {
1721 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1723 let mutability = explicit_self_mutability(&args[0]);
1725 Some(format!("{}self", format_mutability(mutability)))
1730 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1731 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1732 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1733 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1740 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1741 if is_named_arg(arg) {
1748 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1750 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi,
1751 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi,
1752 _ => arg.ty.span.hi,
1756 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1757 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1758 ident.node != symbol::keywords::Invalid.ident()
1764 // Return type is (result, force_new_line_for_brace)
1766 context: &RewriteContext,
1770 generics: &ast::Generics,
1771 unsafety: ast::Unsafety,
1772 constness: ast::Constness,
1773 defaultness: ast::Defaultness,
1775 vis: &ast::Visibility,
1777 newline_brace: bool,
1780 ) -> Option<(String, bool)> {
1781 let mut force_new_line_for_brace = false;
1783 let where_clause = &generics.where_clause;
1785 let mut result = String::with_capacity(1024);
1786 // Vis defaultness constness unsafety abi.
1787 result.push_str(&*format_visibility(vis));
1788 result.push_str(format_defaultness(defaultness));
1789 result.push_str(format_constness(constness));
1790 result.push_str(format_unsafety(unsafety));
1791 if abi != abi::Abi::Rust {
1792 result.push_str(&format_abi(abi, context.config.force_explicit_abi()));
1796 result.push_str("fn ");
1797 result.push_str(&ident.to_string());
1800 let overhead = if has_braces && !newline_brace {
1807 let used_width = last_line_used_width(&result, indent.width());
1808 let one_line_budget = context
1811 .checked_sub(used_width + overhead)
1814 width: one_line_budget,
1818 let g_span = mk_sp(span.lo, fd.output.span().lo);
1819 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1820 result.push_str(&generics_str);
1822 let snuggle_angle_bracket = generics_str
1825 .map_or(false, |l| l.trim_left().len() == 1);
1827 // Note that the width and indent don't really matter, we'll re-layout the
1828 // return type later anyway.
1829 let ret_str = try_opt!(
1831 .rewrite(&context, Shape::indented(indent, context.config))
1834 let multi_line_ret_str = ret_str.contains('\n');
1835 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1838 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1849 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1855 // Check if vertical layout was forced.
1856 if one_line_budget == 0 {
1857 if snuggle_angle_bracket {
1860 if context.config.fn_args_paren_newline() {
1862 result.push_str(&arg_indent.to_string(context.config));
1863 if context.config.fn_args_layout() == IndentStyle::Visual {
1864 arg_indent = arg_indent + 1; // extra space for `(`
1868 result.push_str("(");
1869 if context.config.fn_args_layout() == IndentStyle::Visual {
1871 result.push_str(&arg_indent.to_string(context.config));
1878 if context.config.spaces_within_parens() && fd.inputs.len() > 0 && result.ends_with('(') {
1882 // A conservative estimation, to goal is to be over all parens in generics
1883 let args_start = generics
1886 .map_or(span.lo, |tp| end_typaram(tp));
1887 let args_end = if fd.inputs.is_empty() {
1888 context.codemap.span_after(mk_sp(args_start, span.hi), ")")
1890 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi, span.hi);
1891 context.codemap.span_after(last_span, ")")
1893 let args_span = mk_sp(
1894 context.codemap.span_after(mk_sp(args_start, span.hi), "("),
1897 let arg_str = try_opt!(rewrite_args(
1900 fd.get_self().as_ref(),
1907 generics_str.contains('\n'),
1910 let put_args_in_block = match context.config.fn_args_layout() {
1911 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1913 } && !fd.inputs.is_empty();
1915 let mut args_last_line_contains_comment = false;
1916 if put_args_in_block {
1917 arg_indent = indent.block_indent(context.config);
1919 result.push_str(&arg_indent.to_string(context.config));
1920 result.push_str(&arg_str);
1922 result.push_str(&indent.to_string(context.config));
1925 result.push_str(&arg_str);
1926 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1927 // Put the closing brace on the next line if it overflows the max width.
1929 if fd.inputs.len() == 0 && used_width + 1 > context.config.max_width() {
1932 if context.config.spaces_within_parens() && fd.inputs.len() > 0 {
1935 // If the last line of args contains comment, we cannot put the closing paren
1936 // on the same line.
1940 .map_or(false, |last_line| last_line.contains("//"))
1942 args_last_line_contains_comment = true;
1944 result.push_str(&arg_indent.to_string(context.config));
1950 if let ast::FunctionRetTy::Ty(..) = fd.output {
1951 let ret_should_indent = match context.config.fn_args_layout() {
1952 // If our args are block layout then we surely must have space.
1953 IndentStyle::Block if put_args_in_block || fd.inputs.len() == 0 => false,
1954 _ if args_last_line_contains_comment => false,
1955 _ if result.contains('\n') || multi_line_ret_str => true,
1957 // If the return type would push over the max width, then put the return type on
1958 // a new line. With the +1 for the signature length an additional space between
1959 // the closing parenthesis of the argument and the arrow '->' is considered.
1960 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1962 // If there is no where clause, take into account the space after the return type
1964 if where_clause.predicates.is_empty() {
1968 sig_length > context.config.max_width()
1971 let ret_indent = if ret_should_indent {
1972 let indent = match context.config.fn_return_indent() {
1973 ReturnIndent::WithWhereClause => indent + 4,
1974 // Aligning with non-existent args looks silly.
1975 _ if arg_str.is_empty() => {
1976 force_new_line_for_brace = true;
1979 // FIXME: we might want to check that using the arg indent
1980 // doesn't blow our budget, and if it does, then fallback to
1981 // the where clause indent.
1986 result.push_str(&indent.to_string(context.config));
1990 Indent::new(indent.block_indent, last_line_width(&result))
1993 if multi_line_ret_str || ret_should_indent {
1994 // Now that we know the proper indent and width, we need to
1995 // re-layout the return type.
1996 let ret_str = try_opt!(
1998 .rewrite(context, Shape::indented(ret_indent, context.config))
2000 result.push_str(&ret_str);
2002 result.push_str(&ret_str);
2005 // Comment between return type and the end of the decl.
2006 let snippet_lo = fd.output.span().hi;
2007 if where_clause.predicates.is_empty() {
2008 let snippet_hi = span.hi;
2009 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2010 // Try to preserve the layout of the original snippet.
2011 let original_starts_with_newline = snippet
2013 .map_or(false, |i| snippet[i..].starts_with('\n'));
2014 let original_ends_with_newline = snippet
2015 .rfind(|c| c != ' ')
2016 .map_or(false, |i| snippet[i..].ends_with('\n'));
2017 let snippet = snippet.trim();
2018 if !snippet.is_empty() {
2019 result.push(if original_starts_with_newline {
2024 result.push_str(snippet);
2025 if original_ends_with_newline {
2026 force_new_line_for_brace = true;
2030 // FIXME it would be nice to catch comments between the return type
2031 // and the where clause, but we don't have a span for the where
2036 let should_compress_where = match context.config.where_density() {
2037 Density::Compressed => !result.contains('\n') || put_args_in_block,
2038 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2040 } || (put_args_in_block && ret_str.is_empty());
2042 let pos_before_where = match fd.output {
2043 ast::FunctionRetTy::Default(..) => args_span.hi,
2044 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi,
2046 if where_clause.predicates.len() == 1 && should_compress_where {
2047 let budget = try_opt!(
2051 .checked_sub(last_line_width(&result))
2053 if let Some(where_clause_str) = rewrite_where_clause(
2056 context.config.fn_brace_style(),
2057 Shape::legacy(budget, indent),
2058 Density::Compressed,
2061 put_args_in_block && ret_str.is_empty(),
2066 if !where_clause_str.contains('\n') {
2067 if last_line_width(&result) + where_clause_str.len() > context.config.max_width() {
2071 result.push_str(&where_clause_str);
2073 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2074 return Some((result, force_new_line_for_brace));
2079 let where_clause_str = try_opt!(rewrite_where_clause(
2082 context.config.fn_brace_style(),
2083 Shape::indented(indent, context.config),
2087 put_args_in_block && ret_str.is_empty(),
2093 result.push_str(&where_clause_str);
2095 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2096 return Some((result, force_new_line_for_brace));
2099 fn last_line_contains_single_line_comment(s: &str) -> bool {
2100 s.lines().last().map_or(false, |l| l.contains("//"))
2104 context: &RewriteContext,
2106 explicit_self: Option<&ast::ExplicitSelf>,
2107 one_line_budget: usize,
2108 multi_line_budget: usize,
2113 generics_str_contains_newline: bool,
2114 ) -> Option<String> {
2115 let mut arg_item_strs = try_opt!(
2118 arg.rewrite(&context, Shape::legacy(multi_line_budget, arg_indent))
2120 .collect::<Option<Vec<_>>>()
2123 // Account for sugary self.
2124 // FIXME: the comment for the self argument is dropped. This is blocked
2125 // on rust issue #27522.
2126 let min_args = explicit_self
2127 .and_then(|explicit_self| {
2128 rewrite_explicit_self(explicit_self, args, context)
2130 .map_or(1, |self_str| {
2131 arg_item_strs[0] = self_str;
2135 // Comments between args.
2136 let mut arg_items = Vec::new();
2138 arg_items.push(ListItem::from_str(""));
2141 // FIXME(#21): if there are no args, there might still be a comment, but
2142 // without spans for the comment or parens, there is no chance of
2143 // getting it right. You also don't get to put a comment on self, unless
2145 if args.len() >= min_args || variadic {
2146 let comment_span_start = if min_args == 2 {
2147 let second_arg_start = if arg_has_pattern(&args[1]) {
2152 let reduced_span = mk_sp(span.lo, second_arg_start);
2154 context.codemap.span_after_last(reduced_span, ",")
2159 enum ArgumentKind<'a> {
2160 Regular(&'a ast::Arg),
2164 let variadic_arg = if variadic {
2165 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
2166 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2167 Some(ArgumentKind::Variadic(variadic_start))
2172 let more_items = itemize_list(
2174 args[min_args - 1..]
2176 .map(ArgumentKind::Regular)
2177 .chain(variadic_arg),
2180 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2181 ArgumentKind::Variadic(start) => start,
2184 ArgumentKind::Regular(arg) => arg.ty.span.hi,
2185 ArgumentKind::Variadic(start) => start + BytePos(3),
2188 ArgumentKind::Regular(..) => None,
2189 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2195 arg_items.extend(more_items);
2198 let fits_in_one_line = !generics_str_contains_newline &&
2199 (arg_items.len() == 0 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2201 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2202 item.item = Some(arg);
2205 let last_line_ends_with_comment = arg_items
2208 .and_then(|item| item.post_comment.as_ref())
2209 .map_or(false, |s| s.trim().starts_with("//"));
2211 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2212 IndentStyle::Block if fits_in_one_line => {
2213 (indent.block_indent(context.config), SeparatorTactic::Never)
2215 IndentStyle::Block => (
2216 indent.block_indent(context.config),
2217 context.config.trailing_comma(),
2219 IndentStyle::Visual if last_line_ends_with_comment => {
2220 (arg_indent, context.config.trailing_comma())
2222 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2225 let tactic = definitive_tactic(
2227 context.config.fn_args_density().to_list_tactic(),
2231 let budget = match tactic {
2232 DefinitiveListTactic::Horizontal => one_line_budget,
2233 _ => multi_line_budget,
2236 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2238 let fmt = ListFormatting {
2241 trailing_separator: if variadic {
2242 SeparatorTactic::Never
2246 shape: Shape::legacy(budget, indent),
2247 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2248 preserve_newline: true,
2249 config: context.config,
2252 write_list(&arg_items, &fmt)
2255 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2256 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2257 ident.node != symbol::keywords::Invalid.ident()
2263 fn compute_budgets_for_args(
2264 context: &RewriteContext,
2268 newline_brace: bool,
2270 force_vertical_layout: bool,
2271 ) -> Option<((usize, usize, Indent))> {
2273 "compute_budgets_for_args {} {:?}, {}, {}",
2279 // Try keeping everything on the same line.
2280 if !result.contains('\n') && !force_vertical_layout {
2281 // 2 = `()`, 3 = `() `, space is before ret_string.
2282 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2283 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2293 let one_line_budget = context
2296 .checked_sub(used_space)
2299 if one_line_budget > 0 {
2301 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2302 IndentStyle::Block => {
2303 let indent = indent.block_indent(context.config);
2305 try_opt!(context.config.max_width().checked_sub(indent.width() + 1));
2308 IndentStyle::Visual => {
2309 let indent = indent + result.len() + 1;
2310 let multi_line_overhead =
2311 indent.width() + result.len() + if newline_brace { 2 } else { 4 };
2313 try_opt!(context.config.max_width().checked_sub(multi_line_overhead));
2318 return Some((one_line_budget, multi_line_budget, indent));
2322 // Didn't work. we must force vertical layout and put args on a newline.
2323 let new_indent = indent.block_indent(context.config);
2324 let used_space = match context.config.fn_args_layout() {
2326 IndentStyle::Block => new_indent.width() + 1,
2327 // Account for `)` and possibly ` {`.
2328 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2330 let max_space = try_opt!(context.config.max_width().checked_sub(used_space));
2331 Some((0, max_space, new_indent))
2334 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2335 match (config.fn_brace_style(), config.where_density()) {
2336 (BraceStyle::AlwaysNextLine, _) => true,
2337 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2338 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2339 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2344 fn rewrite_generics(
2345 context: &RewriteContext,
2346 generics: &ast::Generics,
2349 ) -> Option<String> {
2350 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2351 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2352 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2353 rewrite_generics_inner(context, generics, g_shape, 0, span)
2357 fn rewrite_generics_inner(
2358 context: &RewriteContext,
2359 generics: &ast::Generics,
2361 one_line_width: usize,
2363 ) -> Option<String> {
2364 // FIXME: convert bounds to where clauses where they get too big or if
2365 // there is a where clause at all.
2366 let lifetimes: &[_] = &generics.lifetimes;
2367 let tys: &[_] = &generics.ty_params;
2368 if lifetimes.is_empty() && tys.is_empty() {
2369 return Some(String::new());
2372 // Strings for the generics.
2373 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(context, shape));
2374 let ty_strs = tys.iter().map(|ty_param| ty_param.rewrite(context, shape));
2376 // Extract comments between generics.
2377 let lt_spans = lifetimes.iter().map(|l| {
2378 let hi = if l.bounds.is_empty() {
2381 l.bounds[l.bounds.len() - 1].span.hi
2383 mk_sp(l.lifetime.span.lo, hi)
2385 let ty_spans = tys.iter().map(|ty| ty.span());
2387 let items = itemize_list(
2389 lt_spans.chain(ty_spans).zip(lt_strs.chain(ty_strs)),
2393 // FIXME: don't clone
2394 |&(_, ref str)| str.clone(),
2395 context.codemap.span_after(span, "<"),
2398 format_generics_item_list(context, items, shape, one_line_width)
2401 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2402 match config.generics_indent() {
2403 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2404 IndentStyle::Block => {
2408 .block_indent(config.tab_spaces())
2409 .with_max_width(config)
2415 pub fn format_generics_item_list<I>(
2416 context: &RewriteContext,
2419 one_line_budget: usize,
2422 I: Iterator<Item = ListItem>,
2424 let item_vec = items.collect::<Vec<_>>();
2426 let tactic = definitive_tactic(
2428 ListTactic::HorizontalVertical,
2432 let fmt = ListFormatting {
2435 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2436 SeparatorTactic::Never
2438 context.config.trailing_comma()
2441 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2442 preserve_newline: true,
2443 config: context.config,
2446 let list_str = try_opt!(write_list(&item_vec, &fmt));
2448 Some(wrap_generics_with_angle_brackets(
2455 pub fn wrap_generics_with_angle_brackets(
2456 context: &RewriteContext,
2458 list_offset: Indent,
2460 if context.config.generics_indent() == IndentStyle::Block &&
2461 (list_str.contains('\n') || list_str.ends_with(','))
2465 list_offset.to_string(context.config),
2468 .block_unindent(context.config)
2469 .to_string(context.config)
2471 } else if context.config.spaces_within_angle_brackets() {
2472 format!("< {} >", list_str)
2474 format!("<{}>", list_str)
2478 fn rewrite_trait_bounds(
2479 context: &RewriteContext,
2480 type_param_bounds: &ast::TyParamBounds,
2482 ) -> Option<String> {
2483 let bounds: &[_] = type_param_bounds;
2485 if bounds.is_empty() {
2486 return Some(String::new());
2488 let bound_str = try_opt!(
2491 .map(|ty_bound| ty_bound.rewrite(&context, shape))
2492 .collect::<Option<Vec<_>>>()
2494 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2497 fn rewrite_where_clause_rfc_style(
2498 context: &RewriteContext,
2499 where_clause: &ast::WhereClause,
2502 suppress_comma: bool,
2503 // where clause can be kept on the current line.
2505 span_end: Option<BytePos>,
2507 span_end_before_where: BytePos,
2508 ) -> Option<String> {
2509 let block_shape = shape.block().with_max_width(context.config);
2511 let (span_before, span_after) =
2512 missing_span_before_after_where(context, span.hi, span_end_before_where, where_clause);
2513 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2520 let starting_newline = if snuggle && comment_before.is_empty() {
2523 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2526 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2527 // each clause on one line, trailing comma (except if suppress_comma)
2528 let span_start = where_clause.predicates[0].span().lo;
2529 // If we don't have the start of the next span, then use the end of the
2530 // predicates, but that means we miss comments.
2531 let len = where_clause.predicates.len();
2532 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2533 let span_end = span_end.unwrap_or(end_of_preds);
2534 let items = itemize_list(
2536 where_clause.predicates.iter(),
2538 |pred| pred.span().lo,
2539 |pred| pred.span().hi,
2540 |pred| pred.rewrite(context, block_shape),
2544 let comma_tactic = if suppress_comma {
2545 SeparatorTactic::Never
2547 context.config.trailing_comma()
2550 let fmt = ListFormatting {
2551 tactic: DefinitiveListTactic::Vertical,
2553 trailing_separator: comma_tactic,
2554 shape: clause_shape,
2555 ends_with_newline: true,
2556 preserve_newline: true,
2557 config: context.config,
2559 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2561 let newline_before_where = if comment_before.is_empty() || comment_before.ends_with('\n') {
2564 "\n".to_owned() + &shape.indent.to_string(context.config)
2566 let newline_after_where = if comment_after.is_empty() {
2569 "\n".to_owned() + &clause_shape.indent.to_string(context.config)
2572 "{}{}{}where{}{}\n{}{}",
2575 newline_before_where,
2576 newline_after_where,
2578 clause_shape.indent.to_string(context.config),
2583 fn rewrite_where_clause(
2584 context: &RewriteContext,
2585 where_clause: &ast::WhereClause,
2586 brace_style: BraceStyle,
2590 suppress_comma: bool,
2592 span_end: Option<BytePos>,
2594 span_end_before_where: BytePos,
2595 ) -> Option<String> {
2596 if where_clause.predicates.is_empty() {
2597 return Some(String::new());
2600 if context.config.where_style() == Style::Rfc {
2601 return rewrite_where_clause_rfc_style(
2610 span_end_before_where,
2614 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2616 let offset = match context.config.where_pred_indent() {
2617 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2618 // 6 = "where ".len()
2619 IndentStyle::Visual => shape.indent + extra_indent + 6,
2621 // FIXME: if where_pred_indent != Visual, then the budgets below might
2622 // be out by a char or two.
2624 let budget = context.config.max_width() - offset.width();
2625 let span_start = where_clause.predicates[0].span().lo;
2626 // If we don't have the start of the next span, then use the end of the
2627 // predicates, but that means we miss comments.
2628 let len = where_clause.predicates.len();
2629 let end_of_preds = where_clause.predicates[len - 1].span().hi;
2630 let span_end = span_end.unwrap_or(end_of_preds);
2631 let items = itemize_list(
2633 where_clause.predicates.iter(),
2635 |pred| pred.span().lo,
2636 |pred| pred.span().hi,
2637 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2641 let item_vec = items.collect::<Vec<_>>();
2642 // FIXME: we don't need to collect here if the where_layout isn't
2643 // HorizontalVertical.
2644 let tactic = definitive_tactic(
2646 context.config.where_layout(),
2651 let mut comma_tactic = context.config.trailing_comma();
2652 // Kind of a hack because we don't usually have trailing commas in where clauses.
2653 if comma_tactic == SeparatorTactic::Vertical || suppress_comma {
2654 comma_tactic = SeparatorTactic::Never;
2657 let fmt = ListFormatting {
2660 trailing_separator: comma_tactic,
2661 shape: Shape::legacy(budget, offset),
2662 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2663 preserve_newline: true,
2664 config: context.config,
2666 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2668 let end_length = if terminator == "{" {
2669 // If the brace is on the next line we don't need to count it otherwise it needs two
2672 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2673 BraceStyle::PreferSameLine => 2,
2675 } else if terminator == "=" {
2680 if density == Density::Tall || preds_str.contains('\n') ||
2681 shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2685 (shape.indent + extra_indent).to_string(context.config),
2689 Some(format!(" where {}", preds_str))
2693 fn missing_span_before_after_where(
2694 context: &RewriteContext,
2696 before_item_span_end: BytePos,
2697 where_clause: &ast::WhereClause,
2699 let snippet = context.snippet(mk_sp(before_item_span_end, item_end));
2700 let pos_before_where =
2701 before_item_span_end + BytePos(snippet.find_uncommented("where").unwrap() as u32);
2702 let missing_span_before = mk_sp(before_item_span_end, pos_before_where);
2704 let pos_after_where = pos_before_where + BytePos(5);
2705 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo);
2706 (missing_span_before, missing_span_after)
2709 fn rewrite_missing_comment_in_where(
2710 context: &RewriteContext,
2713 ) -> Option<String> {
2714 let comment = comment.trim();
2715 if comment.is_empty() {
2718 rewrite_comment(comment, false, shape, context.config)
2722 fn rewrite_comments_before_after_where(
2723 context: &RewriteContext,
2724 span_before_where: Span,
2725 span_after_where: Span,
2727 ) -> Option<(String, String)> {
2728 let before_comment = try_opt!(rewrite_missing_comment_in_where(
2730 &context.snippet(span_before_where),
2733 let after_comment = try_opt!(rewrite_missing_comment_in_where(
2735 &context.snippet(span_after_where),
2736 shape.block_indent(context.config.tab_spaces()),
2738 Some((before_comment, after_comment))
2741 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2742 format!("{}{}{}", format_visibility(vis), item_name, ident)
2746 context: &RewriteContext,
2747 generics: &ast::Generics,
2750 brace_style: BraceStyle,
2751 force_same_line_brace: bool,
2755 ) -> Option<String> {
2756 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2757 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2759 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2760 let budget = context
2763 .checked_sub(last_line_used_width(&result, offset.width()))
2765 let where_clause_str = try_opt!(rewrite_where_clause(
2767 &generics.where_clause,
2769 Shape::legacy(budget, offset.block_only()),
2773 trimmed_last_line_width(&result) == 1,
2778 result.push_str(&where_clause_str);
2779 force_same_line_brace || brace_style == BraceStyle::PreferSameLine ||
2780 (generics.where_clause.predicates.is_empty() && trimmed_last_line_width(&result) == 1)
2782 force_same_line_brace || trimmed_last_line_width(&result) == 1 ||
2783 brace_style != BraceStyle::AlwaysNextLine
2785 let total_used_width = last_line_used_width(&result, used_width);
2786 let remaining_budget = context
2789 .checked_sub(total_used_width)
2791 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2792 // and hence we take the closer into account as well for one line budget.
2793 // We assume that the closer has the same length as the opener.
2794 let overhead = if force_same_line_brace {
2795 1 + opener.len() + opener.len()
2799 let forbid_same_line_brace = overhead > remaining_budget;
2800 if !forbid_same_line_brace && same_line_brace {
2804 result.push_str(&offset.block_only().to_string(context.config));
2806 result.push_str(opener);