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.
16 use syntax::{abi, ast, ptr, symbol};
17 use syntax::ast::ImplItem;
18 use syntax::codemap::{BytePos, Span};
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
26 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27 rewrite_call_inner, ExprType};
28 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
29 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
32 use types::join_bounds;
33 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
34 format_constness, format_defaultness, format_mutability, format_unsafety,
35 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
36 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
37 stmt_expr, trim_newlines, trimmed_last_line_width};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
41 fn type_annotation_separator(config: &Config) -> &str {
43 config.space_before_type_annotation(),
44 config.space_after_type_annotation_colon(),
48 // Statements of the form
49 // let pat: ty = init;
50 impl Rewrite for ast::Local {
51 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
53 "Local::rewrite {:?} {} {:?}",
59 skip_out_of_file_lines_range!(context, self.span);
61 if contains_skip(&self.attrs) {
65 let attrs_str = self.attrs.rewrite(context, shape)?;
66 let mut result = if attrs_str.is_empty() {
69 combine_strs_with_missing_comments(
74 self.attrs.last().map(|a| a.span.hi()).unwrap(),
83 let pat_shape = shape.offset_left(4)?;
85 let pat_shape = pat_shape.sub_width(1)?;
86 let pat_str = self.pat.rewrite(context, pat_shape)?;
87 result.push_str(&pat_str);
89 // String that is placed within the assignment pattern and expression.
91 let mut infix = String::with_capacity(32);
93 if let Some(ref ty) = self.ty {
94 let separator = type_annotation_separator(context.config);
95 let indent = shape.indent + last_line_width(&result) + separator.len();
97 let budget = shape.width.checked_sub(indent.width() + 1)?;
98 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
100 infix.push_str(separator);
101 infix.push_str(&rewrite);
104 if self.init.is_some() {
105 infix.push_str(" =");
111 result.push_str(&infix);
113 if let Some(ref ex) = self.init {
114 // 1 = trailing semicolon;
115 let nested_shape = shape.sub_width(1)?;
117 result = rewrite_assign_rhs(context, result, ex, nested_shape)?;
125 // TODO convert to using rewrite style rather than visitor
126 // TODO format modules in this style
129 keyword: &'static str,
130 abi: Cow<'static, str>,
131 vis: Option<&'a ast::Visibility>,
132 body: Vec<BodyElement<'a>>,
137 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
140 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
144 .map(|i| BodyElement::ForeignItem(i))
151 enum BodyElement<'a> {
152 // Stmt(&'a ast::Stmt),
153 // Field(&'a ast::Field),
154 // Variant(&'a ast::Variant),
155 // Item(&'a ast::Item),
156 ForeignItem(&'a ast::ForeignItem),
159 /// Represents a fn's signature.
160 pub struct FnSig<'a> {
161 decl: &'a ast::FnDecl,
162 generics: &'a ast::Generics,
164 constness: ast::Constness,
165 defaultness: ast::Defaultness,
166 unsafety: ast::Unsafety,
167 visibility: ast::Visibility,
172 decl: &'a ast::FnDecl,
173 generics: &'a ast::Generics,
174 vis: ast::Visibility,
180 constness: ast::Constness::NotConst,
181 defaultness: ast::Defaultness::Final,
182 unsafety: ast::Unsafety::Normal,
187 pub fn from_method_sig(
188 method_sig: &'a ast::MethodSig,
189 generics: &'a ast::Generics,
192 unsafety: method_sig.unsafety,
193 constness: method_sig.constness.node,
194 defaultness: ast::Defaultness::Final,
196 decl: &*method_sig.decl,
198 visibility: ast::Visibility::Inherited,
203 fn_kind: &'a visit::FnKind,
204 generics: &'a ast::Generics,
205 decl: &'a ast::FnDecl,
206 defualtness: ast::Defaultness,
209 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
213 constness: constness.node,
214 defaultness: defualtness,
216 visibility: visibility.clone(),
218 visit::FnKind::Method(_, ref method_sig, vis, _) => {
219 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
220 fn_sig.defaultness = defualtness;
221 if let Some(vis) = vis {
222 fn_sig.visibility = vis.clone();
230 fn to_str(&self, context: &RewriteContext) -> String {
231 let mut result = String::with_capacity(128);
232 // Vis defaultness constness unsafety abi.
233 result.push_str(&*format_visibility(&self.visibility));
234 result.push_str(format_defaultness(self.defaultness));
235 result.push_str(format_constness(self.constness));
236 result.push_str(format_unsafety(self.unsafety));
237 result.push_str(&format_abi(
239 context.config.force_explicit_abi(),
246 impl<'a> FmtVisitor<'a> {
247 fn format_item(&mut self, item: Item) {
248 self.buffer.push_str(&item.abi);
250 let snippet = self.snippet(item.span);
251 let brace_pos = snippet.find_uncommented("{").unwrap();
253 self.buffer.push_str("{");
254 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
255 // FIXME: this skips comments between the extern keyword and the opening
257 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
258 self.block_indent = self.block_indent.block_indent(self.config);
260 if item.body.is_empty() {
261 self.format_missing_no_indent(item.span.hi() - BytePos(1));
262 self.block_indent = self.block_indent.block_unindent(self.config);
265 .push_str(&self.block_indent.to_string(self.config));
267 for item in &item.body {
268 self.format_body_element(item);
271 self.block_indent = self.block_indent.block_unindent(self.config);
272 self.format_missing_with_indent(item.span.hi() - BytePos(1));
276 self.buffer.push_str("}");
277 self.last_pos = item.span.hi();
280 fn format_body_element(&mut self, element: &BodyElement) {
282 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
286 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
287 let item = Item::from_foreign_mod(fm, span, self.config);
288 self.format_item(item);
292 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
293 let rewrite = item.rewrite(&self.get_context(), self.shape());
294 self.push_rewrite(item.span(), rewrite);
295 self.last_pos = item.span.hi();
305 ) -> Option<String> {
306 let context = self.get_context();
309 !is_empty_block(block, self.codemap) || !context.config.fn_empty_single_line();
310 let mut newline_brace =
311 newline_for_brace(self.config, &fn_sig.generics.where_clause, has_body);
313 let (mut result, force_newline_brace) =
314 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
316 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
317 newline_brace = true;
318 } else if last_line_width(&result) + 2 > self.shape().width {
320 newline_brace = true;
321 } else if !result.contains('\n') {
322 newline_brace = false;
325 // Prepare for the function body by possibly adding a newline and
327 // FIXME we'll miss anything between the end of the signature and the
328 // start of the body, but we need more spans from the compiler to solve
332 result.push_str(&indent.to_string(self.config));
337 self.single_line_fn(&result, block).or_else(|| Some(result))
340 pub fn rewrite_required_fn(
344 sig: &ast::MethodSig,
345 generics: &ast::Generics,
347 ) -> Option<String> {
348 // Drop semicolon or it will be interpreted as comment.
349 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
350 let context = self.get_context();
352 let (mut result, _) = rewrite_fn_base(
356 &FnSig::from_method_sig(sig, generics),
362 // Re-attach semicolon
368 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
369 if fn_str.contains('\n') {
373 let codemap = self.get_context().codemap;
375 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
376 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
378 return Some(format!("{}{{}}", fn_str));
381 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
383 if let Some(stmt) = block.stmts.first() {
384 match stmt_expr(stmt) {
386 let suffix = if semicolon_for_expr(&self.get_context(), e) {
392 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
394 .or_else(|| Some(self.snippet(e.span)))
396 None => stmt.rewrite(&self.get_context(), self.shape()),
403 if let Some(res) = rewrite {
404 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
405 if !res.contains('\n') && width <= self.config.max_width() {
406 return Some(format!("{}{{ {} }}", fn_str, res));
417 vis: &ast::Visibility,
418 enum_def: &ast::EnumDef,
419 generics: &ast::Generics,
422 let enum_header = format_header("enum ", ident, vis);
423 self.buffer.push_str(&enum_header);
425 let enum_snippet = self.snippet(span);
426 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
427 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
428 let generics_str = format_generics(
433 self.config.item_brace_style(),
434 enum_def.variants.is_empty(),
436 mk_sp(span.lo(), body_start),
437 last_line_width(&enum_header),
439 self.buffer.push_str(&generics_str);
441 self.last_pos = body_start;
443 self.block_indent = self.block_indent.block_indent(self.config);
444 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
446 Some(ref body_str) => self.buffer.push_str(body_str),
447 None => if contains_comment(&enum_snippet[brace_pos..]) {
448 self.format_missing_no_indent(span.hi() - BytePos(1))
451 self.block_indent = self.block_indent.block_unindent(self.config);
453 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
455 .push_str(&self.block_indent.to_string(self.config));
457 self.buffer.push_str("}");
458 self.last_pos = span.hi();
461 // Format the body of an enum definition
462 fn format_variant_list(
464 enum_def: &ast::EnumDef,
467 ) -> Option<String> {
468 if enum_def.variants.is_empty() {
471 let mut result = String::with_capacity(1024);
473 let indentation = self.block_indent.to_string(self.config);
474 result.push_str(&indentation);
476 let items = itemize_list(
478 enum_def.variants.iter(),
480 |f| if !f.node.attrs.is_empty() {
481 f.node.attrs[0].span.lo()
486 |f| self.format_variant(f),
492 let shape = self.shape().sub_width(2).unwrap();
493 let fmt = ListFormatting {
494 tactic: DefinitiveListTactic::Vertical,
496 trailing_separator: self.config.trailing_comma(),
497 separator_place: SeparatorPlace::Back,
499 ends_with_newline: true,
500 preserve_newline: true,
504 let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
505 result.push_str(&list);
510 // Variant of an enum.
511 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
512 if contains_skip(&field.node.attrs) {
513 let lo = field.node.attrs[0].span.lo();
514 let span = mk_sp(lo, field.span.hi());
515 return Some(self.snippet(span));
518 let context = self.get_context();
519 let indent = self.block_indent;
520 let shape = self.shape();
521 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
526 .map_or(field.span.lo(), |attr| attr.span.hi());
527 let span = mk_sp(lo, field.span.lo());
529 let variant_body = match field.node.data {
530 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
531 // FIXME: Should limit the width, as we have a trailing comma
536 &ast::Visibility::Inherited,
541 Some(self.config.struct_variant_width()),
544 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
545 let lhs = format!("{} =", field.node.name);
547 rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
549 String::from(field.node.name.to_string())
553 let attrs_extendable = attrs_str.is_empty()
554 || (context.config.attributes_on_same_line_as_variant()
555 && is_attributes_extendable(&attrs_str));
556 combine_strs_with_missing_comments(
568 context: &RewriteContext,
571 where_span_end: Option<BytePos>,
572 ) -> Option<String> {
573 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
574 let mut result = String::with_capacity(128);
575 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
576 let indent_str = offset.to_string(context.config);
577 let sep = format!("\n{}", &indent_str);
578 result.push_str(&ref_and_type);
580 let where_budget = if result.contains('\n') {
581 context.config.max_width()
583 context.budget(last_line_width(&result))
585 let option = WhereClauseOption::snuggled(&ref_and_type);
586 let where_clause_str = rewrite_where_clause(
588 &generics.where_clause,
589 context.config.item_brace_style(),
590 Shape::legacy(where_budget, offset.block_only()),
591 context.config.where_density(),
598 // If there is no where clause, we may have missing comments between the trait name and
599 // the opening brace.
600 if generics.where_clause.predicates.is_empty() {
601 if let Some(hi) = where_span_end {
602 match recover_missing_comment_in_span(
603 mk_sp(self_ty.span.hi(), hi),
604 Shape::indented(offset, context.config),
606 last_line_width(&result),
608 Some(ref missing_comment) if !missing_comment.is_empty() => {
609 result.push_str(missing_comment);
616 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
617 result.push_str(&where_clause_str);
618 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
619 result.push_str(&format!("{}{{{}}}", &sep, &sep));
621 result.push_str(" {}");
626 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
628 let width = offset.block_indent + context.config.tab_spaces() - 1;
629 let where_indent = Indent::new(0, width);
630 result.push_str(&where_indent.to_string(context.config));
632 result.push_str(&where_clause_str);
634 match context.config.item_brace_style() {
635 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
636 BraceStyle::AlwaysNextLine => result.push_str(&sep),
637 BraceStyle::PreferSameLine => result.push(' '),
638 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
639 result.push_str(&sep);
647 let snippet = context.snippet(item.span);
648 let open_pos = snippet.find_uncommented("{")? + 1;
650 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
651 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
652 visitor.block_indent = offset.block_only().block_indent(context.config);
653 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
655 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
657 visitor.visit_impl_item(item);
660 visitor.format_missing(item.span.hi() - BytePos(1));
662 let inner_indent_str = visitor.block_indent.to_string(context.config);
663 let outer_indent_str = offset.block_only().to_string(context.config);
666 result.push_str(&inner_indent_str);
667 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
669 result.push_str(&outer_indent_str);
672 if result.chars().last().unwrap() == '{' {
673 result.push_str(&sep);
683 fn is_impl_single_line(
684 context: &RewriteContext,
687 where_clause_str: &str,
690 let snippet = context.snippet(item.span);
691 let open_pos = snippet.find_uncommented("{")? + 1;
694 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
695 && result.len() + where_clause_str.len() <= context.config.max_width()
696 && !contains_comment(&snippet[open_pos..]),
700 fn format_impl_ref_and_type(
701 context: &RewriteContext,
704 ) -> Option<String> {
705 if let ast::ItemKind::Impl(
715 let mut result = String::with_capacity(128);
717 result.push_str(&format_visibility(&item.vis));
718 result.push_str(format_defaultness(defaultness));
719 result.push_str(format_unsafety(unsafety));
720 result.push_str("impl");
722 let lo = context.codemap.span_after(item.span, "impl");
723 let hi = match *trait_ref {
724 Some(ref tr) => tr.path.span.lo(),
725 None => self_ty.span.lo(),
727 let shape = generics_shape_from_config(
729 Shape::indented(offset + last_line_width(&result), context.config),
732 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
734 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
736 let polarity_str = if polarity == ast::ImplPolarity::Negative {
742 if let Some(ref trait_ref) = *trait_ref {
743 let result_len = result.len();
744 if let Some(trait_ref_str) = rewrite_trait_ref(
753 result.push_str(&trait_ref_str);
756 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
757 result.push_str(&rewrite_trait_ref(
768 result.push_str(&generics_str);
771 // Try to put the self type in a single line.
773 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
774 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
775 // If there is no where clause adapt budget for type formatting to take space and curly
776 // brace into account.
777 match context.config.item_brace_style() {
778 BraceStyle::AlwaysNextLine => 0,
784 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
785 // 1 = space before the type.
786 let budget = context.budget(used_space + 1);
787 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
788 if !self_ty_str.contains('\n') {
789 if trait_ref.is_some() {
790 result.push_str(" for ");
794 result.push_str(&self_ty_str);
799 // Couldn't fit the self type on a single line, put it on a new line.
801 // Add indentation of one additional tab.
802 let new_line_offset = offset.block_indent(context.config);
803 result.push_str(&new_line_offset.to_string(context.config));
804 if trait_ref.is_some() {
805 result.push_str("for ");
807 let budget = context.budget(last_line_width(&result));
808 let type_offset = match context.config.where_style() {
809 Style::Legacy => new_line_offset + trait_ref_overhead,
810 Style::Rfc => new_line_offset,
812 result.push_str(&*self_ty
813 .rewrite(context, Shape::legacy(budget, type_offset))?);
820 fn rewrite_trait_ref(
821 context: &RewriteContext,
822 trait_ref: &ast::TraitRef,
828 ) -> Option<String> {
829 // 1 = space between generics and trait_ref
830 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
831 let shape = Shape::indented(offset + used_space, context.config);
832 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
833 if !(retry && trait_ref_str.contains('\n')) {
842 // We could not make enough space for trait_ref, so put it on new line.
844 let offset = offset.block_indent(context.config);
845 let shape = Shape::indented(offset, context.config);
846 let trait_ref_str = trait_ref.rewrite(context, shape)?;
850 &offset.to_string(context.config),
859 pub fn format_struct(
860 context: &RewriteContext,
863 vis: &ast::Visibility,
864 struct_def: &ast::VariantData,
865 generics: Option<&ast::Generics>,
868 one_line_width: Option<usize>,
869 ) -> Option<String> {
871 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
872 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
882 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
896 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
897 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
900 let mut result = String::with_capacity(128);
901 let header = format!(
903 format_visibility(&item.vis),
904 format_unsafety(unsafety),
908 result.push_str(&header);
910 let body_lo = context.codemap.span_after(item.span, "{");
912 let shape = Shape::indented(offset + last_line_width(&result), context.config);
914 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
915 result.push_str(&generics_str);
917 let trait_bound_str = rewrite_trait_bounds(
920 Shape::indented(offset, context.config),
922 // If the trait, generics, and trait bound cannot fit on the same line,
923 // put the trait bounds on an indented new line
924 if offset.width() + last_line_width(&result) + trait_bound_str.len()
925 > context.config.comment_width()
928 let trait_indent = offset.block_only().block_indent(context.config);
929 result.push_str(&trait_indent.to_string(context.config));
931 result.push_str(&trait_bound_str);
933 let has_body = !trait_items.is_empty();
935 let where_density = if (context.config.where_density() == Density::Compressed
936 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
937 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
938 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
939 && !result.contains('\n'))
946 let where_budget = context.budget(last_line_width(&result));
947 let pos_before_where = if type_param_bounds.is_empty() {
948 generics.where_clause.span.lo()
950 type_param_bounds[type_param_bounds.len() - 1].span().hi()
952 let option = WhereClauseOption::snuggled(&generics_str);
953 let where_clause_str = rewrite_where_clause(
955 &generics.where_clause,
956 context.config.item_brace_style(),
957 Shape::legacy(where_budget, offset.block_only()),
964 // If the where clause cannot fit on the same line,
965 // put the where clause on a new line
966 if !where_clause_str.contains('\n')
967 && last_line_width(&result) + where_clause_str.len() + offset.width()
968 > context.config.comment_width()
971 let width = offset.block_indent + context.config.tab_spaces() - 1;
972 let where_indent = Indent::new(0, width);
973 result.push_str(&where_indent.to_string(context.config));
975 result.push_str(&where_clause_str);
977 if generics.where_clause.predicates.is_empty() {
978 let item_snippet = context.snippet(item.span);
979 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
981 let comment_hi = body_lo - BytePos(1);
982 let comment_lo = item.span.lo() + BytePos(lo as u32);
983 if comment_lo < comment_hi {
984 match recover_missing_comment_in_span(
985 mk_sp(comment_lo, comment_hi),
986 Shape::indented(offset, context.config),
988 last_line_width(&result),
990 Some(ref missing_comment) if !missing_comment.is_empty() => {
991 result.push_str(missing_comment);
999 match context.config.item_brace_style() {
1000 _ if last_line_contains_single_line_comment(&result) => {
1002 result.push_str(&offset.to_string(context.config));
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 = 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) => 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())
1092 || context.config.max_width() < overhead + result.len()
1094 format!("\n{}{{", offset.block_only().to_string(context.config))
1101 let overhead = if fields.is_empty() { 1 } else { 0 };
1102 let total_width = result.len() + generics_str.len() + overhead;
1103 if !generics_str.is_empty() && !generics_str.contains('\n')
1104 && total_width > context.config.max_width()
1107 result.push_str(&offset.to_string(context.config));
1108 result.push_str(generics_str.trim_left());
1110 result.push_str(&generics_str);
1113 if fields.is_empty() {
1114 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1115 if snippet.trim().is_empty() {
1117 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1119 result.push_str(snippet.trim_right());
1121 result.push_str(&offset.to_string(context.config));
1123 result.push_str(&snippet);
1126 return Some(result);
1130 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1131 let one_line_budget =
1132 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1134 let items_str = rewrite_with_alignment(
1137 Shape::indented(offset, context.config),
1138 mk_sp(body_lo, span.hi()),
1142 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1143 Some(format!("{} {} }}", result, items_str))
1149 .block_indent(context.config)
1150 .to_string(context.config),
1152 offset.to_string(context.config)
1157 fn format_tuple_struct(
1158 context: &RewriteContext,
1161 vis: &ast::Visibility,
1162 fields: &[ast::StructField],
1163 generics: Option<&ast::Generics>,
1166 ) -> Option<String> {
1167 let mut result = String::with_capacity(1024);
1169 let header_str = format_header(item_name, ident, vis);
1170 result.push_str(&header_str);
1172 let body_lo = if fields.is_empty() {
1173 context.codemap.span_after(span, "(")
1177 let body_hi = if fields.is_empty() {
1178 context.codemap.span_after(span, ")")
1180 // This is a dirty hack to work around a missing `)` from the span of the last field.
1181 let last_arg_span = fields[fields.len() - 1].span;
1182 if context.snippet(last_arg_span).ends_with(')') {
1187 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1191 let where_clause_str = match generics {
1193 let budget = context.budget(last_line_width(&header_str));
1194 let shape = Shape::legacy(budget, offset);
1195 let g_span = mk_sp(span.lo(), body_lo);
1196 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1197 result.push_str(&generics_str);
1199 let where_budget = context.budget(last_line_width(&result));
1200 let option = WhereClauseOption::new(true, false);
1201 rewrite_where_clause(
1203 &generics.where_clause,
1204 context.config.item_brace_style(),
1205 Shape::legacy(where_budget, offset.block_only()),
1206 Density::Compressed,
1213 None => "".to_owned(),
1216 if fields.is_empty() {
1218 let used_width = last_line_used_width(&result, offset.width()) + 3;
1219 if used_width > context.config.max_width() {
1221 result.push_str(&offset
1222 .block_indent(context.config)
1223 .to_string(context.config))
1226 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1227 if snippet.is_empty() {
1229 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1230 result.push_str(snippet.trim_right());
1232 result.push_str(&offset.to_string(context.config));
1234 result.push_str(&snippet);
1239 let body = rewrite_call_inner(
1242 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1244 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1245 context.config.fn_call_width(),
1248 result.push_str(&body);
1251 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1252 && (result.contains('\n')
1253 || offset.block_indent + result.len() + where_clause_str.len() + 1
1254 > context.config.max_width())
1256 // We need to put the where clause on a new line, but we didn't
1257 // know that earlier, so the where clause will not be indented properly.
1259 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1260 .to_string(context.config));
1262 result.push_str(&where_clause_str);
1267 pub fn rewrite_type_alias(
1268 context: &RewriteContext,
1272 generics: &ast::Generics,
1273 vis: &ast::Visibility,
1275 ) -> Option<String> {
1276 let mut result = String::with_capacity(128);
1278 result.push_str(&format_visibility(vis));
1279 result.push_str("type ");
1280 result.push_str(&ident.to_string());
1283 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1284 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1285 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1286 result.push_str(&generics_str);
1288 let where_budget = context.budget(last_line_width(&result));
1289 let option = WhereClauseOption::snuggled(&result);
1290 let where_clause_str = rewrite_where_clause(
1292 &generics.where_clause,
1293 context.config.item_brace_style(),
1294 Shape::legacy(where_budget, indent),
1295 context.config.where_density(),
1301 result.push_str(&where_clause_str);
1302 if where_clause_str.is_empty() {
1303 result.push_str(" = ");
1305 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1308 let line_width = last_line_width(&result);
1309 // This checked_sub may fail as the extra space after '=' is not taken into account
1310 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1311 let budget = context.budget(indent.width() + line_width + ";".len());
1312 let type_indent = indent + line_width;
1313 // Try to fit the type on the same line
1314 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1316 // The line was too short, try to put the type on the next line
1318 // Remove the space after '='
1320 let type_indent = indent.block_indent(context.config);
1322 result.push_str(&type_indent.to_string(context.config));
1323 let budget = context.budget(type_indent.width() + ";".len());
1324 ty.rewrite(context, Shape::legacy(budget, type_indent))
1326 result.push_str(&ty_str);
1327 result.push_str(";");
1331 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1333 if config.space_before_type_annotation() {
1338 if config.space_after_type_annotation_colon() {
1346 pub fn rewrite_struct_field_prefix(
1347 context: &RewriteContext,
1348 field: &ast::StructField,
1349 ) -> Option<String> {
1350 let vis = format_visibility(&field.vis);
1351 let type_annotation_spacing = type_annotation_spacing(context.config);
1352 Some(match field.ident {
1353 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1354 None => format!("{}", vis),
1358 impl Rewrite for ast::StructField {
1359 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1360 rewrite_struct_field(context, self, shape, 0)
1364 pub fn rewrite_struct_field(
1365 context: &RewriteContext,
1366 field: &ast::StructField,
1368 lhs_max_width: usize,
1369 ) -> Option<String> {
1370 if contains_skip(&field.attrs) {
1371 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1374 let type_annotation_spacing = type_annotation_spacing(context.config);
1375 let prefix = rewrite_struct_field_prefix(context, field)?;
1377 let attrs_str = field.attrs.rewrite(context, shape)?;
1378 let attrs_extendable = attrs_str.is_empty()
1379 || (context.config.attributes_on_same_line_as_field()
1380 && is_attributes_extendable(&attrs_str));
1381 let missing_span = if field.attrs.is_empty() {
1382 mk_sp(field.span.lo(), field.span.lo())
1384 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1386 let mut spacing = String::from(if field.ident.is_some() {
1387 type_annotation_spacing.1
1391 // Try to put everything on a single line.
1392 let attr_prefix = combine_strs_with_missing_comments(
1400 let overhead = last_line_width(&attr_prefix);
1401 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1402 for _ in 0..lhs_offset {
1405 // In this extreme case we will be missing a space betweeen an attribute and a field.
1406 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1409 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1410 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1411 if !ty.contains('\n') {
1412 return Some(attr_prefix + &spacing + ty);
1416 // We must use multiline.
1417 let new_shape = shape.with_max_width(context.config);
1418 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1420 let field_str = if prefix.is_empty() {
1422 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1423 prefix + " " + &ty_rewritten
1425 let type_offset = shape.indent.block_indent(context.config);
1426 let nested_shape = Shape::indented(type_offset, context.config);
1427 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1428 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1430 combine_strs_with_missing_comments(
1440 pub fn rewrite_static(
1442 vis: &ast::Visibility,
1445 mutability: ast::Mutability,
1446 expr_opt: Option<&ptr::P<ast::Expr>>,
1449 context: &RewriteContext,
1450 ) -> Option<String> {
1451 let colon = colon_spaces(
1452 context.config.space_before_type_annotation(),
1453 context.config.space_after_type_annotation_colon(),
1455 let prefix = format!(
1457 format_visibility(vis),
1459 format_mutability(mutability),
1464 let ty_str = ty.rewrite(
1466 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1469 if let Some(expr) = expr_opt {
1470 let lhs = format!("{}{} =", prefix, ty_str);
1472 let remaining_width = context.budget(offset.block_indent + 1);
1477 Shape::legacy(remaining_width, offset.block_only()),
1478 ).and_then(|res| recover_comment_removed(res, span, context))
1479 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1481 Some(format!("{}{};", prefix, ty_str))
1485 pub fn rewrite_associated_type(
1487 ty_opt: Option<&ptr::P<ast::Ty>>,
1488 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1489 context: &RewriteContext,
1491 ) -> Option<String> {
1492 let prefix = format!("type {}", ident);
1494 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1496 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1497 let bounds: &[_] = ty_param_bounds;
1498 let bound_str = bounds
1500 .map(|ty_bound| ty_bound.rewrite(context, shape))
1501 .collect::<Option<Vec<_>>>()?;
1502 if !bounds.is_empty() {
1503 format!(": {}", join_bounds(context, shape, &bound_str))
1511 if let Some(ty) = ty_opt {
1512 let ty_str = ty.rewrite(
1515 context.budget(indent.block_indent + prefix.len() + 2),
1516 indent.block_only(),
1519 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1521 Some(format!("{}{};", prefix, type_bounds_str))
1525 pub fn rewrite_associated_impl_type(
1527 defaultness: ast::Defaultness,
1528 ty_opt: Option<&ptr::P<ast::Ty>>,
1529 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1530 context: &RewriteContext,
1532 ) -> Option<String> {
1533 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1536 ast::Defaultness::Default => Some(format!("default {}", result)),
1541 impl Rewrite for ast::FunctionRetTy {
1542 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1544 ast::FunctionRetTy::Default(_) => Some(String::new()),
1545 ast::FunctionRetTy::Ty(ref ty) => {
1546 let inner_width = shape.width.checked_sub(3)?;
1547 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1548 .map(|r| format!("-> {}", r))
1554 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1556 ast::TyKind::Infer => {
1557 let original = context.snippet(ty.span);
1564 impl Rewrite for ast::Arg {
1565 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1566 if is_named_arg(self) {
1567 let mut result = self.pat
1568 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1570 if !is_empty_infer(context, &*self.ty) {
1571 if context.config.space_before_type_annotation() {
1572 result.push_str(" ");
1574 result.push_str(":");
1575 if context.config.space_after_type_annotation_colon() {
1576 result.push_str(" ");
1578 let overhead = last_line_width(&result);
1579 let max_width = shape.width.checked_sub(overhead)?;
1580 let ty_str = self.ty
1581 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1582 result.push_str(&ty_str);
1587 self.ty.rewrite(context, shape)
1592 fn rewrite_explicit_self(
1593 explicit_self: &ast::ExplicitSelf,
1595 context: &RewriteContext,
1596 ) -> Option<String> {
1597 match explicit_self.node {
1598 ast::SelfKind::Region(lt, m) => {
1599 let mut_str = format_mutability(m);
1602 let lifetime_str = l.rewrite(
1604 Shape::legacy(context.config.max_width(), Indent::empty()),
1606 Some(format!("&{} {}self", lifetime_str, mut_str))
1608 None => Some(format!("&{}self", mut_str)),
1611 ast::SelfKind::Explicit(ref ty, _) => {
1612 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1614 let mutability = explicit_self_mutability(&args[0]);
1615 let type_str = ty.rewrite(
1617 Shape::legacy(context.config.max_width(), Indent::empty()),
1622 format_mutability(mutability),
1626 ast::SelfKind::Value(_) => {
1627 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1629 let mutability = explicit_self_mutability(&args[0]);
1631 Some(format!("{}self", format_mutability(mutability)))
1636 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1637 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1638 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1639 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1646 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1647 if is_named_arg(arg) {
1654 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1656 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1657 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1658 _ => arg.ty.span.hi(),
1662 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1663 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1664 ident.node != symbol::keywords::Invalid.ident()
1670 // Return type is (result, force_new_line_for_brace)
1672 context: &RewriteContext,
1677 newline_brace: bool,
1679 ) -> Option<(String, bool)> {
1680 let mut force_new_line_for_brace = false;
1682 let where_clause = &fn_sig.generics.where_clause;
1684 let mut result = String::with_capacity(1024);
1685 result.push_str(&fn_sig.to_str(context));
1688 result.push_str("fn ");
1689 result.push_str(&ident.to_string());
1692 let overhead = if has_body && !newline_brace {
1699 let used_width = last_line_used_width(&result, indent.width());
1700 let one_line_budget = context.budget(used_width + overhead);
1702 width: one_line_budget,
1706 let fd = fn_sig.decl;
1707 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1708 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1709 result.push_str(&generics_str);
1711 let snuggle_angle_bracket = generics_str
1714 .map_or(false, |l| l.trim_left().len() == 1);
1716 // Note that the width and indent don't really matter, we'll re-layout the
1717 // return type later anyway.
1718 let ret_str = fd.output
1719 .rewrite(context, Shape::indented(indent, context.config))?;
1721 let multi_line_ret_str = ret_str.contains('\n');
1722 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1725 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1736 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1742 // Check if vertical layout was forced.
1743 if one_line_budget == 0 {
1744 if snuggle_angle_bracket {
1746 } else if context.config.fn_args_paren_newline() {
1748 result.push_str(&arg_indent.to_string(context.config));
1749 if context.config.fn_args_layout() == IndentStyle::Visual {
1750 arg_indent = arg_indent + 1; // extra space for `(`
1754 result.push_str("(");
1755 if context.config.fn_args_layout() == IndentStyle::Visual {
1757 result.push_str(&arg_indent.to_string(context.config));
1763 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1767 // Skip `pub(crate)`.
1768 let lo_after_visibility = if let ast::Visibility::Crate(s) = fn_sig.visibility {
1769 context.codemap.span_after(mk_sp(s.hi(), span.hi()), ")")
1773 // A conservative estimation, to goal is to be over all parens in generics
1774 let args_start = fn_sig
1778 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1779 let args_end = if fd.inputs.is_empty() {
1782 .span_after(mk_sp(args_start, span.hi()), ")")
1784 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1785 context.codemap.span_after(last_span, ")")
1787 let args_span = mk_sp(
1790 .span_after(mk_sp(args_start, span.hi()), "("),
1793 let arg_str = rewrite_args(
1796 fd.get_self().as_ref(),
1803 generics_str.contains('\n'),
1806 let put_args_in_block = match context.config.fn_args_layout() {
1807 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1809 } && !fd.inputs.is_empty();
1811 let mut args_last_line_contains_comment = false;
1812 if put_args_in_block {
1813 arg_indent = indent.block_indent(context.config);
1815 result.push_str(&arg_indent.to_string(context.config));
1816 result.push_str(&arg_str);
1818 result.push_str(&indent.to_string(context.config));
1821 result.push_str(&arg_str);
1822 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1823 // Put the closing brace on the next line if it overflows the max width.
1825 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1828 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1831 // If the last line of args contains comment, we cannot put the closing paren
1832 // on the same line.
1836 .map_or(false, |last_line| last_line.contains("//"))
1838 args_last_line_contains_comment = true;
1840 result.push_str(&arg_indent.to_string(context.config));
1846 if let ast::FunctionRetTy::Ty(..) = fd.output {
1847 let ret_should_indent = match context.config.fn_args_layout() {
1848 // If our args are block layout then we surely must have space.
1849 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1850 _ if args_last_line_contains_comment => false,
1851 _ if result.contains('\n') || multi_line_ret_str => true,
1853 // If the return type would push over the max width, then put the return type on
1854 // a new line. With the +1 for the signature length an additional space between
1855 // the closing parenthesis of the argument and the arrow '->' is considered.
1856 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1858 // If there is no where clause, take into account the space after the return type
1860 if where_clause.predicates.is_empty() {
1864 sig_length > context.config.max_width()
1867 let ret_indent = if ret_should_indent {
1868 let indent = match context.config.fn_return_indent() {
1869 ReturnIndent::WithWhereClause => indent + 4,
1870 // Aligning with non-existent args looks silly.
1871 _ if arg_str.is_empty() => {
1872 force_new_line_for_brace = true;
1875 // FIXME: we might want to check that using the arg indent
1876 // doesn't blow our budget, and if it does, then fallback to
1877 // the where clause indent.
1882 result.push_str(&indent.to_string(context.config));
1886 Indent::new(indent.block_indent, last_line_width(&result))
1889 if multi_line_ret_str || ret_should_indent {
1890 // Now that we know the proper indent and width, we need to
1891 // re-layout the return type.
1892 let ret_str = fd.output
1893 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1894 result.push_str(&ret_str);
1896 result.push_str(&ret_str);
1899 // Comment between return type and the end of the decl.
1900 let snippet_lo = fd.output.span().hi();
1901 if where_clause.predicates.is_empty() {
1902 let snippet_hi = span.hi();
1903 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1904 // Try to preserve the layout of the original snippet.
1905 let original_starts_with_newline = snippet
1907 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1908 let original_ends_with_newline = snippet
1909 .rfind(|c| c != ' ')
1910 .map_or(false, |i| snippet[i..].ends_with('\n'));
1911 let snippet = snippet.trim();
1912 if !snippet.is_empty() {
1913 result.push(if original_starts_with_newline {
1918 result.push_str(snippet);
1919 if original_ends_with_newline {
1920 force_new_line_for_brace = true;
1926 let should_compress_where = match context.config.where_density() {
1927 Density::Compressed => !result.contains('\n'),
1928 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1932 let pos_before_where = match fd.output {
1933 ast::FunctionRetTy::Default(..) => args_span.hi(),
1934 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1937 if where_clause.predicates.len() == 1 && should_compress_where {
1938 let budget = context.budget(last_line_used_width(&result, indent.width()));
1939 if let Some(where_clause_str) = rewrite_where_clause(
1942 context.config.fn_brace_style(),
1943 Shape::legacy(budget, indent),
1944 Density::Compressed,
1948 WhereClauseOption::compressed(),
1950 result.push_str(&where_clause_str);
1951 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1952 return Some((result, force_new_line_for_brace));
1956 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1957 let where_clause_str = rewrite_where_clause(
1960 context.config.fn_brace_style(),
1961 Shape::indented(indent, context.config),
1968 // If there are neither where clause nor return type, we may be missing comments between
1970 if where_clause_str.is_empty() {
1971 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1972 match recover_missing_comment_in_span(
1973 mk_sp(args_span.hi(), ret_span.hi()),
1976 last_line_width(&result),
1978 Some(ref missing_comment) if !missing_comment.is_empty() => {
1979 result.push_str(missing_comment);
1980 force_new_line_for_brace = true;
1987 result.push_str(&where_clause_str);
1989 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1990 Some((result, force_new_line_for_brace))
1993 #[derive(Copy, Clone)]
1994 struct WhereClauseOption {
1995 suppress_comma: bool, // Force no trailing comma
1996 snuggle: bool, // Do not insert newline before `where`
1997 compress_where: bool, // Try single line where clause instead of vertical layout
2000 impl WhereClauseOption {
2001 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2003 suppress_comma: suppress_comma,
2005 compress_where: false,
2009 pub fn compressed() -> WhereClauseOption {
2011 suppress_comma: true,
2013 compress_where: true,
2017 pub fn snuggled(current: &str) -> WhereClauseOption {
2019 suppress_comma: false,
2020 snuggle: trimmed_last_line_width(current) == 1,
2021 compress_where: false,
2027 context: &RewriteContext,
2029 explicit_self: Option<&ast::ExplicitSelf>,
2030 one_line_budget: usize,
2031 multi_line_budget: usize,
2036 generics_str_contains_newline: bool,
2037 ) -> Option<String> {
2038 let mut arg_item_strs = args.iter()
2039 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2040 .collect::<Option<Vec<_>>>()?;
2042 // Account for sugary self.
2043 // FIXME: the comment for the self argument is dropped. This is blocked
2044 // on rust issue #27522.
2045 let min_args = explicit_self
2046 .and_then(|explicit_self| {
2047 rewrite_explicit_self(explicit_self, args, context)
2049 .map_or(1, |self_str| {
2050 arg_item_strs[0] = self_str;
2054 // Comments between args.
2055 let mut arg_items = Vec::new();
2057 arg_items.push(ListItem::from_str(""));
2060 // FIXME(#21): if there are no args, there might still be a comment, but
2061 // without spans for the comment or parens, there is no chance of
2062 // getting it right. You also don't get to put a comment on self, unless
2064 if args.len() >= min_args || variadic {
2065 let comment_span_start = if min_args == 2 {
2066 let second_arg_start = if arg_has_pattern(&args[1]) {
2067 args[1].pat.span.lo()
2069 args[1].ty.span.lo()
2071 let reduced_span = mk_sp(span.lo(), second_arg_start);
2073 context.codemap.span_after_last(reduced_span, ",")
2078 enum ArgumentKind<'a> {
2079 Regular(&'a ast::Arg),
2083 let variadic_arg = if variadic {
2084 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2085 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2086 Some(ArgumentKind::Variadic(variadic_start))
2091 let more_items = itemize_list(
2093 args[min_args - 1..]
2095 .map(ArgumentKind::Regular)
2096 .chain(variadic_arg),
2099 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2100 ArgumentKind::Variadic(start) => start,
2103 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2104 ArgumentKind::Variadic(start) => start + BytePos(3),
2107 ArgumentKind::Regular(..) => None,
2108 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2115 arg_items.extend(more_items);
2118 let fits_in_one_line = !generics_str_contains_newline
2119 && (arg_items.is_empty()
2120 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2122 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2123 item.item = Some(arg);
2126 let last_line_ends_with_comment = arg_items
2129 .and_then(|item| item.post_comment.as_ref())
2130 .map_or(false, |s| s.trim().starts_with("//"));
2132 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2133 IndentStyle::Block if fits_in_one_line => {
2134 (indent.block_indent(context.config), SeparatorTactic::Never)
2136 IndentStyle::Block => (
2137 indent.block_indent(context.config),
2138 context.config.trailing_comma(),
2140 IndentStyle::Visual if last_line_ends_with_comment => {
2141 (arg_indent, context.config.trailing_comma())
2143 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2146 let tactic = definitive_tactic(
2148 context.config.fn_args_density().to_list_tactic(),
2152 let budget = match tactic {
2153 DefinitiveListTactic::Horizontal => one_line_budget,
2154 _ => multi_line_budget,
2157 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2159 let fmt = ListFormatting {
2162 trailing_separator: if variadic {
2163 SeparatorTactic::Never
2167 separator_place: SeparatorPlace::Back,
2168 shape: Shape::legacy(budget, indent),
2169 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2170 preserve_newline: true,
2171 config: context.config,
2174 write_list(&arg_items, &fmt)
2177 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2178 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2179 ident.node != symbol::keywords::Invalid.ident()
2185 fn compute_budgets_for_args(
2186 context: &RewriteContext,
2190 newline_brace: bool,
2192 force_vertical_layout: bool,
2193 ) -> Option<((usize, usize, Indent))> {
2195 "compute_budgets_for_args {} {:?}, {}, {}",
2201 // Try keeping everything on the same line.
2202 if !result.contains('\n') && !force_vertical_layout {
2203 // 2 = `()`, 3 = `() `, space is before ret_string.
2204 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2205 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2215 let one_line_budget = context.budget(used_space);
2217 if one_line_budget > 0 {
2219 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2220 IndentStyle::Block => {
2221 let indent = indent.block_indent(context.config);
2222 (indent, context.budget(indent.width() + 1))
2224 IndentStyle::Visual => {
2225 let indent = indent + result.len() + 1;
2226 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2227 (indent, context.budget(multi_line_overhead))
2231 return Some((one_line_budget, multi_line_budget, indent));
2235 // Didn't work. we must force vertical layout and put args on a newline.
2236 let new_indent = indent.block_indent(context.config);
2237 let used_space = match context.config.fn_args_layout() {
2239 IndentStyle::Block => new_indent.width() + 1,
2240 // Account for `)` and possibly ` {`.
2241 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2243 Some((0, context.budget(used_space), new_indent))
2246 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2247 match (config.fn_brace_style(), config.where_density()) {
2248 (BraceStyle::AlwaysNextLine, _) => true,
2249 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2250 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2251 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2256 fn rewrite_generics(
2257 context: &RewriteContext,
2258 generics: &ast::Generics,
2261 ) -> Option<String> {
2262 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2263 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2264 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2265 rewrite_generics_inner(context, generics, g_shape, 0, span)
2269 fn rewrite_generics_inner(
2270 context: &RewriteContext,
2271 generics: &ast::Generics,
2273 one_line_width: usize,
2275 ) -> Option<String> {
2276 // FIXME: convert bounds to where clauses where they get too big or if
2277 // there is a where clause at all.
2280 enum GenericsArg<'a> {
2281 Lifetime(&'a ast::LifetimeDef),
2282 TyParam(&'a ast::TyParam),
2284 impl<'a> Rewrite for GenericsArg<'a> {
2285 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2287 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2288 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2292 impl<'a> Spanned for GenericsArg<'a> {
2293 fn span(&self) -> Span {
2295 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2296 GenericsArg::TyParam(ref ty) => ty.span(),
2301 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2302 return Some(String::new());
2305 let generics_args = generics
2308 .map(|lt| GenericsArg::Lifetime(lt))
2309 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2310 let items = itemize_list(
2314 |arg| arg.span().lo(),
2315 |arg| arg.span().hi(),
2316 |arg| arg.rewrite(context, shape),
2317 context.codemap.span_after(span, "<"),
2321 format_generics_item_list(context, items, shape, one_line_width)
2324 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2325 match config.generics_indent() {
2326 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2327 IndentStyle::Block => {
2331 .block_indent(config.tab_spaces())
2332 .with_max_width(config)
2338 pub fn format_generics_item_list<I>(
2339 context: &RewriteContext,
2342 one_line_budget: usize,
2345 I: Iterator<Item = ListItem>,
2347 let item_vec = items.collect::<Vec<_>>();
2349 let tactic = definitive_tactic(
2351 ListTactic::HorizontalVertical,
2355 let fmt = ListFormatting {
2358 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2359 SeparatorTactic::Never
2361 context.config.trailing_comma()
2363 separator_place: SeparatorPlace::Back,
2365 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2366 preserve_newline: true,
2367 config: context.config,
2370 let list_str = write_list(&item_vec, &fmt)?;
2372 Some(wrap_generics_with_angle_brackets(
2379 pub fn wrap_generics_with_angle_brackets(
2380 context: &RewriteContext,
2382 list_offset: Indent,
2384 if context.config.generics_indent() == IndentStyle::Block
2385 && (list_str.contains('\n') || list_str.ends_with(','))
2389 list_offset.to_string(context.config),
2392 .block_unindent(context.config)
2393 .to_string(context.config)
2395 } else if context.config.spaces_within_angle_brackets() {
2396 format!("< {} >", list_str)
2398 format!("<{}>", list_str)
2402 fn rewrite_trait_bounds(
2403 context: &RewriteContext,
2404 type_param_bounds: &ast::TyParamBounds,
2406 ) -> Option<String> {
2407 let bounds: &[_] = type_param_bounds;
2409 if bounds.is_empty() {
2410 return Some(String::new());
2412 let bound_str = bounds
2414 .map(|ty_bound| ty_bound.rewrite(context, shape))
2415 .collect::<Option<Vec<_>>>()?;
2416 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2419 fn rewrite_where_clause_rfc_style(
2420 context: &RewriteContext,
2421 where_clause: &ast::WhereClause,
2424 span_end: Option<BytePos>,
2425 span_end_before_where: BytePos,
2426 where_clause_option: WhereClauseOption,
2427 ) -> Option<String> {
2428 let block_shape = shape.block().with_max_width(context.config);
2430 let (span_before, span_after) =
2431 missing_span_before_after_where(span_end_before_where, where_clause);
2432 let (comment_before, comment_after) =
2433 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2435 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2438 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2441 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2443 let clause_shape = clause_shape.sub_width(1)?;
2444 // each clause on one line, trailing comma (except if suppress_comma)
2445 let span_start = where_clause.predicates[0].span().lo();
2446 // If we don't have the start of the next span, then use the end of the
2447 // predicates, but that means we miss comments.
2448 let len = where_clause.predicates.len();
2449 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2450 let span_end = span_end.unwrap_or(end_of_preds);
2451 let items = itemize_list(
2453 where_clause.predicates.iter(),
2455 |pred| pred.span().lo(),
2456 |pred| pred.span().hi(),
2457 |pred| pred.rewrite(context, clause_shape),
2462 let comma_tactic = if where_clause_option.suppress_comma {
2463 SeparatorTactic::Never
2465 context.config.trailing_comma()
2468 let fmt = ListFormatting {
2469 tactic: DefinitiveListTactic::Vertical,
2471 trailing_separator: comma_tactic,
2472 separator_place: SeparatorPlace::Back,
2473 shape: clause_shape,
2474 ends_with_newline: true,
2475 preserve_newline: true,
2476 config: context.config,
2478 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2480 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2483 format!("\n{}", shape.indent.to_string(context.config))
2485 let newline_before_where = comment_separator(&comment_before, shape);
2486 let newline_after_where = comment_separator(&comment_after, clause_shape);
2489 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2490 && comment_after.is_empty() && !preds_str.contains('\n')
2491 && 6 + preds_str.len() <= shape.width
2495 format!("\n{}", clause_shape.indent.to_string(context.config))
2498 "{}{}{}where{}{}{}{}",
2501 newline_before_where,
2502 newline_after_where,
2509 fn rewrite_where_clause(
2510 context: &RewriteContext,
2511 where_clause: &ast::WhereClause,
2512 brace_style: BraceStyle,
2516 span_end: Option<BytePos>,
2517 span_end_before_where: BytePos,
2518 where_clause_option: WhereClauseOption,
2519 ) -> Option<String> {
2520 if where_clause.predicates.is_empty() {
2521 return Some(String::new());
2524 if context.config.where_style() == Style::Rfc {
2525 return rewrite_where_clause_rfc_style(
2531 span_end_before_where,
2532 where_clause_option,
2536 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2538 let offset = match context.config.where_pred_indent() {
2539 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2540 // 6 = "where ".len()
2541 IndentStyle::Visual => shape.indent + extra_indent + 6,
2543 // FIXME: if where_pred_indent != Visual, then the budgets below might
2544 // be out by a char or two.
2546 let budget = context.config.max_width() - offset.width();
2547 let span_start = where_clause.predicates[0].span().lo();
2548 // If we don't have the start of the next span, then use the end of the
2549 // predicates, but that means we miss comments.
2550 let len = where_clause.predicates.len();
2551 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2552 let span_end = span_end.unwrap_or(end_of_preds);
2553 let items = itemize_list(
2555 where_clause.predicates.iter(),
2557 |pred| pred.span().lo(),
2558 |pred| pred.span().hi(),
2559 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2564 let item_vec = items.collect::<Vec<_>>();
2565 // FIXME: we don't need to collect here if the where_layout isn't
2566 // HorizontalVertical.
2567 let tactic = definitive_tactic(
2569 context.config.where_layout(),
2574 let mut comma_tactic = context.config.trailing_comma();
2575 // Kind of a hack because we don't usually have trailing commas in where clauses.
2576 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2577 comma_tactic = SeparatorTactic::Never;
2580 let fmt = ListFormatting {
2583 trailing_separator: comma_tactic,
2584 separator_place: SeparatorPlace::Back,
2585 shape: Shape::legacy(budget, offset),
2586 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2587 preserve_newline: true,
2588 config: context.config,
2590 let preds_str = write_list(&item_vec, &fmt)?;
2592 let end_length = if terminator == "{" {
2593 // If the brace is on the next line we don't need to count it otherwise it needs two
2596 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2597 BraceStyle::PreferSameLine => 2,
2599 } else if terminator == "=" {
2604 if density == Density::Tall || preds_str.contains('\n')
2605 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2609 (shape.indent + extra_indent).to_string(context.config),
2613 Some(format!(" where {}", preds_str))
2617 fn missing_span_before_after_where(
2618 before_item_span_end: BytePos,
2619 where_clause: &ast::WhereClause,
2621 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2623 let pos_after_where = where_clause.span.lo() + BytePos(5);
2624 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2625 (missing_span_before, missing_span_after)
2628 fn rewrite_comments_before_after_where(
2629 context: &RewriteContext,
2630 span_before_where: Span,
2631 span_after_where: Span,
2633 ) -> Option<(String, String)> {
2634 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2635 let after_comment = rewrite_missing_comment(
2637 shape.block_indent(context.config.tab_spaces()),
2640 Some((before_comment, after_comment))
2643 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2644 format!("{}{}{}", format_visibility(vis), item_name, ident)
2648 context: &RewriteContext,
2649 generics: &ast::Generics,
2652 brace_style: BraceStyle,
2653 force_same_line_brace: bool,
2657 ) -> Option<String> {
2658 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2659 let mut result = rewrite_generics(context, generics, shape, span)?;
2661 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2662 let budget = context.budget(last_line_used_width(&result, offset.width()));
2663 let option = WhereClauseOption::snuggled(&result);
2664 let where_clause_str = rewrite_where_clause(
2666 &generics.where_clause,
2668 Shape::legacy(budget, offset.block_only()),
2675 result.push_str(&where_clause_str);
2676 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2677 || (generics.where_clause.predicates.is_empty()
2678 && trimmed_last_line_width(&result) == 1)
2680 force_same_line_brace || trimmed_last_line_width(&result) == 1
2681 || brace_style != BraceStyle::AlwaysNextLine
2683 let total_used_width = last_line_used_width(&result, used_width);
2684 let remaining_budget = context.budget(total_used_width);
2685 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2686 // and hence we take the closer into account as well for one line budget.
2687 // We assume that the closer has the same length as the opener.
2688 let overhead = if force_same_line_brace {
2689 1 + opener.len() + opener.len()
2693 let forbid_same_line_brace = overhead > remaining_budget;
2694 if !forbid_same_line_brace && same_line_brace {
2698 result.push_str(&offset.block_only().to_string(context.config));
2700 result.push_str(opener);
2705 impl Rewrite for ast::ForeignItem {
2706 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2707 let attrs_str = self.attrs.rewrite(context, shape)?;
2708 // Drop semicolon or it will be interpreted as comment.
2709 // FIXME: this may be a faulty span from libsyntax.
2710 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2712 let item_str = match self.node {
2713 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2717 &FnSig::new(fn_decl, generics, self.vis.clone()),
2721 ).map(|(s, _)| format!("{};", s)),
2722 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2723 // FIXME(#21): we're dropping potential comments in between the
2724 // function keywords here.
2725 let vis = format_visibility(&self.vis);
2726 let mut_str = if is_mutable { "mut " } else { "" };
2727 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2729 let shape = shape.sub_width(1)?;
2730 ty.rewrite(context, shape).map(|ty_str| {
2731 // 1 = space between prefix and type.
2732 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2735 let nested_indent = shape.indent.block_indent(context.config);
2736 format!("\n{}", nested_indent.to_string(context.config))
2738 format!("{}{}{};", prefix, sep, ty_str)
2743 let missing_span = if self.attrs.is_empty() {
2744 mk_sp(self.span.lo(), self.span.lo())
2746 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2748 combine_strs_with_missing_comments(