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 {
546 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
547 if one_line_width <= shape.width {
548 format!("{} = {}", field.node.name, self.snippet(expr.span))
555 .block_indent(self.config)
556 .to_string(self.config),
557 self.snippet(expr.span)
561 String::from(field.node.name.to_string())
565 let attrs_extendable = attrs_str.is_empty()
566 || (context.config.attributes_on_same_line_as_variant()
567 && is_attributes_extendable(&attrs_str));
568 combine_strs_with_missing_comments(
580 context: &RewriteContext,
583 where_span_end: Option<BytePos>,
584 ) -> Option<String> {
585 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
586 let mut result = String::with_capacity(128);
587 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
588 let indent_str = offset.to_string(context.config);
589 let sep = format!("\n{}", &indent_str);
590 result.push_str(&ref_and_type);
592 let where_budget = if result.contains('\n') {
593 context.config.max_width()
595 context.budget(last_line_width(&result))
597 let option = WhereClauseOption::snuggled(&ref_and_type);
598 let where_clause_str = rewrite_where_clause(
600 &generics.where_clause,
601 context.config.item_brace_style(),
602 Shape::legacy(where_budget, offset.block_only()),
603 context.config.where_density(),
610 // If there is no where clause, we may have missing comments between the trait name and
611 // the opening brace.
612 if generics.where_clause.predicates.is_empty() {
613 if let Some(hi) = where_span_end {
614 match recover_missing_comment_in_span(
615 mk_sp(self_ty.span.hi(), hi),
616 Shape::indented(offset, context.config),
618 last_line_width(&result),
620 Some(ref missing_comment) if !missing_comment.is_empty() => {
621 result.push_str(missing_comment);
628 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
629 result.push_str(&where_clause_str);
630 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
631 result.push_str(&format!("{}{{{}}}", &sep, &sep));
633 result.push_str(" {}");
638 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
640 let width = offset.block_indent + context.config.tab_spaces() - 1;
641 let where_indent = Indent::new(0, width);
642 result.push_str(&where_indent.to_string(context.config));
644 result.push_str(&where_clause_str);
646 match context.config.item_brace_style() {
647 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
648 BraceStyle::AlwaysNextLine => result.push_str(&sep),
649 BraceStyle::PreferSameLine => result.push(' '),
650 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
651 result.push_str(&sep);
659 let snippet = context.snippet(item.span);
660 let open_pos = snippet.find_uncommented("{")? + 1;
662 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
663 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
664 visitor.block_indent = offset.block_only().block_indent(context.config);
665 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
667 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
669 visitor.visit_impl_item(item);
672 visitor.format_missing(item.span.hi() - BytePos(1));
674 let inner_indent_str = visitor.block_indent.to_string(context.config);
675 let outer_indent_str = offset.block_only().to_string(context.config);
678 result.push_str(&inner_indent_str);
679 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
681 result.push_str(&outer_indent_str);
684 if result.chars().last().unwrap() == '{' {
685 result.push_str(&sep);
695 fn is_impl_single_line(
696 context: &RewriteContext,
699 where_clause_str: &str,
702 let snippet = context.snippet(item.span);
703 let open_pos = snippet.find_uncommented("{")? + 1;
706 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
707 && result.len() + where_clause_str.len() <= context.config.max_width()
708 && !contains_comment(&snippet[open_pos..]),
712 fn format_impl_ref_and_type(
713 context: &RewriteContext,
716 ) -> Option<String> {
717 if let ast::ItemKind::Impl(
727 let mut result = String::with_capacity(128);
729 result.push_str(&format_visibility(&item.vis));
730 result.push_str(format_defaultness(defaultness));
731 result.push_str(format_unsafety(unsafety));
732 result.push_str("impl");
734 let lo = context.codemap.span_after(item.span, "impl");
735 let hi = match *trait_ref {
736 Some(ref tr) => tr.path.span.lo(),
737 None => self_ty.span.lo(),
739 let shape = generics_shape_from_config(
741 Shape::indented(offset + last_line_width(&result), context.config),
744 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
746 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
748 let polarity_str = if polarity == ast::ImplPolarity::Negative {
754 if let Some(ref trait_ref) = *trait_ref {
755 let result_len = result.len();
756 if let Some(trait_ref_str) = rewrite_trait_ref(
765 result.push_str(&trait_ref_str);
768 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
769 result.push_str(&rewrite_trait_ref(
780 result.push_str(&generics_str);
783 // Try to put the self type in a single line.
785 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
786 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
787 // If there is no where clause adapt budget for type formatting to take space and curly
788 // brace into account.
789 match context.config.item_brace_style() {
790 BraceStyle::AlwaysNextLine => 0,
796 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
797 // 1 = space before the type.
798 let budget = context.budget(used_space + 1);
799 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
800 if !self_ty_str.contains('\n') {
801 if trait_ref.is_some() {
802 result.push_str(" for ");
806 result.push_str(&self_ty_str);
811 // Couldn't fit the self type on a single line, put it on a new line.
813 // Add indentation of one additional tab.
814 let new_line_offset = offset.block_indent(context.config);
815 result.push_str(&new_line_offset.to_string(context.config));
816 if trait_ref.is_some() {
817 result.push_str("for ");
819 let budget = context.budget(last_line_width(&result));
820 let type_offset = match context.config.where_style() {
821 Style::Legacy => new_line_offset + trait_ref_overhead,
822 Style::Rfc => new_line_offset,
824 result.push_str(&*self_ty
825 .rewrite(context, Shape::legacy(budget, type_offset))?);
832 fn rewrite_trait_ref(
833 context: &RewriteContext,
834 trait_ref: &ast::TraitRef,
840 ) -> Option<String> {
841 // 1 = space between generics and trait_ref
842 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
843 let shape = Shape::indented(offset + used_space, context.config);
844 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
845 if !(retry && trait_ref_str.contains('\n')) {
854 // We could not make enough space for trait_ref, so put it on new line.
856 let offset = offset.block_indent(context.config);
857 let shape = Shape::indented(offset, context.config);
858 let trait_ref_str = trait_ref.rewrite(context, shape)?;
862 &offset.to_string(context.config),
871 pub fn format_struct(
872 context: &RewriteContext,
875 vis: &ast::Visibility,
876 struct_def: &ast::VariantData,
877 generics: Option<&ast::Generics>,
880 one_line_width: Option<usize>,
881 ) -> Option<String> {
883 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
884 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
894 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
908 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
909 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
912 let mut result = String::with_capacity(128);
913 let header = format!(
915 format_visibility(&item.vis),
916 format_unsafety(unsafety),
920 result.push_str(&header);
922 let body_lo = context.codemap.span_after(item.span, "{");
924 let shape = Shape::indented(offset + last_line_width(&result), context.config);
926 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
927 result.push_str(&generics_str);
929 let trait_bound_str = rewrite_trait_bounds(
932 Shape::indented(offset, context.config),
934 // If the trait, generics, and trait bound cannot fit on the same line,
935 // put the trait bounds on an indented new line
936 if offset.width() + last_line_width(&result) + trait_bound_str.len()
937 > context.config.comment_width()
940 let trait_indent = offset.block_only().block_indent(context.config);
941 result.push_str(&trait_indent.to_string(context.config));
943 result.push_str(&trait_bound_str);
945 let has_body = !trait_items.is_empty();
947 let where_density = if (context.config.where_density() == Density::Compressed
948 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
949 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
950 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
951 && !result.contains('\n'))
958 let where_budget = context.budget(last_line_width(&result));
959 let pos_before_where = if type_param_bounds.is_empty() {
960 generics.where_clause.span.lo()
962 type_param_bounds[type_param_bounds.len() - 1].span().hi()
964 let option = WhereClauseOption::snuggled(&generics_str);
965 let where_clause_str = rewrite_where_clause(
967 &generics.where_clause,
968 context.config.item_brace_style(),
969 Shape::legacy(where_budget, offset.block_only()),
976 // If the where clause cannot fit on the same line,
977 // put the where clause on a new line
978 if !where_clause_str.contains('\n')
979 && last_line_width(&result) + where_clause_str.len() + offset.width()
980 > context.config.comment_width()
983 let width = offset.block_indent + context.config.tab_spaces() - 1;
984 let where_indent = Indent::new(0, width);
985 result.push_str(&where_indent.to_string(context.config));
987 result.push_str(&where_clause_str);
989 if generics.where_clause.predicates.is_empty() {
990 let item_snippet = context.snippet(item.span);
991 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
993 let comment_hi = body_lo - BytePos(1);
994 let comment_lo = item.span.lo() + BytePos(lo as u32);
995 if comment_lo < comment_hi {
996 match recover_missing_comment_in_span(
997 mk_sp(comment_lo, comment_hi),
998 Shape::indented(offset, context.config),
1000 last_line_width(&result),
1002 Some(ref missing_comment) if !missing_comment.is_empty() => {
1003 result.push_str(missing_comment);
1011 match context.config.item_brace_style() {
1012 _ if last_line_contains_single_line_comment(&result) => {
1014 result.push_str(&offset.to_string(context.config));
1016 BraceStyle::AlwaysNextLine => {
1018 result.push_str(&offset.to_string(context.config));
1020 BraceStyle::PreferSameLine => result.push(' '),
1021 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1022 && (!trait_items.is_empty() || result.contains('\n'))
1025 result.push_str(&offset.to_string(context.config));
1032 let snippet = context.snippet(item.span);
1033 let open_pos = snippet.find_uncommented("{")? + 1;
1035 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1036 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1037 visitor.block_indent = offset.block_only().block_indent(context.config);
1038 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1040 for item in trait_items {
1041 visitor.visit_trait_item(item);
1044 visitor.format_missing(item.span.hi() - BytePos(1));
1046 let inner_indent_str = visitor.block_indent.to_string(context.config);
1047 let outer_indent_str = offset.block_only().to_string(context.config);
1050 result.push_str(&inner_indent_str);
1051 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1053 result.push_str(&outer_indent_str);
1054 } else if result.contains('\n') {
1065 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1066 format!("{};", format_header(item_name, ident, vis))
1069 pub fn format_struct_struct(
1070 context: &RewriteContext,
1073 vis: &ast::Visibility,
1074 fields: &[ast::StructField],
1075 generics: Option<&ast::Generics>,
1078 one_line_width: Option<usize>,
1079 ) -> Option<String> {
1080 let mut result = String::with_capacity(1024);
1082 let header_str = format_header(item_name, ident, vis);
1083 result.push_str(&header_str);
1085 let body_lo = context.codemap.span_after(span, "{");
1087 let generics_str = match generics {
1088 Some(g) => format_generics(
1093 context.config.item_brace_style(),
1096 mk_sp(span.lo(), body_lo),
1097 last_line_width(&result),
1100 // 3 = ` {}`, 2 = ` {`.
1101 let overhead = if fields.is_empty() { 3 } else { 2 };
1102 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1103 && !fields.is_empty())
1104 || context.config.max_width() < overhead + result.len()
1106 format!("\n{}{{", offset.block_only().to_string(context.config))
1113 let overhead = if fields.is_empty() { 1 } else { 0 };
1114 let total_width = result.len() + generics_str.len() + overhead;
1115 if !generics_str.is_empty() && !generics_str.contains('\n')
1116 && total_width > context.config.max_width()
1119 result.push_str(&offset.to_string(context.config));
1120 result.push_str(generics_str.trim_left());
1122 result.push_str(&generics_str);
1125 if fields.is_empty() {
1126 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1127 if snippet.trim().is_empty() {
1129 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1131 result.push_str(snippet.trim_right());
1133 result.push_str(&offset.to_string(context.config));
1135 result.push_str(&snippet);
1138 return Some(result);
1142 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1143 let one_line_budget =
1144 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1146 let items_str = rewrite_with_alignment(
1149 Shape::indented(offset, context.config),
1150 mk_sp(body_lo, span.hi()),
1154 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1155 Some(format!("{} {} }}", result, items_str))
1161 .block_indent(context.config)
1162 .to_string(context.config),
1164 offset.to_string(context.config)
1169 fn format_tuple_struct(
1170 context: &RewriteContext,
1173 vis: &ast::Visibility,
1174 fields: &[ast::StructField],
1175 generics: Option<&ast::Generics>,
1178 ) -> Option<String> {
1179 let mut result = String::with_capacity(1024);
1181 let header_str = format_header(item_name, ident, vis);
1182 result.push_str(&header_str);
1184 let body_lo = if fields.is_empty() {
1185 context.codemap.span_after(span, "(")
1189 let body_hi = if fields.is_empty() {
1190 context.codemap.span_after(span, ")")
1192 // This is a dirty hack to work around a missing `)` from the span of the last field.
1193 let last_arg_span = fields[fields.len() - 1].span;
1194 if context.snippet(last_arg_span).ends_with(')') {
1199 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1203 let where_clause_str = match generics {
1205 let budget = context.budget(last_line_width(&header_str));
1206 let shape = Shape::legacy(budget, offset);
1207 let g_span = mk_sp(span.lo(), body_lo);
1208 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1209 result.push_str(&generics_str);
1211 let where_budget = context.budget(last_line_width(&result));
1212 let option = WhereClauseOption::new(true, false);
1213 rewrite_where_clause(
1215 &generics.where_clause,
1216 context.config.item_brace_style(),
1217 Shape::legacy(where_budget, offset.block_only()),
1218 Density::Compressed,
1225 None => "".to_owned(),
1228 if fields.is_empty() {
1230 let used_width = last_line_used_width(&result, offset.width()) + 3;
1231 if used_width > context.config.max_width() {
1233 result.push_str(&offset
1234 .block_indent(context.config)
1235 .to_string(context.config))
1238 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1239 if snippet.is_empty() {
1241 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1242 result.push_str(snippet.trim_right());
1244 result.push_str(&offset.to_string(context.config));
1246 result.push_str(&snippet);
1251 let body = rewrite_call_inner(
1254 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1256 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1257 context.config.fn_call_width(),
1260 result.push_str(&body);
1263 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1264 && (result.contains('\n')
1265 || offset.block_indent + result.len() + where_clause_str.len() + 1
1266 > context.config.max_width())
1268 // We need to put the where clause on a new line, but we didn't
1269 // know that earlier, so the where clause will not be indented properly.
1271 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1272 .to_string(context.config));
1274 result.push_str(&where_clause_str);
1279 pub fn rewrite_type_alias(
1280 context: &RewriteContext,
1284 generics: &ast::Generics,
1285 vis: &ast::Visibility,
1287 ) -> Option<String> {
1288 let mut result = String::with_capacity(128);
1290 result.push_str(&format_visibility(vis));
1291 result.push_str("type ");
1292 result.push_str(&ident.to_string());
1295 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1296 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1297 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1298 result.push_str(&generics_str);
1300 let where_budget = context.budget(last_line_width(&result));
1301 let option = WhereClauseOption::snuggled(&result);
1302 let where_clause_str = rewrite_where_clause(
1304 &generics.where_clause,
1305 context.config.item_brace_style(),
1306 Shape::legacy(where_budget, indent),
1307 context.config.where_density(),
1313 result.push_str(&where_clause_str);
1314 if where_clause_str.is_empty() {
1315 result.push_str(" = ");
1317 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1320 let line_width = last_line_width(&result);
1321 // This checked_sub may fail as the extra space after '=' is not taken into account
1322 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1323 let budget = context.budget(indent.width() + line_width + ";".len());
1324 let type_indent = indent + line_width;
1325 // Try to fit the type on the same line
1326 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1328 // The line was too short, try to put the type on the next line
1330 // Remove the space after '='
1332 let type_indent = indent.block_indent(context.config);
1334 result.push_str(&type_indent.to_string(context.config));
1335 let budget = context.budget(type_indent.width() + ";".len());
1336 ty.rewrite(context, Shape::legacy(budget, type_indent))
1338 result.push_str(&ty_str);
1339 result.push_str(";");
1343 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1345 if config.space_before_type_annotation() {
1350 if config.space_after_type_annotation_colon() {
1358 pub fn rewrite_struct_field_prefix(
1359 context: &RewriteContext,
1360 field: &ast::StructField,
1361 ) -> Option<String> {
1362 let vis = format_visibility(&field.vis);
1363 let type_annotation_spacing = type_annotation_spacing(context.config);
1364 Some(match field.ident {
1365 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1366 None => format!("{}", vis),
1370 impl Rewrite for ast::StructField {
1371 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1372 rewrite_struct_field(context, self, shape, 0)
1376 pub fn rewrite_struct_field(
1377 context: &RewriteContext,
1378 field: &ast::StructField,
1380 lhs_max_width: usize,
1381 ) -> Option<String> {
1382 if contains_skip(&field.attrs) {
1383 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1386 let type_annotation_spacing = type_annotation_spacing(context.config);
1387 let prefix = rewrite_struct_field_prefix(context, field)?;
1389 let attrs_str = field.attrs.rewrite(context, shape)?;
1390 let attrs_extendable = attrs_str.is_empty()
1391 || (context.config.attributes_on_same_line_as_field()
1392 && is_attributes_extendable(&attrs_str));
1393 let missing_span = if field.attrs.is_empty() {
1394 mk_sp(field.span.lo(), field.span.lo())
1396 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1398 let mut spacing = String::from(if field.ident.is_some() {
1399 type_annotation_spacing.1
1403 // Try to put everything on a single line.
1404 let attr_prefix = combine_strs_with_missing_comments(
1412 let overhead = last_line_width(&attr_prefix);
1413 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1414 for _ in 0..lhs_offset {
1417 // In this extreme case we will be missing a space betweeen an attribute and a field.
1418 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1421 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1422 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1423 if !ty.contains('\n') {
1424 return Some(attr_prefix + &spacing + ty);
1428 // We must use multiline.
1429 let new_shape = shape.with_max_width(context.config);
1430 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1432 let field_str = if prefix.is_empty() {
1434 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1435 prefix + " " + &ty_rewritten
1437 let type_offset = shape.indent.block_indent(context.config);
1438 let nested_shape = Shape::indented(type_offset, context.config);
1439 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1440 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1442 combine_strs_with_missing_comments(
1452 pub fn rewrite_static(
1454 vis: &ast::Visibility,
1457 mutability: ast::Mutability,
1458 expr_opt: Option<&ptr::P<ast::Expr>>,
1461 context: &RewriteContext,
1462 ) -> Option<String> {
1463 let colon = colon_spaces(
1464 context.config.space_before_type_annotation(),
1465 context.config.space_after_type_annotation_colon(),
1467 let prefix = format!(
1469 format_visibility(vis),
1471 format_mutability(mutability),
1476 let ty_str = ty.rewrite(
1478 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1481 if let Some(expr) = expr_opt {
1482 let lhs = format!("{}{} =", prefix, ty_str);
1484 let remaining_width = context.budget(offset.block_indent + 1);
1489 Shape::legacy(remaining_width, offset.block_only()),
1490 ).and_then(|res| recover_comment_removed(res, span, context))
1491 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1493 Some(format!("{}{};", prefix, ty_str))
1497 pub fn rewrite_associated_type(
1499 ty_opt: Option<&ptr::P<ast::Ty>>,
1500 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1501 context: &RewriteContext,
1503 ) -> Option<String> {
1504 let prefix = format!("type {}", ident);
1506 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1508 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1509 let bounds: &[_] = ty_param_bounds;
1510 let bound_str = bounds
1512 .map(|ty_bound| ty_bound.rewrite(context, shape))
1513 .collect::<Option<Vec<_>>>()?;
1514 if !bounds.is_empty() {
1515 format!(": {}", join_bounds(context, shape, &bound_str))
1523 if let Some(ty) = ty_opt {
1524 let ty_str = ty.rewrite(
1527 context.budget(indent.block_indent + prefix.len() + 2),
1528 indent.block_only(),
1531 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1533 Some(format!("{}{};", prefix, type_bounds_str))
1537 pub fn rewrite_associated_impl_type(
1539 defaultness: ast::Defaultness,
1540 ty_opt: Option<&ptr::P<ast::Ty>>,
1541 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1542 context: &RewriteContext,
1544 ) -> Option<String> {
1545 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1548 ast::Defaultness::Default => Some(format!("default {}", result)),
1553 impl Rewrite for ast::FunctionRetTy {
1554 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1556 ast::FunctionRetTy::Default(_) => Some(String::new()),
1557 ast::FunctionRetTy::Ty(ref ty) => {
1558 let inner_width = shape.width.checked_sub(3)?;
1559 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1560 .map(|r| format!("-> {}", r))
1566 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1568 ast::TyKind::Infer => {
1569 let original = context.snippet(ty.span);
1576 impl Rewrite for ast::Arg {
1577 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1578 if is_named_arg(self) {
1579 let mut result = self.pat
1580 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1582 if !is_empty_infer(context, &*self.ty) {
1583 if context.config.space_before_type_annotation() {
1584 result.push_str(" ");
1586 result.push_str(":");
1587 if context.config.space_after_type_annotation_colon() {
1588 result.push_str(" ");
1590 let overhead = last_line_width(&result);
1591 let max_width = shape.width.checked_sub(overhead)?;
1592 let ty_str = self.ty
1593 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1594 result.push_str(&ty_str);
1599 self.ty.rewrite(context, shape)
1604 fn rewrite_explicit_self(
1605 explicit_self: &ast::ExplicitSelf,
1607 context: &RewriteContext,
1608 ) -> Option<String> {
1609 match explicit_self.node {
1610 ast::SelfKind::Region(lt, m) => {
1611 let mut_str = format_mutability(m);
1614 let lifetime_str = l.rewrite(
1616 Shape::legacy(context.config.max_width(), Indent::empty()),
1618 Some(format!("&{} {}self", lifetime_str, mut_str))
1620 None => Some(format!("&{}self", mut_str)),
1623 ast::SelfKind::Explicit(ref ty, _) => {
1624 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1626 let mutability = explicit_self_mutability(&args[0]);
1627 let type_str = ty.rewrite(
1629 Shape::legacy(context.config.max_width(), Indent::empty()),
1634 format_mutability(mutability),
1638 ast::SelfKind::Value(_) => {
1639 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1641 let mutability = explicit_self_mutability(&args[0]);
1643 Some(format!("{}self", format_mutability(mutability)))
1648 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1649 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1650 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1651 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1658 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1659 if is_named_arg(arg) {
1666 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1668 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1669 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1670 _ => arg.ty.span.hi(),
1674 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1675 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1676 ident.node != symbol::keywords::Invalid.ident()
1682 // Return type is (result, force_new_line_for_brace)
1684 context: &RewriteContext,
1689 newline_brace: bool,
1691 ) -> Option<(String, bool)> {
1692 let mut force_new_line_for_brace = false;
1694 let where_clause = &fn_sig.generics.where_clause;
1696 let mut result = String::with_capacity(1024);
1697 result.push_str(&fn_sig.to_str(context));
1700 result.push_str("fn ");
1701 result.push_str(&ident.to_string());
1704 let overhead = if has_body && !newline_brace {
1711 let used_width = last_line_used_width(&result, indent.width());
1712 let one_line_budget = context.budget(used_width + overhead);
1714 width: one_line_budget,
1718 let fd = fn_sig.decl;
1719 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1720 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1721 result.push_str(&generics_str);
1723 let snuggle_angle_bracket = generics_str
1726 .map_or(false, |l| l.trim_left().len() == 1);
1728 // Note that the width and indent don't really matter, we'll re-layout the
1729 // return type later anyway.
1730 let ret_str = fd.output
1731 .rewrite(context, Shape::indented(indent, context.config))?;
1733 let multi_line_ret_str = ret_str.contains('\n');
1734 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1737 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1748 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1754 // Check if vertical layout was forced.
1755 if one_line_budget == 0 {
1756 if snuggle_angle_bracket {
1758 } else if context.config.fn_args_paren_newline() {
1760 result.push_str(&arg_indent.to_string(context.config));
1761 if context.config.fn_args_layout() == IndentStyle::Visual {
1762 arg_indent = arg_indent + 1; // extra space for `(`
1766 result.push_str("(");
1767 if context.config.fn_args_layout() == IndentStyle::Visual {
1769 result.push_str(&arg_indent.to_string(context.config));
1775 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1779 // A conservative estimation, to goal is to be over all parens in generics
1780 let args_start = fn_sig
1784 .map_or(span.lo(), |tp| end_typaram(tp));
1785 let args_end = if fd.inputs.is_empty() {
1788 .span_after(mk_sp(args_start, span.hi()), ")")
1790 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1791 context.codemap.span_after(last_span, ")")
1793 let args_span = mk_sp(
1796 .span_after(mk_sp(args_start, span.hi()), "("),
1799 let arg_str = rewrite_args(
1802 fd.get_self().as_ref(),
1809 generics_str.contains('\n'),
1812 let put_args_in_block = match context.config.fn_args_layout() {
1813 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1815 } && !fd.inputs.is_empty();
1817 let mut args_last_line_contains_comment = false;
1818 if put_args_in_block {
1819 arg_indent = indent.block_indent(context.config);
1821 result.push_str(&arg_indent.to_string(context.config));
1822 result.push_str(&arg_str);
1824 result.push_str(&indent.to_string(context.config));
1827 result.push_str(&arg_str);
1828 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1829 // Put the closing brace on the next line if it overflows the max width.
1831 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1834 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1837 // If the last line of args contains comment, we cannot put the closing paren
1838 // on the same line.
1842 .map_or(false, |last_line| last_line.contains("//"))
1844 args_last_line_contains_comment = true;
1846 result.push_str(&arg_indent.to_string(context.config));
1852 if let ast::FunctionRetTy::Ty(..) = fd.output {
1853 let ret_should_indent = match context.config.fn_args_layout() {
1854 // If our args are block layout then we surely must have space.
1855 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1856 _ if args_last_line_contains_comment => false,
1857 _ if result.contains('\n') || multi_line_ret_str => true,
1859 // If the return type would push over the max width, then put the return type on
1860 // a new line. With the +1 for the signature length an additional space between
1861 // the closing parenthesis of the argument and the arrow '->' is considered.
1862 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1864 // If there is no where clause, take into account the space after the return type
1866 if where_clause.predicates.is_empty() {
1870 sig_length > context.config.max_width()
1873 let ret_indent = if ret_should_indent {
1874 let indent = match context.config.fn_return_indent() {
1875 ReturnIndent::WithWhereClause => indent + 4,
1876 // Aligning with non-existent args looks silly.
1877 _ if arg_str.is_empty() => {
1878 force_new_line_for_brace = true;
1881 // FIXME: we might want to check that using the arg indent
1882 // doesn't blow our budget, and if it does, then fallback to
1883 // the where clause indent.
1888 result.push_str(&indent.to_string(context.config));
1892 Indent::new(indent.block_indent, last_line_width(&result))
1895 if multi_line_ret_str || ret_should_indent {
1896 // Now that we know the proper indent and width, we need to
1897 // re-layout the return type.
1898 let ret_str = fd.output
1899 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1900 result.push_str(&ret_str);
1902 result.push_str(&ret_str);
1905 // Comment between return type and the end of the decl.
1906 let snippet_lo = fd.output.span().hi();
1907 if where_clause.predicates.is_empty() {
1908 let snippet_hi = span.hi();
1909 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1910 // Try to preserve the layout of the original snippet.
1911 let original_starts_with_newline = snippet
1913 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1914 let original_ends_with_newline = snippet
1915 .rfind(|c| c != ' ')
1916 .map_or(false, |i| snippet[i..].ends_with('\n'));
1917 let snippet = snippet.trim();
1918 if !snippet.is_empty() {
1919 result.push(if original_starts_with_newline {
1924 result.push_str(snippet);
1925 if original_ends_with_newline {
1926 force_new_line_for_brace = true;
1932 let should_compress_where = match context.config.where_density() {
1933 Density::Compressed => !result.contains('\n'),
1934 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1938 let pos_before_where = match fd.output {
1939 ast::FunctionRetTy::Default(..) => args_span.hi(),
1940 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1943 if where_clause.predicates.len() == 1 && should_compress_where {
1944 let budget = context.budget(last_line_used_width(&result, indent.width()));
1945 if let Some(where_clause_str) = rewrite_where_clause(
1948 context.config.fn_brace_style(),
1949 Shape::legacy(budget, indent),
1950 Density::Compressed,
1954 WhereClauseOption::compressed(),
1956 result.push_str(&where_clause_str);
1957 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1958 return Some((result, force_new_line_for_brace));
1962 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1963 let where_clause_str = rewrite_where_clause(
1966 context.config.fn_brace_style(),
1967 Shape::indented(indent, context.config),
1974 // If there are neither where clause nor return type, we may be missing comments between
1976 if where_clause_str.is_empty() {
1977 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1978 match recover_missing_comment_in_span(
1979 mk_sp(args_span.hi(), ret_span.hi()),
1982 last_line_width(&result),
1984 Some(ref missing_comment) if !missing_comment.is_empty() => {
1985 result.push_str(missing_comment);
1986 force_new_line_for_brace = true;
1993 result.push_str(&where_clause_str);
1995 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1996 Some((result, force_new_line_for_brace))
1999 #[derive(Copy, Clone)]
2000 struct WhereClauseOption {
2001 suppress_comma: bool, // Force no trailing comma
2002 snuggle: bool, // Do not insert newline before `where`
2003 compress_where: bool, // Try single line where clause instead of vertical layout
2006 impl WhereClauseOption {
2007 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2009 suppress_comma: suppress_comma,
2011 compress_where: false,
2015 pub fn compressed() -> WhereClauseOption {
2017 suppress_comma: true,
2019 compress_where: true,
2023 pub fn snuggled(current: &str) -> WhereClauseOption {
2025 suppress_comma: false,
2026 snuggle: trimmed_last_line_width(current) == 1,
2027 compress_where: false,
2033 context: &RewriteContext,
2035 explicit_self: Option<&ast::ExplicitSelf>,
2036 one_line_budget: usize,
2037 multi_line_budget: usize,
2042 generics_str_contains_newline: bool,
2043 ) -> Option<String> {
2044 let mut arg_item_strs = args.iter()
2046 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2048 .collect::<Option<Vec<_>>>()?;
2050 // Account for sugary self.
2051 // FIXME: the comment for the self argument is dropped. This is blocked
2052 // on rust issue #27522.
2053 let min_args = explicit_self
2054 .and_then(|explicit_self| {
2055 rewrite_explicit_self(explicit_self, args, context)
2057 .map_or(1, |self_str| {
2058 arg_item_strs[0] = self_str;
2062 // Comments between args.
2063 let mut arg_items = Vec::new();
2065 arg_items.push(ListItem::from_str(""));
2068 // FIXME(#21): if there are no args, there might still be a comment, but
2069 // without spans for the comment or parens, there is no chance of
2070 // getting it right. You also don't get to put a comment on self, unless
2072 if args.len() >= min_args || variadic {
2073 let comment_span_start = if min_args == 2 {
2074 let second_arg_start = if arg_has_pattern(&args[1]) {
2075 args[1].pat.span.lo()
2077 args[1].ty.span.lo()
2079 let reduced_span = mk_sp(span.lo(), second_arg_start);
2081 context.codemap.span_after_last(reduced_span, ",")
2086 enum ArgumentKind<'a> {
2087 Regular(&'a ast::Arg),
2091 let variadic_arg = if variadic {
2092 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2093 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2094 Some(ArgumentKind::Variadic(variadic_start))
2099 let more_items = itemize_list(
2101 args[min_args - 1..]
2103 .map(ArgumentKind::Regular)
2104 .chain(variadic_arg),
2107 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2108 ArgumentKind::Variadic(start) => start,
2111 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2112 ArgumentKind::Variadic(start) => start + BytePos(3),
2115 ArgumentKind::Regular(..) => None,
2116 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2123 arg_items.extend(more_items);
2126 let fits_in_one_line = !generics_str_contains_newline
2127 && (arg_items.is_empty()
2128 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2130 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2131 item.item = Some(arg);
2134 let last_line_ends_with_comment = arg_items
2137 .and_then(|item| item.post_comment.as_ref())
2138 .map_or(false, |s| s.trim().starts_with("//"));
2140 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2141 IndentStyle::Block if fits_in_one_line => {
2142 (indent.block_indent(context.config), SeparatorTactic::Never)
2144 IndentStyle::Block => (
2145 indent.block_indent(context.config),
2146 context.config.trailing_comma(),
2148 IndentStyle::Visual if last_line_ends_with_comment => {
2149 (arg_indent, context.config.trailing_comma())
2151 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2154 let tactic = definitive_tactic(
2156 context.config.fn_args_density().to_list_tactic(),
2160 let budget = match tactic {
2161 DefinitiveListTactic::Horizontal => one_line_budget,
2162 _ => multi_line_budget,
2165 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2167 let fmt = ListFormatting {
2170 trailing_separator: if variadic {
2171 SeparatorTactic::Never
2175 separator_place: SeparatorPlace::Back,
2176 shape: Shape::legacy(budget, indent),
2177 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2178 preserve_newline: true,
2179 config: context.config,
2182 write_list(&arg_items, &fmt)
2185 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2186 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2187 ident.node != symbol::keywords::Invalid.ident()
2193 fn compute_budgets_for_args(
2194 context: &RewriteContext,
2198 newline_brace: bool,
2200 force_vertical_layout: bool,
2201 ) -> Option<((usize, usize, Indent))> {
2203 "compute_budgets_for_args {} {:?}, {}, {}",
2209 // Try keeping everything on the same line.
2210 if !result.contains('\n') && !force_vertical_layout {
2211 // 2 = `()`, 3 = `() `, space is before ret_string.
2212 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2213 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2223 let one_line_budget = context.budget(used_space);
2225 if one_line_budget > 0 {
2227 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2228 IndentStyle::Block => {
2229 let indent = indent.block_indent(context.config);
2230 (indent, context.budget(indent.width() + 1))
2232 IndentStyle::Visual => {
2233 let indent = indent + result.len() + 1;
2234 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2235 (indent, context.budget(multi_line_overhead))
2239 return Some((one_line_budget, multi_line_budget, indent));
2243 // Didn't work. we must force vertical layout and put args on a newline.
2244 let new_indent = indent.block_indent(context.config);
2245 let used_space = match context.config.fn_args_layout() {
2247 IndentStyle::Block => new_indent.width() + 1,
2248 // Account for `)` and possibly ` {`.
2249 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2251 Some((0, context.budget(used_space), new_indent))
2254 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2255 match (config.fn_brace_style(), config.where_density()) {
2256 (BraceStyle::AlwaysNextLine, _) => true,
2257 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2258 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2259 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2264 fn rewrite_generics(
2265 context: &RewriteContext,
2266 generics: &ast::Generics,
2269 ) -> Option<String> {
2270 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2271 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2272 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2273 rewrite_generics_inner(context, generics, g_shape, 0, span)
2277 fn rewrite_generics_inner(
2278 context: &RewriteContext,
2279 generics: &ast::Generics,
2281 one_line_width: usize,
2283 ) -> Option<String> {
2284 // FIXME: convert bounds to where clauses where they get too big or if
2285 // there is a where clause at all.
2288 enum GenericsArg<'a> {
2289 Lifetime(&'a ast::LifetimeDef),
2290 TyParam(&'a ast::TyParam),
2292 impl<'a> Rewrite for GenericsArg<'a> {
2293 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2295 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2296 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2300 impl<'a> Spanned for GenericsArg<'a> {
2301 fn span(&self) -> Span {
2303 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2304 GenericsArg::TyParam(ref ty) => ty.span(),
2309 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2310 return Some(String::new());
2313 let generics_args = generics
2316 .map(|lt| GenericsArg::Lifetime(lt))
2317 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2318 let items = itemize_list(
2322 |arg| arg.span().lo(),
2323 |arg| arg.span().hi(),
2324 |arg| arg.rewrite(context, shape),
2325 context.codemap.span_after(span, "<"),
2329 format_generics_item_list(context, items, shape, one_line_width)
2332 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2333 match config.generics_indent() {
2334 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2335 IndentStyle::Block => {
2339 .block_indent(config.tab_spaces())
2340 .with_max_width(config)
2346 pub fn format_generics_item_list<I>(
2347 context: &RewriteContext,
2350 one_line_budget: usize,
2353 I: Iterator<Item = ListItem>,
2355 let item_vec = items.collect::<Vec<_>>();
2357 let tactic = definitive_tactic(
2359 ListTactic::HorizontalVertical,
2363 let fmt = ListFormatting {
2366 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2367 SeparatorTactic::Never
2369 context.config.trailing_comma()
2371 separator_place: SeparatorPlace::Back,
2373 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2374 preserve_newline: true,
2375 config: context.config,
2378 let list_str = write_list(&item_vec, &fmt)?;
2380 Some(wrap_generics_with_angle_brackets(
2387 pub fn wrap_generics_with_angle_brackets(
2388 context: &RewriteContext,
2390 list_offset: Indent,
2392 if context.config.generics_indent() == IndentStyle::Block
2393 && (list_str.contains('\n') || list_str.ends_with(','))
2397 list_offset.to_string(context.config),
2400 .block_unindent(context.config)
2401 .to_string(context.config)
2403 } else if context.config.spaces_within_angle_brackets() {
2404 format!("< {} >", list_str)
2406 format!("<{}>", list_str)
2410 fn rewrite_trait_bounds(
2411 context: &RewriteContext,
2412 type_param_bounds: &ast::TyParamBounds,
2414 ) -> Option<String> {
2415 let bounds: &[_] = type_param_bounds;
2417 if bounds.is_empty() {
2418 return Some(String::new());
2420 let bound_str = bounds
2422 .map(|ty_bound| ty_bound.rewrite(context, shape))
2423 .collect::<Option<Vec<_>>>()?;
2424 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2427 fn rewrite_where_clause_rfc_style(
2428 context: &RewriteContext,
2429 where_clause: &ast::WhereClause,
2432 span_end: Option<BytePos>,
2433 span_end_before_where: BytePos,
2434 where_clause_option: WhereClauseOption,
2435 ) -> Option<String> {
2436 let block_shape = shape.block().with_max_width(context.config);
2438 let (span_before, span_after) =
2439 missing_span_before_after_where(span_end_before_where, where_clause);
2440 let (comment_before, comment_after) =
2441 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2443 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2446 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2449 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2451 let clause_shape = clause_shape.sub_width(1)?;
2452 // each clause on one line, trailing comma (except if suppress_comma)
2453 let span_start = where_clause.predicates[0].span().lo();
2454 // If we don't have the start of the next span, then use the end of the
2455 // predicates, but that means we miss comments.
2456 let len = where_clause.predicates.len();
2457 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2458 let span_end = span_end.unwrap_or(end_of_preds);
2459 let items = itemize_list(
2461 where_clause.predicates.iter(),
2463 |pred| pred.span().lo(),
2464 |pred| pred.span().hi(),
2465 |pred| pred.rewrite(context, clause_shape),
2470 let comma_tactic = if where_clause_option.suppress_comma {
2471 SeparatorTactic::Never
2473 context.config.trailing_comma()
2476 let fmt = ListFormatting {
2477 tactic: DefinitiveListTactic::Vertical,
2479 trailing_separator: comma_tactic,
2480 separator_place: SeparatorPlace::Back,
2481 shape: clause_shape,
2482 ends_with_newline: true,
2483 preserve_newline: true,
2484 config: context.config,
2486 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2488 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2491 format!("\n{}", shape.indent.to_string(context.config))
2493 let newline_before_where = comment_separator(&comment_before, shape);
2494 let newline_after_where = comment_separator(&comment_after, clause_shape);
2497 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2498 && comment_after.is_empty() && !preds_str.contains('\n')
2499 && 6 + preds_str.len() <= shape.width
2503 format!("\n{}", clause_shape.indent.to_string(context.config))
2506 "{}{}{}where{}{}{}{}",
2509 newline_before_where,
2510 newline_after_where,
2517 fn rewrite_where_clause(
2518 context: &RewriteContext,
2519 where_clause: &ast::WhereClause,
2520 brace_style: BraceStyle,
2524 span_end: Option<BytePos>,
2525 span_end_before_where: BytePos,
2526 where_clause_option: WhereClauseOption,
2527 ) -> Option<String> {
2528 if where_clause.predicates.is_empty() {
2529 return Some(String::new());
2532 if context.config.where_style() == Style::Rfc {
2533 return rewrite_where_clause_rfc_style(
2539 span_end_before_where,
2540 where_clause_option,
2544 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2546 let offset = match context.config.where_pred_indent() {
2547 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2548 // 6 = "where ".len()
2549 IndentStyle::Visual => shape.indent + extra_indent + 6,
2551 // FIXME: if where_pred_indent != Visual, then the budgets below might
2552 // be out by a char or two.
2554 let budget = context.config.max_width() - offset.width();
2555 let span_start = where_clause.predicates[0].span().lo();
2556 // If we don't have the start of the next span, then use the end of the
2557 // predicates, but that means we miss comments.
2558 let len = where_clause.predicates.len();
2559 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2560 let span_end = span_end.unwrap_or(end_of_preds);
2561 let items = itemize_list(
2563 where_clause.predicates.iter(),
2565 |pred| pred.span().lo(),
2566 |pred| pred.span().hi(),
2567 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2572 let item_vec = items.collect::<Vec<_>>();
2573 // FIXME: we don't need to collect here if the where_layout isn't
2574 // HorizontalVertical.
2575 let tactic = definitive_tactic(
2577 context.config.where_layout(),
2582 let mut comma_tactic = context.config.trailing_comma();
2583 // Kind of a hack because we don't usually have trailing commas in where clauses.
2584 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2585 comma_tactic = SeparatorTactic::Never;
2588 let fmt = ListFormatting {
2591 trailing_separator: comma_tactic,
2592 separator_place: SeparatorPlace::Back,
2593 shape: Shape::legacy(budget, offset),
2594 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2595 preserve_newline: true,
2596 config: context.config,
2598 let preds_str = write_list(&item_vec, &fmt)?;
2600 let end_length = if terminator == "{" {
2601 // If the brace is on the next line we don't need to count it otherwise it needs two
2604 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2605 BraceStyle::PreferSameLine => 2,
2607 } else if terminator == "=" {
2612 if density == Density::Tall || preds_str.contains('\n')
2613 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2617 (shape.indent + extra_indent).to_string(context.config),
2621 Some(format!(" where {}", preds_str))
2625 fn missing_span_before_after_where(
2626 before_item_span_end: BytePos,
2627 where_clause: &ast::WhereClause,
2629 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2631 let pos_after_where = where_clause.span.lo() + BytePos(5);
2632 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2633 (missing_span_before, missing_span_after)
2636 fn rewrite_comments_before_after_where(
2637 context: &RewriteContext,
2638 span_before_where: Span,
2639 span_after_where: Span,
2641 ) -> Option<(String, String)> {
2642 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2643 let after_comment = rewrite_missing_comment(
2645 shape.block_indent(context.config.tab_spaces()),
2648 Some((before_comment, after_comment))
2651 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2652 format!("{}{}{}", format_visibility(vis), item_name, ident)
2656 context: &RewriteContext,
2657 generics: &ast::Generics,
2660 brace_style: BraceStyle,
2661 force_same_line_brace: bool,
2665 ) -> Option<String> {
2666 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2667 let mut result = rewrite_generics(context, generics, shape, span)?;
2669 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2670 let budget = context.budget(last_line_used_width(&result, offset.width()));
2671 let option = WhereClauseOption::snuggled(&result);
2672 let where_clause_str = rewrite_where_clause(
2674 &generics.where_clause,
2676 Shape::legacy(budget, offset.block_only()),
2683 result.push_str(&where_clause_str);
2684 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2685 || (generics.where_clause.predicates.is_empty()
2686 && trimmed_last_line_width(&result) == 1)
2688 force_same_line_brace || trimmed_last_line_width(&result) == 1
2689 || brace_style != BraceStyle::AlwaysNextLine
2691 let total_used_width = last_line_used_width(&result, used_width);
2692 let remaining_budget = context.budget(total_used_width);
2693 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2694 // and hence we take the closer into account as well for one line budget.
2695 // We assume that the closer has the same length as the opener.
2696 let overhead = if force_same_line_brace {
2697 1 + opener.len() + opener.len()
2701 let forbid_same_line_brace = overhead > remaining_budget;
2702 if !forbid_same_line_brace && same_line_brace {
2706 result.push_str(&offset.block_only().to_string(context.config));
2708 result.push_str(opener);
2713 impl Rewrite for ast::ForeignItem {
2714 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2715 let attrs_str = self.attrs.rewrite(context, shape)?;
2716 // Drop semicolon or it will be interpreted as comment.
2717 // FIXME: this may be a faulty span from libsyntax.
2718 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2720 let item_str = match self.node {
2721 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2726 &FnSig::new(fn_decl, generics, self.vis.clone()),
2730 ).map(|(s, _)| format!("{};", s))
2732 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2733 // FIXME(#21): we're dropping potential comments in between the
2734 // function keywords here.
2735 let vis = format_visibility(&self.vis);
2736 let mut_str = if is_mutable { "mut " } else { "" };
2737 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2739 let shape = shape.sub_width(1)?;
2740 ty.rewrite(context, shape).map(|ty_str| {
2741 // 1 = space between prefix and type.
2742 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2745 let nested_indent = shape.indent.block_indent(context.config);
2746 format!("\n{}", nested_indent.to_string(context.config))
2748 format!("{}{}{};", prefix, sep, ty_str)
2753 let missing_span = if self.attrs.is_empty() {
2754 mk_sp(self.span.lo(), self.span.lo())
2756 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2758 combine_strs_with_missing_comments(