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::{CrateSugar, 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 = match fn_sig.visibility {
1769 ast::Visibility::Crate(s, CrateSugar::PubCrate) => {
1770 context.codemap.span_after(mk_sp(s.hi(), span.hi()), ")")
1772 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1775 // A conservative estimation, to goal is to be over all parens in generics
1776 let args_start = fn_sig
1780 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1781 let args_end = if fd.inputs.is_empty() {
1784 .span_after(mk_sp(args_start, span.hi()), ")")
1786 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1787 context.codemap.span_after(last_span, ")")
1789 let args_span = mk_sp(
1792 .span_after(mk_sp(args_start, span.hi()), "("),
1795 let arg_str = rewrite_args(
1798 fd.get_self().as_ref(),
1805 generics_str.contains('\n'),
1808 let put_args_in_block = match context.config.fn_args_layout() {
1809 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1811 } && !fd.inputs.is_empty();
1813 let mut args_last_line_contains_comment = false;
1814 if put_args_in_block {
1815 arg_indent = indent.block_indent(context.config);
1817 result.push_str(&arg_indent.to_string(context.config));
1818 result.push_str(&arg_str);
1820 result.push_str(&indent.to_string(context.config));
1823 result.push_str(&arg_str);
1824 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1825 // Put the closing brace on the next line if it overflows the max width.
1827 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1830 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1833 // If the last line of args contains comment, we cannot put the closing paren
1834 // on the same line.
1838 .map_or(false, |last_line| last_line.contains("//"))
1840 args_last_line_contains_comment = true;
1842 result.push_str(&arg_indent.to_string(context.config));
1848 if let ast::FunctionRetTy::Ty(..) = fd.output {
1849 let ret_should_indent = match context.config.fn_args_layout() {
1850 // If our args are block layout then we surely must have space.
1851 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1852 _ if args_last_line_contains_comment => false,
1853 _ if result.contains('\n') || multi_line_ret_str => true,
1855 // If the return type would push over the max width, then put the return type on
1856 // a new line. With the +1 for the signature length an additional space between
1857 // the closing parenthesis of the argument and the arrow '->' is considered.
1858 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1860 // If there is no where clause, take into account the space after the return type
1862 if where_clause.predicates.is_empty() {
1866 sig_length > context.config.max_width()
1869 let ret_indent = if ret_should_indent {
1870 let indent = match context.config.fn_return_indent() {
1871 ReturnIndent::WithWhereClause => indent + 4,
1872 // Aligning with non-existent args looks silly.
1873 _ if arg_str.is_empty() => {
1874 force_new_line_for_brace = true;
1877 // FIXME: we might want to check that using the arg indent
1878 // doesn't blow our budget, and if it does, then fallback to
1879 // the where clause indent.
1884 result.push_str(&indent.to_string(context.config));
1888 Indent::new(indent.block_indent, last_line_width(&result))
1891 if multi_line_ret_str || ret_should_indent {
1892 // Now that we know the proper indent and width, we need to
1893 // re-layout the return type.
1894 let ret_str = fd.output
1895 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1896 result.push_str(&ret_str);
1898 result.push_str(&ret_str);
1901 // Comment between return type and the end of the decl.
1902 let snippet_lo = fd.output.span().hi();
1903 if where_clause.predicates.is_empty() {
1904 let snippet_hi = span.hi();
1905 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1906 // Try to preserve the layout of the original snippet.
1907 let original_starts_with_newline = snippet
1909 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1910 let original_ends_with_newline = snippet
1911 .rfind(|c| c != ' ')
1912 .map_or(false, |i| snippet[i..].ends_with('\n'));
1913 let snippet = snippet.trim();
1914 if !snippet.is_empty() {
1915 result.push(if original_starts_with_newline {
1920 result.push_str(snippet);
1921 if original_ends_with_newline {
1922 force_new_line_for_brace = true;
1928 let should_compress_where = match context.config.where_density() {
1929 Density::Compressed => !result.contains('\n'),
1930 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1934 let pos_before_where = match fd.output {
1935 ast::FunctionRetTy::Default(..) => args_span.hi(),
1936 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1939 if where_clause.predicates.len() == 1 && should_compress_where {
1940 let budget = context.budget(last_line_used_width(&result, indent.width()));
1941 if let Some(where_clause_str) = rewrite_where_clause(
1944 context.config.fn_brace_style(),
1945 Shape::legacy(budget, indent),
1946 Density::Compressed,
1950 WhereClauseOption::compressed(),
1952 result.push_str(&where_clause_str);
1953 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1954 return Some((result, force_new_line_for_brace));
1958 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1959 let where_clause_str = rewrite_where_clause(
1962 context.config.fn_brace_style(),
1963 Shape::indented(indent, context.config),
1970 // If there are neither where clause nor return type, we may be missing comments between
1972 if where_clause_str.is_empty() {
1973 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1974 match recover_missing_comment_in_span(
1975 mk_sp(args_span.hi(), ret_span.hi()),
1978 last_line_width(&result),
1980 Some(ref missing_comment) if !missing_comment.is_empty() => {
1981 result.push_str(missing_comment);
1982 force_new_line_for_brace = true;
1989 result.push_str(&where_clause_str);
1991 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1992 Some((result, force_new_line_for_brace))
1995 #[derive(Copy, Clone)]
1996 struct WhereClauseOption {
1997 suppress_comma: bool, // Force no trailing comma
1998 snuggle: bool, // Do not insert newline before `where`
1999 compress_where: bool, // Try single line where clause instead of vertical layout
2002 impl WhereClauseOption {
2003 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2005 suppress_comma: suppress_comma,
2007 compress_where: false,
2011 pub fn compressed() -> WhereClauseOption {
2013 suppress_comma: true,
2015 compress_where: true,
2019 pub fn snuggled(current: &str) -> WhereClauseOption {
2021 suppress_comma: false,
2022 snuggle: trimmed_last_line_width(current) == 1,
2023 compress_where: false,
2029 context: &RewriteContext,
2031 explicit_self: Option<&ast::ExplicitSelf>,
2032 one_line_budget: usize,
2033 multi_line_budget: usize,
2038 generics_str_contains_newline: bool,
2039 ) -> Option<String> {
2040 let mut arg_item_strs = args.iter()
2041 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2042 .collect::<Option<Vec<_>>>()?;
2044 // Account for sugary self.
2045 // FIXME: the comment for the self argument is dropped. This is blocked
2046 // on rust issue #27522.
2047 let min_args = explicit_self
2048 .and_then(|explicit_self| {
2049 rewrite_explicit_self(explicit_self, args, context)
2051 .map_or(1, |self_str| {
2052 arg_item_strs[0] = self_str;
2056 // Comments between args.
2057 let mut arg_items = Vec::new();
2059 arg_items.push(ListItem::from_str(""));
2062 // FIXME(#21): if there are no args, there might still be a comment, but
2063 // without spans for the comment or parens, there is no chance of
2064 // getting it right. You also don't get to put a comment on self, unless
2066 if args.len() >= min_args || variadic {
2067 let comment_span_start = if min_args == 2 {
2068 let second_arg_start = if arg_has_pattern(&args[1]) {
2069 args[1].pat.span.lo()
2071 args[1].ty.span.lo()
2073 let reduced_span = mk_sp(span.lo(), second_arg_start);
2075 context.codemap.span_after_last(reduced_span, ",")
2080 enum ArgumentKind<'a> {
2081 Regular(&'a ast::Arg),
2085 let variadic_arg = if variadic {
2086 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2087 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2088 Some(ArgumentKind::Variadic(variadic_start))
2093 let more_items = itemize_list(
2095 args[min_args - 1..]
2097 .map(ArgumentKind::Regular)
2098 .chain(variadic_arg),
2101 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2102 ArgumentKind::Variadic(start) => start,
2105 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2106 ArgumentKind::Variadic(start) => start + BytePos(3),
2109 ArgumentKind::Regular(..) => None,
2110 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2117 arg_items.extend(more_items);
2120 let fits_in_one_line = !generics_str_contains_newline
2121 && (arg_items.is_empty()
2122 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2124 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2125 item.item = Some(arg);
2128 let last_line_ends_with_comment = arg_items
2131 .and_then(|item| item.post_comment.as_ref())
2132 .map_or(false, |s| s.trim().starts_with("//"));
2134 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2135 IndentStyle::Block if fits_in_one_line => {
2136 (indent.block_indent(context.config), SeparatorTactic::Never)
2138 IndentStyle::Block => (
2139 indent.block_indent(context.config),
2140 context.config.trailing_comma(),
2142 IndentStyle::Visual if last_line_ends_with_comment => {
2143 (arg_indent, context.config.trailing_comma())
2145 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2148 let tactic = definitive_tactic(
2150 context.config.fn_args_density().to_list_tactic(),
2154 let budget = match tactic {
2155 DefinitiveListTactic::Horizontal => one_line_budget,
2156 _ => multi_line_budget,
2159 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2161 let fmt = ListFormatting {
2164 trailing_separator: if variadic {
2165 SeparatorTactic::Never
2169 separator_place: SeparatorPlace::Back,
2170 shape: Shape::legacy(budget, indent),
2171 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2172 preserve_newline: true,
2173 config: context.config,
2176 write_list(&arg_items, &fmt)
2179 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2180 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2181 ident.node != symbol::keywords::Invalid.ident()
2187 fn compute_budgets_for_args(
2188 context: &RewriteContext,
2192 newline_brace: bool,
2194 force_vertical_layout: bool,
2195 ) -> Option<((usize, usize, Indent))> {
2197 "compute_budgets_for_args {} {:?}, {}, {}",
2203 // Try keeping everything on the same line.
2204 if !result.contains('\n') && !force_vertical_layout {
2205 // 2 = `()`, 3 = `() `, space is before ret_string.
2206 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2207 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2217 let one_line_budget = context.budget(used_space);
2219 if one_line_budget > 0 {
2221 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2222 IndentStyle::Block => {
2223 let indent = indent.block_indent(context.config);
2224 (indent, context.budget(indent.width() + 1))
2226 IndentStyle::Visual => {
2227 let indent = indent + result.len() + 1;
2228 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2229 (indent, context.budget(multi_line_overhead))
2233 return Some((one_line_budget, multi_line_budget, indent));
2237 // Didn't work. we must force vertical layout and put args on a newline.
2238 let new_indent = indent.block_indent(context.config);
2239 let used_space = match context.config.fn_args_layout() {
2241 IndentStyle::Block => new_indent.width() + 1,
2242 // Account for `)` and possibly ` {`.
2243 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2245 Some((0, context.budget(used_space), new_indent))
2248 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2249 match (config.fn_brace_style(), config.where_density()) {
2250 (BraceStyle::AlwaysNextLine, _) => true,
2251 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2252 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2253 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2258 fn rewrite_generics(
2259 context: &RewriteContext,
2260 generics: &ast::Generics,
2263 ) -> Option<String> {
2264 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2265 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2266 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2267 rewrite_generics_inner(context, generics, g_shape, 0, span)
2271 fn rewrite_generics_inner(
2272 context: &RewriteContext,
2273 generics: &ast::Generics,
2275 one_line_width: usize,
2277 ) -> Option<String> {
2278 // FIXME: convert bounds to where clauses where they get too big or if
2279 // there is a where clause at all.
2282 enum GenericsArg<'a> {
2283 Lifetime(&'a ast::LifetimeDef),
2284 TyParam(&'a ast::TyParam),
2286 impl<'a> Rewrite for GenericsArg<'a> {
2287 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2289 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2290 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2294 impl<'a> Spanned for GenericsArg<'a> {
2295 fn span(&self) -> Span {
2297 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2298 GenericsArg::TyParam(ref ty) => ty.span(),
2303 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2304 return Some(String::new());
2307 let generics_args = generics
2310 .map(|lt| GenericsArg::Lifetime(lt))
2311 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2312 let items = itemize_list(
2316 |arg| arg.span().lo(),
2317 |arg| arg.span().hi(),
2318 |arg| arg.rewrite(context, shape),
2319 context.codemap.span_after(span, "<"),
2323 format_generics_item_list(context, items, shape, one_line_width)
2326 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2327 match config.generics_indent() {
2328 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2329 IndentStyle::Block => {
2333 .block_indent(config.tab_spaces())
2334 .with_max_width(config)
2340 pub fn format_generics_item_list<I>(
2341 context: &RewriteContext,
2344 one_line_budget: usize,
2347 I: Iterator<Item = ListItem>,
2349 let item_vec = items.collect::<Vec<_>>();
2351 let tactic = definitive_tactic(
2353 ListTactic::HorizontalVertical,
2357 let fmt = ListFormatting {
2360 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2361 SeparatorTactic::Never
2363 context.config.trailing_comma()
2365 separator_place: SeparatorPlace::Back,
2367 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2368 preserve_newline: true,
2369 config: context.config,
2372 let list_str = write_list(&item_vec, &fmt)?;
2374 Some(wrap_generics_with_angle_brackets(
2381 pub fn wrap_generics_with_angle_brackets(
2382 context: &RewriteContext,
2384 list_offset: Indent,
2386 if context.config.generics_indent() == IndentStyle::Block
2387 && (list_str.contains('\n') || list_str.ends_with(','))
2391 list_offset.to_string(context.config),
2394 .block_unindent(context.config)
2395 .to_string(context.config)
2397 } else if context.config.spaces_within_angle_brackets() {
2398 format!("< {} >", list_str)
2400 format!("<{}>", list_str)
2404 fn rewrite_trait_bounds(
2405 context: &RewriteContext,
2406 type_param_bounds: &ast::TyParamBounds,
2408 ) -> Option<String> {
2409 let bounds: &[_] = type_param_bounds;
2411 if bounds.is_empty() {
2412 return Some(String::new());
2414 let bound_str = bounds
2416 .map(|ty_bound| ty_bound.rewrite(context, shape))
2417 .collect::<Option<Vec<_>>>()?;
2418 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2421 fn rewrite_where_clause_rfc_style(
2422 context: &RewriteContext,
2423 where_clause: &ast::WhereClause,
2426 span_end: Option<BytePos>,
2427 span_end_before_where: BytePos,
2428 where_clause_option: WhereClauseOption,
2429 ) -> Option<String> {
2430 let block_shape = shape.block().with_max_width(context.config);
2432 let (span_before, span_after) =
2433 missing_span_before_after_where(span_end_before_where, where_clause);
2434 let (comment_before, comment_after) =
2435 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2437 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2440 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2443 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2445 let clause_shape = clause_shape.sub_width(1)?;
2446 // each clause on one line, trailing comma (except if suppress_comma)
2447 let span_start = where_clause.predicates[0].span().lo();
2448 // If we don't have the start of the next span, then use the end of the
2449 // predicates, but that means we miss comments.
2450 let len = where_clause.predicates.len();
2451 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2452 let span_end = span_end.unwrap_or(end_of_preds);
2453 let items = itemize_list(
2455 where_clause.predicates.iter(),
2457 |pred| pred.span().lo(),
2458 |pred| pred.span().hi(),
2459 |pred| pred.rewrite(context, clause_shape),
2464 let comma_tactic = if where_clause_option.suppress_comma {
2465 SeparatorTactic::Never
2467 context.config.trailing_comma()
2470 let fmt = ListFormatting {
2471 tactic: DefinitiveListTactic::Vertical,
2473 trailing_separator: comma_tactic,
2474 separator_place: SeparatorPlace::Back,
2475 shape: clause_shape,
2476 ends_with_newline: true,
2477 preserve_newline: true,
2478 config: context.config,
2480 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2482 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2485 format!("\n{}", shape.indent.to_string(context.config))
2487 let newline_before_where = comment_separator(&comment_before, shape);
2488 let newline_after_where = comment_separator(&comment_after, clause_shape);
2491 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2492 && comment_after.is_empty() && !preds_str.contains('\n')
2493 && 6 + preds_str.len() <= shape.width
2497 format!("\n{}", clause_shape.indent.to_string(context.config))
2500 "{}{}{}where{}{}{}{}",
2503 newline_before_where,
2504 newline_after_where,
2511 fn rewrite_where_clause(
2512 context: &RewriteContext,
2513 where_clause: &ast::WhereClause,
2514 brace_style: BraceStyle,
2518 span_end: Option<BytePos>,
2519 span_end_before_where: BytePos,
2520 where_clause_option: WhereClauseOption,
2521 ) -> Option<String> {
2522 if where_clause.predicates.is_empty() {
2523 return Some(String::new());
2526 if context.config.where_style() == Style::Rfc {
2527 return rewrite_where_clause_rfc_style(
2533 span_end_before_where,
2534 where_clause_option,
2538 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2540 let offset = match context.config.where_pred_indent() {
2541 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2542 // 6 = "where ".len()
2543 IndentStyle::Visual => shape.indent + extra_indent + 6,
2545 // FIXME: if where_pred_indent != Visual, then the budgets below might
2546 // be out by a char or two.
2548 let budget = context.config.max_width() - offset.width();
2549 let span_start = where_clause.predicates[0].span().lo();
2550 // If we don't have the start of the next span, then use the end of the
2551 // predicates, but that means we miss comments.
2552 let len = where_clause.predicates.len();
2553 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2554 let span_end = span_end.unwrap_or(end_of_preds);
2555 let items = itemize_list(
2557 where_clause.predicates.iter(),
2559 |pred| pred.span().lo(),
2560 |pred| pred.span().hi(),
2561 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2566 let item_vec = items.collect::<Vec<_>>();
2567 // FIXME: we don't need to collect here if the where_layout isn't
2568 // HorizontalVertical.
2569 let tactic = definitive_tactic(
2571 context.config.where_layout(),
2576 let mut comma_tactic = context.config.trailing_comma();
2577 // Kind of a hack because we don't usually have trailing commas in where clauses.
2578 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2579 comma_tactic = SeparatorTactic::Never;
2582 let fmt = ListFormatting {
2585 trailing_separator: comma_tactic,
2586 separator_place: SeparatorPlace::Back,
2587 shape: Shape::legacy(budget, offset),
2588 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2589 preserve_newline: true,
2590 config: context.config,
2592 let preds_str = write_list(&item_vec, &fmt)?;
2594 let end_length = if terminator == "{" {
2595 // If the brace is on the next line we don't need to count it otherwise it needs two
2598 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2599 BraceStyle::PreferSameLine => 2,
2601 } else if terminator == "=" {
2606 if density == Density::Tall || preds_str.contains('\n')
2607 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2611 (shape.indent + extra_indent).to_string(context.config),
2615 Some(format!(" where {}", preds_str))
2619 fn missing_span_before_after_where(
2620 before_item_span_end: BytePos,
2621 where_clause: &ast::WhereClause,
2623 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2625 let pos_after_where = where_clause.span.lo() + BytePos(5);
2626 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2627 (missing_span_before, missing_span_after)
2630 fn rewrite_comments_before_after_where(
2631 context: &RewriteContext,
2632 span_before_where: Span,
2633 span_after_where: Span,
2635 ) -> Option<(String, String)> {
2636 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2637 let after_comment = rewrite_missing_comment(
2639 shape.block_indent(context.config.tab_spaces()),
2642 Some((before_comment, after_comment))
2645 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2646 format!("{}{}{}", format_visibility(vis), item_name, ident)
2650 context: &RewriteContext,
2651 generics: &ast::Generics,
2654 brace_style: BraceStyle,
2655 force_same_line_brace: bool,
2659 ) -> Option<String> {
2660 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2661 let mut result = rewrite_generics(context, generics, shape, span)?;
2663 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2664 let budget = context.budget(last_line_used_width(&result, offset.width()));
2665 let option = WhereClauseOption::snuggled(&result);
2666 let where_clause_str = rewrite_where_clause(
2668 &generics.where_clause,
2670 Shape::legacy(budget, offset.block_only()),
2677 result.push_str(&where_clause_str);
2678 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2679 || (generics.where_clause.predicates.is_empty()
2680 && trimmed_last_line_width(&result) == 1)
2682 force_same_line_brace || trimmed_last_line_width(&result) == 1
2683 || brace_style != BraceStyle::AlwaysNextLine
2685 let total_used_width = last_line_used_width(&result, used_width);
2686 let remaining_budget = context.budget(total_used_width);
2687 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2688 // and hence we take the closer into account as well for one line budget.
2689 // We assume that the closer has the same length as the opener.
2690 let overhead = if force_same_line_brace {
2691 1 + opener.len() + opener.len()
2695 let forbid_same_line_brace = overhead > remaining_budget;
2696 if !forbid_same_line_brace && same_line_brace {
2700 result.push_str(&offset.block_only().to_string(context.config));
2702 result.push_str(opener);
2707 impl Rewrite for ast::ForeignItem {
2708 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2709 let attrs_str = self.attrs.rewrite(context, shape)?;
2710 // Drop semicolon or it will be interpreted as comment.
2711 // FIXME: this may be a faulty span from libsyntax.
2712 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2714 let item_str = match self.node {
2715 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2719 &FnSig::new(fn_decl, generics, self.vis.clone()),
2723 ).map(|(s, _)| format!("{};", s)),
2724 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2725 // FIXME(#21): we're dropping potential comments in between the
2726 // function keywords here.
2727 let vis = format_visibility(&self.vis);
2728 let mut_str = if is_mutable { "mut " } else { "" };
2729 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2731 let shape = shape.sub_width(1)?;
2732 ty.rewrite(context, shape).map(|ty_str| {
2733 // 1 = space between prefix and type.
2734 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2737 let nested_indent = shape.indent.block_indent(context.config);
2738 format!("\n{}", nested_indent.to_string(context.config))
2740 format!("{}{}{};", prefix, sep, ty_str)
2743 // FIXME(#2097) support extern types.
2744 ast::ForeignItemKind::Ty => unimplemented!(),
2747 let missing_span = if self.attrs.is_empty() {
2748 mk_sp(self.span.lo(), self.span.lo())
2750 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2752 combine_strs_with_missing_comments(