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(method_sig: &'a ast::MethodSig) -> FnSig {
189 unsafety: method_sig.unsafety,
190 constness: method_sig.constness.node,
191 defaultness: ast::Defaultness::Final,
193 decl: &*method_sig.decl,
194 generics: &method_sig.generics,
195 visibility: ast::Visibility::Inherited,
200 fn_kind: &'a visit::FnKind,
201 decl: &'a ast::FnDecl,
202 defualtness: ast::Defaultness,
205 visit::FnKind::ItemFn(_, generics, unsafety, constness, abi, visibility, _) => FnSig {
209 constness: constness.node,
210 defaultness: defualtness,
212 visibility: visibility.clone(),
214 visit::FnKind::Method(_, ref method_sig, vis, _) => {
215 let mut fn_sig = FnSig::from_method_sig(method_sig);
216 fn_sig.defaultness = defualtness;
217 if let Some(vis) = vis {
218 fn_sig.visibility = vis.clone();
226 fn to_str(&self, context: &RewriteContext) -> String {
227 let mut result = String::with_capacity(128);
228 // Vis defaultness constness unsafety abi.
229 result.push_str(&*format_visibility(&self.visibility));
230 result.push_str(format_defaultness(self.defaultness));
231 result.push_str(format_constness(self.constness));
232 result.push_str(format_unsafety(self.unsafety));
233 result.push_str(&format_abi(
235 context.config.force_explicit_abi(),
242 impl<'a> FmtVisitor<'a> {
243 fn format_item(&mut self, item: Item) {
244 self.buffer.push_str(&item.abi);
246 let snippet = self.snippet(item.span);
247 let brace_pos = snippet.find_uncommented("{").unwrap();
249 self.buffer.push_str("{");
250 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
251 // FIXME: this skips comments between the extern keyword and the opening
253 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
254 self.block_indent = self.block_indent.block_indent(self.config);
256 if item.body.is_empty() {
257 self.format_missing_no_indent(item.span.hi() - BytePos(1));
258 self.block_indent = self.block_indent.block_unindent(self.config);
261 .push_str(&self.block_indent.to_string(self.config));
263 for item in &item.body {
264 self.format_body_element(item);
267 self.block_indent = self.block_indent.block_unindent(self.config);
268 self.format_missing_with_indent(item.span.hi() - BytePos(1));
272 self.buffer.push_str("}");
273 self.last_pos = item.span.hi();
276 fn format_body_element(&mut self, element: &BodyElement) {
278 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
282 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
283 let item = Item::from_foreign_mod(fm, span, self.config);
284 self.format_item(item);
288 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
289 let rewrite = item.rewrite(&self.get_context(), self.shape());
290 self.push_rewrite(item.span(), rewrite);
291 self.last_pos = item.span.hi();
301 ) -> Option<String> {
302 let context = self.get_context();
305 !is_empty_block(block, self.codemap) || !context.config.fn_empty_single_line();
306 let mut newline_brace =
307 newline_for_brace(self.config, &fn_sig.generics.where_clause, has_body);
309 let (mut result, force_newline_brace) =
310 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
312 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
313 newline_brace = true;
314 } else if last_line_width(&result) + 2 > self.shape().width {
316 newline_brace = true;
317 } else if !result.contains('\n') {
318 newline_brace = false;
321 // Prepare for the function body by possibly adding a newline and
323 // FIXME we'll miss anything between the end of the signature and the
324 // start of the body, but we need more spans from the compiler to solve
328 result.push_str(&indent.to_string(self.config));
333 self.single_line_fn(&result, block).or_else(|| Some(result))
336 pub fn rewrite_required_fn(
340 sig: &ast::MethodSig,
342 ) -> Option<String> {
343 // Drop semicolon or it will be interpreted as comment.
344 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
345 let context = self.get_context();
347 let (mut result, _) = rewrite_fn_base(
351 &FnSig::from_method_sig(sig),
357 // Re-attach semicolon
363 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
364 if fn_str.contains('\n') {
368 let codemap = self.get_context().codemap;
370 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
371 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
373 return Some(format!("{}{{}}", fn_str));
376 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
378 if let Some(stmt) = block.stmts.first() {
379 match stmt_expr(stmt) {
381 let suffix = if semicolon_for_expr(&self.get_context(), e) {
387 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
389 .or_else(|| Some(self.snippet(e.span)))
391 None => stmt.rewrite(&self.get_context(), self.shape()),
398 if let Some(res) = rewrite {
399 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
400 if !res.contains('\n') && width <= self.config.max_width() {
401 return Some(format!("{}{{ {} }}", fn_str, res));
412 vis: &ast::Visibility,
413 enum_def: &ast::EnumDef,
414 generics: &ast::Generics,
417 let enum_header = format_header("enum ", ident, vis);
418 self.buffer.push_str(&enum_header);
420 let enum_snippet = self.snippet(span);
421 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
422 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
423 let generics_str = format_generics(
428 self.config.item_brace_style(),
429 enum_def.variants.is_empty(),
431 mk_sp(span.lo(), body_start),
432 last_line_width(&enum_header),
434 self.buffer.push_str(&generics_str);
436 self.last_pos = body_start;
438 self.block_indent = self.block_indent.block_indent(self.config);
439 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
441 Some(ref body_str) => self.buffer.push_str(body_str),
442 None => if contains_comment(&enum_snippet[brace_pos..]) {
443 self.format_missing_no_indent(span.hi() - BytePos(1))
446 self.block_indent = self.block_indent.block_unindent(self.config);
448 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
450 .push_str(&self.block_indent.to_string(self.config));
452 self.buffer.push_str("}");
453 self.last_pos = span.hi();
456 // Format the body of an enum definition
457 fn format_variant_list(
459 enum_def: &ast::EnumDef,
462 ) -> Option<String> {
463 if enum_def.variants.is_empty() {
466 let mut result = String::with_capacity(1024);
468 let indentation = self.block_indent.to_string(self.config);
469 result.push_str(&indentation);
471 let items = itemize_list(
473 enum_def.variants.iter(),
475 |f| if !f.node.attrs.is_empty() {
476 f.node.attrs[0].span.lo()
481 |f| self.format_variant(f),
487 let shape = self.shape().sub_width(2).unwrap();
488 let fmt = ListFormatting {
489 tactic: DefinitiveListTactic::Vertical,
491 trailing_separator: self.config.trailing_comma(),
492 separator_place: SeparatorPlace::Back,
494 ends_with_newline: true,
495 preserve_newline: true,
499 let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
500 result.push_str(&list);
505 // Variant of an enum.
506 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
507 if contains_skip(&field.node.attrs) {
508 let lo = field.node.attrs[0].span.lo();
509 let span = mk_sp(lo, field.span.hi());
510 return Some(self.snippet(span));
513 let context = self.get_context();
514 let indent = self.block_indent;
515 let shape = self.shape();
516 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
521 .map_or(field.span.lo(), |attr| attr.span.hi());
522 let span = mk_sp(lo, field.span.lo());
524 let variant_body = match field.node.data {
525 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
526 // FIXME: Should limit the width, as we have a trailing comma
531 &ast::Visibility::Inherited,
536 Some(self.config.struct_variant_width()),
539 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
541 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
542 if one_line_width <= shape.width {
543 format!("{} = {}", field.node.name, self.snippet(expr.span))
550 .block_indent(self.config)
551 .to_string(self.config),
552 self.snippet(expr.span)
556 String::from(field.node.name.to_string())
560 let attrs_extendable = attrs_str.is_empty()
561 || (context.config.attributes_on_same_line_as_variant()
562 && is_attributes_extendable(&attrs_str));
563 combine_strs_with_missing_comments(
575 context: &RewriteContext,
578 where_span_end: Option<BytePos>,
579 ) -> Option<String> {
580 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
581 let mut result = String::with_capacity(128);
582 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
583 let indent_str = offset.to_string(context.config);
584 let sep = format!("\n{}", &indent_str);
585 result.push_str(&ref_and_type);
587 let where_budget = if result.contains('\n') {
588 context.config.max_width()
590 context.budget(last_line_width(&result))
592 let option = WhereClauseOption::snuggled(&ref_and_type);
593 let where_clause_str = rewrite_where_clause(
595 &generics.where_clause,
596 context.config.item_brace_style(),
597 Shape::legacy(where_budget, offset.block_only()),
598 context.config.where_density(),
605 // If there is no where clause, we may have missing comments between the trait name and
606 // the opening brace.
607 if generics.where_clause.predicates.is_empty() {
608 if let Some(hi) = where_span_end {
609 match recover_missing_comment_in_span(
610 mk_sp(self_ty.span.hi(), hi),
611 Shape::indented(offset, context.config),
613 last_line_width(&result),
615 Some(ref missing_comment) if !missing_comment.is_empty() => {
616 result.push_str(missing_comment);
623 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
624 result.push_str(&where_clause_str);
625 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
626 result.push_str(&format!("{}{{{}}}", &sep, &sep));
628 result.push_str(" {}");
633 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
635 let width = offset.block_indent + context.config.tab_spaces() - 1;
636 let where_indent = Indent::new(0, width);
637 result.push_str(&where_indent.to_string(context.config));
639 result.push_str(&where_clause_str);
641 match context.config.item_brace_style() {
642 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
643 BraceStyle::AlwaysNextLine => result.push_str(&sep),
644 BraceStyle::PreferSameLine => result.push(' '),
645 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
646 result.push_str(&sep);
654 let snippet = context.snippet(item.span);
655 let open_pos = snippet.find_uncommented("{")? + 1;
657 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
658 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
659 visitor.block_indent = offset.block_only().block_indent(context.config);
660 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
662 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
664 visitor.visit_impl_item(item);
667 visitor.format_missing(item.span.hi() - BytePos(1));
669 let inner_indent_str = visitor.block_indent.to_string(context.config);
670 let outer_indent_str = offset.block_only().to_string(context.config);
673 result.push_str(&inner_indent_str);
674 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
676 result.push_str(&outer_indent_str);
679 if result.chars().last().unwrap() == '{' {
680 result.push_str(&sep);
690 fn is_impl_single_line(
691 context: &RewriteContext,
694 where_clause_str: &str,
697 let snippet = context.snippet(item.span);
698 let open_pos = snippet.find_uncommented("{")? + 1;
701 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
702 && result.len() + where_clause_str.len() <= context.config.max_width()
703 && !contains_comment(&snippet[open_pos..]),
707 fn format_impl_ref_and_type(
708 context: &RewriteContext,
711 ) -> Option<String> {
712 if let ast::ItemKind::Impl(
722 let mut result = String::with_capacity(128);
724 result.push_str(&format_visibility(&item.vis));
725 result.push_str(format_defaultness(defaultness));
726 result.push_str(format_unsafety(unsafety));
727 result.push_str("impl");
729 let lo = context.codemap.span_after(item.span, "impl");
730 let hi = match *trait_ref {
731 Some(ref tr) => tr.path.span.lo(),
732 None => self_ty.span.lo(),
734 let shape = generics_shape_from_config(
736 Shape::indented(offset + last_line_width(&result), context.config),
739 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
741 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
743 let polarity_str = if polarity == ast::ImplPolarity::Negative {
749 if let Some(ref trait_ref) = *trait_ref {
750 let result_len = result.len();
751 if let Some(trait_ref_str) = rewrite_trait_ref(
760 result.push_str(&trait_ref_str);
763 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
764 result.push_str(&rewrite_trait_ref(
775 result.push_str(&generics_str);
778 // Try to put the self type in a single line.
780 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
781 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
782 // If there is no where clause adapt budget for type formatting to take space and curly
783 // brace into account.
784 match context.config.item_brace_style() {
785 BraceStyle::AlwaysNextLine => 0,
791 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
792 // 1 = space before the type.
793 let budget = context.budget(used_space + 1);
794 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
795 if !self_ty_str.contains('\n') {
796 if trait_ref.is_some() {
797 result.push_str(" for ");
801 result.push_str(&self_ty_str);
806 // Couldn't fit the self type on a single line, put it on a new line.
808 // Add indentation of one additional tab.
809 let new_line_offset = offset.block_indent(context.config);
810 result.push_str(&new_line_offset.to_string(context.config));
811 if trait_ref.is_some() {
812 result.push_str("for ");
814 let budget = context.budget(last_line_width(&result));
815 let type_offset = match context.config.where_style() {
816 Style::Legacy => new_line_offset + trait_ref_overhead,
817 Style::Rfc => new_line_offset,
819 result.push_str(&*self_ty
820 .rewrite(context, Shape::legacy(budget, type_offset))?);
827 fn rewrite_trait_ref(
828 context: &RewriteContext,
829 trait_ref: &ast::TraitRef,
835 ) -> Option<String> {
836 // 1 = space between generics and trait_ref
837 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
838 let shape = Shape::indented(offset + used_space, context.config);
839 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
840 if !(retry && trait_ref_str.contains('\n')) {
849 // We could not make enough space for trait_ref, so put it on new line.
851 let offset = offset.block_indent(context.config);
852 let shape = Shape::indented(offset, context.config);
853 let trait_ref_str = trait_ref.rewrite(context, shape)?;
857 &offset.to_string(context.config),
866 pub fn format_struct(
867 context: &RewriteContext,
870 vis: &ast::Visibility,
871 struct_def: &ast::VariantData,
872 generics: Option<&ast::Generics>,
875 one_line_width: Option<usize>,
876 ) -> Option<String> {
878 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
879 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
889 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
903 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
904 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
907 let mut result = String::with_capacity(128);
908 let header = format!(
910 format_visibility(&item.vis),
911 format_unsafety(unsafety),
915 result.push_str(&header);
917 let body_lo = context.codemap.span_after(item.span, "{");
919 let shape = Shape::indented(offset + last_line_width(&result), context.config);
921 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
922 result.push_str(&generics_str);
924 let trait_bound_str = rewrite_trait_bounds(
927 Shape::indented(offset, context.config),
929 // If the trait, generics, and trait bound cannot fit on the same line,
930 // put the trait bounds on an indented new line
931 if offset.width() + last_line_width(&result) + trait_bound_str.len()
932 > context.config.comment_width()
935 let trait_indent = offset.block_only().block_indent(context.config);
936 result.push_str(&trait_indent.to_string(context.config));
938 result.push_str(&trait_bound_str);
940 let has_body = !trait_items.is_empty();
942 let where_density = if (context.config.where_density() == Density::Compressed
943 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
944 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
945 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
946 && !result.contains('\n'))
953 let where_budget = context.budget(last_line_width(&result));
954 let pos_before_where = if type_param_bounds.is_empty() {
955 generics.where_clause.span.lo()
957 type_param_bounds[type_param_bounds.len() - 1].span().hi()
959 let option = WhereClauseOption::snuggled(&generics_str);
960 let where_clause_str = rewrite_where_clause(
962 &generics.where_clause,
963 context.config.item_brace_style(),
964 Shape::legacy(where_budget, offset.block_only()),
971 // If the where clause cannot fit on the same line,
972 // put the where clause on a new line
973 if !where_clause_str.contains('\n')
974 && last_line_width(&result) + where_clause_str.len() + offset.width()
975 > context.config.comment_width()
978 let width = offset.block_indent + context.config.tab_spaces() - 1;
979 let where_indent = Indent::new(0, width);
980 result.push_str(&where_indent.to_string(context.config));
982 result.push_str(&where_clause_str);
984 if generics.where_clause.predicates.is_empty() {
985 let item_snippet = context.snippet(item.span);
986 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
988 let comment_hi = body_lo - BytePos(1);
989 let comment_lo = item.span.lo() + BytePos(lo as u32);
990 if comment_lo < comment_hi {
991 match recover_missing_comment_in_span(
992 mk_sp(comment_lo, comment_hi),
993 Shape::indented(offset, context.config),
995 last_line_width(&result),
997 Some(ref missing_comment) if !missing_comment.is_empty() => {
998 result.push_str(missing_comment);
1006 match context.config.item_brace_style() {
1007 _ if last_line_contains_single_line_comment(&result) => {
1009 result.push_str(&offset.to_string(context.config));
1011 BraceStyle::AlwaysNextLine => {
1013 result.push_str(&offset.to_string(context.config));
1015 BraceStyle::PreferSameLine => result.push(' '),
1016 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1017 && (!trait_items.is_empty() || result.contains('\n'))
1020 result.push_str(&offset.to_string(context.config));
1027 let snippet = context.snippet(item.span);
1028 let open_pos = snippet.find_uncommented("{")? + 1;
1030 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1031 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1032 visitor.block_indent = offset.block_only().block_indent(context.config);
1033 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1035 for item in trait_items {
1036 visitor.visit_trait_item(item);
1039 visitor.format_missing(item.span.hi() - BytePos(1));
1041 let inner_indent_str = visitor.block_indent.to_string(context.config);
1042 let outer_indent_str = offset.block_only().to_string(context.config);
1045 result.push_str(&inner_indent_str);
1046 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1048 result.push_str(&outer_indent_str);
1049 } else if result.contains('\n') {
1060 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1061 format!("{};", format_header(item_name, ident, vis))
1064 pub fn format_struct_struct(
1065 context: &RewriteContext,
1068 vis: &ast::Visibility,
1069 fields: &[ast::StructField],
1070 generics: Option<&ast::Generics>,
1073 one_line_width: Option<usize>,
1074 ) -> Option<String> {
1075 let mut result = String::with_capacity(1024);
1077 let header_str = format_header(item_name, ident, vis);
1078 result.push_str(&header_str);
1080 let body_lo = context.codemap.span_after(span, "{");
1082 let generics_str = match generics {
1083 Some(g) => format_generics(
1088 context.config.item_brace_style(),
1091 mk_sp(span.lo(), body_lo),
1092 last_line_width(&result),
1095 // 3 = ` {}`, 2 = ` {`.
1096 let overhead = if fields.is_empty() { 3 } else { 2 };
1097 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1098 && !fields.is_empty())
1099 || context.config.max_width() < overhead + result.len()
1101 format!("\n{}{{", offset.block_only().to_string(context.config))
1108 let overhead = if fields.is_empty() { 1 } else { 0 };
1109 let total_width = result.len() + generics_str.len() + overhead;
1110 if !generics_str.is_empty() && !generics_str.contains('\n')
1111 && total_width > context.config.max_width()
1114 result.push_str(&offset.to_string(context.config));
1115 result.push_str(generics_str.trim_left());
1117 result.push_str(&generics_str);
1120 if fields.is_empty() {
1121 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1122 if snippet.trim().is_empty() {
1124 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1126 result.push_str(snippet.trim_right());
1128 result.push_str(&offset.to_string(context.config));
1130 result.push_str(&snippet);
1133 return Some(result);
1137 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1138 let one_line_budget =
1139 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1141 let items_str = rewrite_with_alignment(
1144 Shape::indented(offset, context.config),
1145 mk_sp(body_lo, span.hi()),
1149 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1150 Some(format!("{} {} }}", result, items_str))
1156 .block_indent(context.config)
1157 .to_string(context.config),
1159 offset.to_string(context.config)
1164 fn format_tuple_struct(
1165 context: &RewriteContext,
1168 vis: &ast::Visibility,
1169 fields: &[ast::StructField],
1170 generics: Option<&ast::Generics>,
1173 ) -> Option<String> {
1174 let mut result = String::with_capacity(1024);
1176 let header_str = format_header(item_name, ident, vis);
1177 result.push_str(&header_str);
1179 let body_lo = if fields.is_empty() {
1180 context.codemap.span_after(span, "(")
1184 let body_hi = if fields.is_empty() {
1185 context.codemap.span_after(span, ")")
1187 // This is a dirty hack to work around a missing `)` from the span of the last field.
1188 let last_arg_span = fields[fields.len() - 1].span;
1189 if context.snippet(last_arg_span).ends_with(')') {
1194 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1198 let where_clause_str = match generics {
1200 let budget = context.budget(last_line_width(&header_str));
1201 let shape = Shape::legacy(budget, offset);
1202 let g_span = mk_sp(span.lo(), body_lo);
1203 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1204 result.push_str(&generics_str);
1206 let where_budget = context.budget(last_line_width(&result));
1207 let option = WhereClauseOption::new(true, false);
1208 rewrite_where_clause(
1210 &generics.where_clause,
1211 context.config.item_brace_style(),
1212 Shape::legacy(where_budget, offset.block_only()),
1213 Density::Compressed,
1220 None => "".to_owned(),
1223 if fields.is_empty() {
1225 let used_width = last_line_used_width(&result, offset.width()) + 3;
1226 if used_width > context.config.max_width() {
1228 result.push_str(&offset
1229 .block_indent(context.config)
1230 .to_string(context.config))
1233 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1234 if snippet.is_empty() {
1236 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1237 result.push_str(snippet.trim_right());
1239 result.push_str(&offset.to_string(context.config));
1241 result.push_str(&snippet);
1246 let body = rewrite_call_inner(
1249 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1251 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1252 context.config.fn_call_width(),
1255 result.push_str(&body);
1258 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1259 && (result.contains('\n')
1260 || offset.block_indent + result.len() + where_clause_str.len() + 1
1261 > context.config.max_width())
1263 // We need to put the where clause on a new line, but we didn't
1264 // know that earlier, so the where clause will not be indented properly.
1266 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1267 .to_string(context.config));
1269 result.push_str(&where_clause_str);
1274 pub fn rewrite_type_alias(
1275 context: &RewriteContext,
1279 generics: &ast::Generics,
1280 vis: &ast::Visibility,
1282 ) -> Option<String> {
1283 let mut result = String::with_capacity(128);
1285 result.push_str(&format_visibility(vis));
1286 result.push_str("type ");
1287 result.push_str(&ident.to_string());
1290 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1291 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1292 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1293 result.push_str(&generics_str);
1295 let where_budget = context.budget(last_line_width(&result));
1296 let option = WhereClauseOption::snuggled(&result);
1297 let where_clause_str = rewrite_where_clause(
1299 &generics.where_clause,
1300 context.config.item_brace_style(),
1301 Shape::legacy(where_budget, indent),
1302 context.config.where_density(),
1308 result.push_str(&where_clause_str);
1309 if where_clause_str.is_empty() {
1310 result.push_str(" = ");
1312 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1315 let line_width = last_line_width(&result);
1316 // This checked_sub may fail as the extra space after '=' is not taken into account
1317 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1318 let budget = context.budget(indent.width() + line_width + ";".len());
1319 let type_indent = indent + line_width;
1320 // Try to fit the type on the same line
1321 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1323 // The line was too short, try to put the type on the next line
1325 // Remove the space after '='
1327 let type_indent = indent.block_indent(context.config);
1329 result.push_str(&type_indent.to_string(context.config));
1330 let budget = context.budget(type_indent.width() + ";".len());
1331 ty.rewrite(context, Shape::legacy(budget, type_indent))
1333 result.push_str(&ty_str);
1334 result.push_str(";");
1338 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1340 if config.space_before_type_annotation() {
1345 if config.space_after_type_annotation_colon() {
1353 pub fn rewrite_struct_field_prefix(
1354 context: &RewriteContext,
1355 field: &ast::StructField,
1356 ) -> Option<String> {
1357 let vis = format_visibility(&field.vis);
1358 let type_annotation_spacing = type_annotation_spacing(context.config);
1359 Some(match field.ident {
1360 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1361 None => format!("{}", vis),
1365 impl Rewrite for ast::StructField {
1366 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1367 rewrite_struct_field(context, self, shape, 0)
1371 pub fn rewrite_struct_field(
1372 context: &RewriteContext,
1373 field: &ast::StructField,
1375 lhs_max_width: usize,
1376 ) -> Option<String> {
1377 if contains_skip(&field.attrs) {
1378 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1381 let type_annotation_spacing = type_annotation_spacing(context.config);
1382 let prefix = rewrite_struct_field_prefix(context, field)?;
1384 let attrs_str = field.attrs.rewrite(context, shape)?;
1385 let attrs_extendable = attrs_str.is_empty()
1386 || (context.config.attributes_on_same_line_as_field()
1387 && is_attributes_extendable(&attrs_str));
1388 let missing_span = if field.attrs.is_empty() {
1389 mk_sp(field.span.lo(), field.span.lo())
1391 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1393 let mut spacing = String::from(if field.ident.is_some() {
1394 type_annotation_spacing.1
1398 // Try to put everything on a single line.
1399 let attr_prefix = combine_strs_with_missing_comments(
1407 let overhead = last_line_width(&attr_prefix);
1408 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1409 for _ in 0..lhs_offset {
1412 // In this extreme case we will be missing a space betweeen an attribute and a field.
1413 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1416 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1417 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1418 if !ty.contains('\n') {
1419 return Some(attr_prefix + &spacing + ty);
1423 // We must use multiline.
1424 let new_shape = shape.with_max_width(context.config);
1425 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1427 let field_str = if prefix.is_empty() {
1429 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1430 prefix + " " + &ty_rewritten
1432 let type_offset = shape.indent.block_indent(context.config);
1433 let nested_shape = Shape::indented(type_offset, context.config);
1434 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1435 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1437 combine_strs_with_missing_comments(
1447 pub fn rewrite_static(
1449 vis: &ast::Visibility,
1452 mutability: ast::Mutability,
1453 expr_opt: Option<&ptr::P<ast::Expr>>,
1456 context: &RewriteContext,
1457 ) -> Option<String> {
1458 let colon = colon_spaces(
1459 context.config.space_before_type_annotation(),
1460 context.config.space_after_type_annotation_colon(),
1462 let prefix = format!(
1464 format_visibility(vis),
1466 format_mutability(mutability),
1471 let ty_str = ty.rewrite(
1473 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1476 if let Some(expr) = expr_opt {
1477 let lhs = format!("{}{} =", prefix, ty_str);
1479 let remaining_width = context.budget(offset.block_indent + 1);
1484 Shape::legacy(remaining_width, offset.block_only()),
1485 ).and_then(|res| recover_comment_removed(res, span, context))
1486 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1488 Some(format!("{}{};", prefix, ty_str))
1492 pub fn rewrite_associated_type(
1494 ty_opt: Option<&ptr::P<ast::Ty>>,
1495 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1496 context: &RewriteContext,
1498 ) -> Option<String> {
1499 let prefix = format!("type {}", ident);
1501 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1503 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1504 let bounds: &[_] = ty_param_bounds;
1505 let bound_str = bounds
1507 .map(|ty_bound| ty_bound.rewrite(context, shape))
1508 .collect::<Option<Vec<_>>>()?;
1509 if !bounds.is_empty() {
1510 format!(": {}", join_bounds(context, shape, &bound_str))
1518 if let Some(ty) = ty_opt {
1519 let ty_str = ty.rewrite(
1522 context.budget(indent.block_indent + prefix.len() + 2),
1523 indent.block_only(),
1526 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1528 Some(format!("{}{};", prefix, type_bounds_str))
1532 pub fn rewrite_associated_impl_type(
1534 defaultness: ast::Defaultness,
1535 ty_opt: Option<&ptr::P<ast::Ty>>,
1536 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1537 context: &RewriteContext,
1539 ) -> Option<String> {
1540 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1543 ast::Defaultness::Default => Some(format!("default {}", result)),
1548 impl Rewrite for ast::FunctionRetTy {
1549 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1551 ast::FunctionRetTy::Default(_) => Some(String::new()),
1552 ast::FunctionRetTy::Ty(ref ty) => {
1553 let inner_width = shape.width.checked_sub(3)?;
1554 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1555 .map(|r| format!("-> {}", r))
1561 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1563 ast::TyKind::Infer => {
1564 let original = context.snippet(ty.span);
1571 impl Rewrite for ast::Arg {
1572 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1573 if is_named_arg(self) {
1574 let mut result = self.pat
1575 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1577 if !is_empty_infer(context, &*self.ty) {
1578 if context.config.space_before_type_annotation() {
1579 result.push_str(" ");
1581 result.push_str(":");
1582 if context.config.space_after_type_annotation_colon() {
1583 result.push_str(" ");
1585 let overhead = last_line_width(&result);
1586 let max_width = shape.width.checked_sub(overhead)?;
1587 let ty_str = self.ty
1588 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1589 result.push_str(&ty_str);
1594 self.ty.rewrite(context, shape)
1599 fn rewrite_explicit_self(
1600 explicit_self: &ast::ExplicitSelf,
1602 context: &RewriteContext,
1603 ) -> Option<String> {
1604 match explicit_self.node {
1605 ast::SelfKind::Region(lt, m) => {
1606 let mut_str = format_mutability(m);
1609 let lifetime_str = l.rewrite(
1611 Shape::legacy(context.config.max_width(), Indent::empty()),
1613 Some(format!("&{} {}self", lifetime_str, mut_str))
1615 None => Some(format!("&{}self", mut_str)),
1618 ast::SelfKind::Explicit(ref ty, _) => {
1619 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1621 let mutability = explicit_self_mutability(&args[0]);
1622 let type_str = ty.rewrite(
1624 Shape::legacy(context.config.max_width(), Indent::empty()),
1629 format_mutability(mutability),
1633 ast::SelfKind::Value(_) => {
1634 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1636 let mutability = explicit_self_mutability(&args[0]);
1638 Some(format!("{}self", format_mutability(mutability)))
1643 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1644 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1645 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1646 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1653 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1654 if is_named_arg(arg) {
1661 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1663 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1664 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1665 _ => arg.ty.span.hi(),
1669 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1670 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1671 ident.node != symbol::keywords::Invalid.ident()
1677 // Return type is (result, force_new_line_for_brace)
1679 context: &RewriteContext,
1684 newline_brace: bool,
1686 ) -> Option<(String, bool)> {
1687 let mut force_new_line_for_brace = false;
1689 let where_clause = &fn_sig.generics.where_clause;
1691 let mut result = String::with_capacity(1024);
1692 result.push_str(&fn_sig.to_str(context));
1695 result.push_str("fn ");
1696 result.push_str(&ident.to_string());
1699 let overhead = if has_body && !newline_brace {
1706 let used_width = last_line_used_width(&result, indent.width());
1707 let one_line_budget = context.budget(used_width + overhead);
1709 width: one_line_budget,
1713 let fd = fn_sig.decl;
1714 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1715 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1716 result.push_str(&generics_str);
1718 let snuggle_angle_bracket = generics_str
1721 .map_or(false, |l| l.trim_left().len() == 1);
1723 // Note that the width and indent don't really matter, we'll re-layout the
1724 // return type later anyway.
1725 let ret_str = fd.output
1726 .rewrite(context, Shape::indented(indent, context.config))?;
1728 let multi_line_ret_str = ret_str.contains('\n');
1729 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1732 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1743 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1749 // Check if vertical layout was forced.
1750 if one_line_budget == 0 {
1751 if snuggle_angle_bracket {
1753 } else if context.config.fn_args_paren_newline() {
1755 result.push_str(&arg_indent.to_string(context.config));
1756 if context.config.fn_args_layout() == IndentStyle::Visual {
1757 arg_indent = arg_indent + 1; // extra space for `(`
1761 result.push_str("(");
1762 if context.config.fn_args_layout() == IndentStyle::Visual {
1764 result.push_str(&arg_indent.to_string(context.config));
1770 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1774 // A conservative estimation, to goal is to be over all parens in generics
1775 let args_start = fn_sig
1779 .map_or(span.lo(), |tp| end_typaram(tp));
1780 let args_end = if fd.inputs.is_empty() {
1783 .span_after(mk_sp(args_start, span.hi()), ")")
1785 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1786 context.codemap.span_after(last_span, ")")
1788 let args_span = mk_sp(
1791 .span_after(mk_sp(args_start, span.hi()), "("),
1794 let arg_str = rewrite_args(
1797 fd.get_self().as_ref(),
1804 generics_str.contains('\n'),
1807 let put_args_in_block = match context.config.fn_args_layout() {
1808 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1810 } && !fd.inputs.is_empty();
1812 let mut args_last_line_contains_comment = false;
1813 if put_args_in_block {
1814 arg_indent = indent.block_indent(context.config);
1816 result.push_str(&arg_indent.to_string(context.config));
1817 result.push_str(&arg_str);
1819 result.push_str(&indent.to_string(context.config));
1822 result.push_str(&arg_str);
1823 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1824 // Put the closing brace on the next line if it overflows the max width.
1826 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1829 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1832 // If the last line of args contains comment, we cannot put the closing paren
1833 // on the same line.
1837 .map_or(false, |last_line| last_line.contains("//"))
1839 args_last_line_contains_comment = true;
1841 result.push_str(&arg_indent.to_string(context.config));
1847 if let ast::FunctionRetTy::Ty(..) = fd.output {
1848 let ret_should_indent = match context.config.fn_args_layout() {
1849 // If our args are block layout then we surely must have space.
1850 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1851 _ if args_last_line_contains_comment => false,
1852 _ if result.contains('\n') || multi_line_ret_str => true,
1854 // If the return type would push over the max width, then put the return type on
1855 // a new line. With the +1 for the signature length an additional space between
1856 // the closing parenthesis of the argument and the arrow '->' is considered.
1857 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1859 // If there is no where clause, take into account the space after the return type
1861 if where_clause.predicates.is_empty() {
1865 sig_length > context.config.max_width()
1868 let ret_indent = if ret_should_indent {
1869 let indent = match context.config.fn_return_indent() {
1870 ReturnIndent::WithWhereClause => indent + 4,
1871 // Aligning with non-existent args looks silly.
1872 _ if arg_str.is_empty() => {
1873 force_new_line_for_brace = true;
1876 // FIXME: we might want to check that using the arg indent
1877 // doesn't blow our budget, and if it does, then fallback to
1878 // the where clause indent.
1883 result.push_str(&indent.to_string(context.config));
1887 Indent::new(indent.block_indent, last_line_width(&result))
1890 if multi_line_ret_str || ret_should_indent {
1891 // Now that we know the proper indent and width, we need to
1892 // re-layout the return type.
1893 let ret_str = fd.output
1894 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1895 result.push_str(&ret_str);
1897 result.push_str(&ret_str);
1900 // Comment between return type and the end of the decl.
1901 let snippet_lo = fd.output.span().hi();
1902 if where_clause.predicates.is_empty() {
1903 let snippet_hi = span.hi();
1904 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1905 // Try to preserve the layout of the original snippet.
1906 let original_starts_with_newline = snippet
1908 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1909 let original_ends_with_newline = snippet
1910 .rfind(|c| c != ' ')
1911 .map_or(false, |i| snippet[i..].ends_with('\n'));
1912 let snippet = snippet.trim();
1913 if !snippet.is_empty() {
1914 result.push(if original_starts_with_newline {
1919 result.push_str(snippet);
1920 if original_ends_with_newline {
1921 force_new_line_for_brace = true;
1927 let should_compress_where = match context.config.where_density() {
1928 Density::Compressed => !result.contains('\n'),
1929 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1933 let pos_before_where = match fd.output {
1934 ast::FunctionRetTy::Default(..) => args_span.hi(),
1935 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1938 if where_clause.predicates.len() == 1 && should_compress_where {
1939 let budget = context.budget(last_line_used_width(&result, indent.width()));
1940 if let Some(where_clause_str) = rewrite_where_clause(
1943 context.config.fn_brace_style(),
1944 Shape::legacy(budget, indent),
1945 Density::Compressed,
1949 WhereClauseOption::compressed(),
1951 result.push_str(&where_clause_str);
1952 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1953 return Some((result, force_new_line_for_brace));
1957 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1958 let where_clause_str = rewrite_where_clause(
1961 context.config.fn_brace_style(),
1962 Shape::indented(indent, context.config),
1969 // If there are neither where clause nor return type, we may be missing comments between
1971 if where_clause_str.is_empty() {
1972 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1973 match recover_missing_comment_in_span(
1974 mk_sp(args_span.hi(), ret_span.hi()),
1977 last_line_width(&result),
1979 Some(ref missing_comment) if !missing_comment.is_empty() => {
1980 result.push_str(missing_comment);
1981 force_new_line_for_brace = true;
1988 result.push_str(&where_clause_str);
1990 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1991 Some((result, force_new_line_for_brace))
1994 #[derive(Copy, Clone)]
1995 struct WhereClauseOption {
1996 suppress_comma: bool, // Force no trailing comma
1997 snuggle: bool, // Do not insert newline before `where`
1998 compress_where: bool, // Try single line where clause instead of vertical layout
2001 impl WhereClauseOption {
2002 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2004 suppress_comma: suppress_comma,
2006 compress_where: false,
2010 pub fn compressed() -> WhereClauseOption {
2012 suppress_comma: true,
2014 compress_where: true,
2018 pub fn snuggled(current: &str) -> WhereClauseOption {
2020 suppress_comma: false,
2021 snuggle: trimmed_last_line_width(current) == 1,
2022 compress_where: false,
2028 context: &RewriteContext,
2030 explicit_self: Option<&ast::ExplicitSelf>,
2031 one_line_budget: usize,
2032 multi_line_budget: usize,
2037 generics_str_contains_newline: bool,
2038 ) -> Option<String> {
2039 let mut arg_item_strs = args.iter()
2041 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2043 .collect::<Option<Vec<_>>>()?;
2045 // Account for sugary self.
2046 // FIXME: the comment for the self argument is dropped. This is blocked
2047 // on rust issue #27522.
2048 let min_args = explicit_self
2049 .and_then(|explicit_self| {
2050 rewrite_explicit_self(explicit_self, args, context)
2052 .map_or(1, |self_str| {
2053 arg_item_strs[0] = self_str;
2057 // Comments between args.
2058 let mut arg_items = Vec::new();
2060 arg_items.push(ListItem::from_str(""));
2063 // FIXME(#21): if there are no args, there might still be a comment, but
2064 // without spans for the comment or parens, there is no chance of
2065 // getting it right. You also don't get to put a comment on self, unless
2067 if args.len() >= min_args || variadic {
2068 let comment_span_start = if min_args == 2 {
2069 let second_arg_start = if arg_has_pattern(&args[1]) {
2070 args[1].pat.span.lo()
2072 args[1].ty.span.lo()
2074 let reduced_span = mk_sp(span.lo(), second_arg_start);
2076 context.codemap.span_after_last(reduced_span, ",")
2081 enum ArgumentKind<'a> {
2082 Regular(&'a ast::Arg),
2086 let variadic_arg = if variadic {
2087 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2088 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2089 Some(ArgumentKind::Variadic(variadic_start))
2094 let more_items = itemize_list(
2096 args[min_args - 1..]
2098 .map(ArgumentKind::Regular)
2099 .chain(variadic_arg),
2102 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2103 ArgumentKind::Variadic(start) => start,
2106 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2107 ArgumentKind::Variadic(start) => start + BytePos(3),
2110 ArgumentKind::Regular(..) => None,
2111 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2118 arg_items.extend(more_items);
2121 let fits_in_one_line = !generics_str_contains_newline
2122 && (arg_items.is_empty()
2123 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2125 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2126 item.item = Some(arg);
2129 let last_line_ends_with_comment = arg_items
2132 .and_then(|item| item.post_comment.as_ref())
2133 .map_or(false, |s| s.trim().starts_with("//"));
2135 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2136 IndentStyle::Block if fits_in_one_line => {
2137 (indent.block_indent(context.config), SeparatorTactic::Never)
2139 IndentStyle::Block => (
2140 indent.block_indent(context.config),
2141 context.config.trailing_comma(),
2143 IndentStyle::Visual if last_line_ends_with_comment => {
2144 (arg_indent, context.config.trailing_comma())
2146 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2149 let tactic = definitive_tactic(
2151 context.config.fn_args_density().to_list_tactic(),
2155 let budget = match tactic {
2156 DefinitiveListTactic::Horizontal => one_line_budget,
2157 _ => multi_line_budget,
2160 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2162 let fmt = ListFormatting {
2165 trailing_separator: if variadic {
2166 SeparatorTactic::Never
2170 separator_place: SeparatorPlace::Back,
2171 shape: Shape::legacy(budget, indent),
2172 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2173 preserve_newline: true,
2174 config: context.config,
2177 write_list(&arg_items, &fmt)
2180 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2181 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2182 ident.node != symbol::keywords::Invalid.ident()
2188 fn compute_budgets_for_args(
2189 context: &RewriteContext,
2193 newline_brace: bool,
2195 force_vertical_layout: bool,
2196 ) -> Option<((usize, usize, Indent))> {
2198 "compute_budgets_for_args {} {:?}, {}, {}",
2204 // Try keeping everything on the same line.
2205 if !result.contains('\n') && !force_vertical_layout {
2206 // 2 = `()`, 3 = `() `, space is before ret_string.
2207 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2208 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2218 let one_line_budget = context.budget(used_space);
2220 if one_line_budget > 0 {
2222 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2223 IndentStyle::Block => {
2224 let indent = indent.block_indent(context.config);
2225 (indent, context.budget(indent.width() + 1))
2227 IndentStyle::Visual => {
2228 let indent = indent + result.len() + 1;
2229 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2230 (indent, context.budget(multi_line_overhead))
2234 return Some((one_line_budget, multi_line_budget, indent));
2238 // Didn't work. we must force vertical layout and put args on a newline.
2239 let new_indent = indent.block_indent(context.config);
2240 let used_space = match context.config.fn_args_layout() {
2242 IndentStyle::Block => new_indent.width() + 1,
2243 // Account for `)` and possibly ` {`.
2244 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2246 Some((0, context.budget(used_space), new_indent))
2249 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2250 match (config.fn_brace_style(), config.where_density()) {
2251 (BraceStyle::AlwaysNextLine, _) => true,
2252 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2253 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2254 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2259 fn rewrite_generics(
2260 context: &RewriteContext,
2261 generics: &ast::Generics,
2264 ) -> Option<String> {
2265 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2266 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2267 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2268 rewrite_generics_inner(context, generics, g_shape, 0, span)
2272 fn rewrite_generics_inner(
2273 context: &RewriteContext,
2274 generics: &ast::Generics,
2276 one_line_width: usize,
2278 ) -> Option<String> {
2279 // FIXME: convert bounds to where clauses where they get too big or if
2280 // there is a where clause at all.
2283 enum GenericsArg<'a> {
2284 Lifetime(&'a ast::LifetimeDef),
2285 TyParam(&'a ast::TyParam),
2287 impl<'a> Rewrite for GenericsArg<'a> {
2288 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2290 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2291 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2295 impl<'a> Spanned for GenericsArg<'a> {
2296 fn span(&self) -> Span {
2298 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2299 GenericsArg::TyParam(ref ty) => ty.span(),
2304 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2305 return Some(String::new());
2308 let generics_args = generics
2311 .map(|lt| GenericsArg::Lifetime(lt))
2312 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2313 let items = itemize_list(
2317 |arg| arg.span().lo(),
2318 |arg| arg.span().hi(),
2319 |arg| arg.rewrite(context, shape),
2320 context.codemap.span_after(span, "<"),
2324 format_generics_item_list(context, items, shape, one_line_width)
2327 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2328 match config.generics_indent() {
2329 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2330 IndentStyle::Block => {
2334 .block_indent(config.tab_spaces())
2335 .with_max_width(config)
2341 pub fn format_generics_item_list<I>(
2342 context: &RewriteContext,
2345 one_line_budget: usize,
2348 I: Iterator<Item = ListItem>,
2350 let item_vec = items.collect::<Vec<_>>();
2352 let tactic = definitive_tactic(
2354 ListTactic::HorizontalVertical,
2358 let fmt = ListFormatting {
2361 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2362 SeparatorTactic::Never
2364 context.config.trailing_comma()
2366 separator_place: SeparatorPlace::Back,
2368 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2369 preserve_newline: true,
2370 config: context.config,
2373 let list_str = write_list(&item_vec, &fmt)?;
2375 Some(wrap_generics_with_angle_brackets(
2382 pub fn wrap_generics_with_angle_brackets(
2383 context: &RewriteContext,
2385 list_offset: Indent,
2387 if context.config.generics_indent() == IndentStyle::Block
2388 && (list_str.contains('\n') || list_str.ends_with(','))
2392 list_offset.to_string(context.config),
2395 .block_unindent(context.config)
2396 .to_string(context.config)
2398 } else if context.config.spaces_within_angle_brackets() {
2399 format!("< {} >", list_str)
2401 format!("<{}>", list_str)
2405 fn rewrite_trait_bounds(
2406 context: &RewriteContext,
2407 type_param_bounds: &ast::TyParamBounds,
2409 ) -> Option<String> {
2410 let bounds: &[_] = type_param_bounds;
2412 if bounds.is_empty() {
2413 return Some(String::new());
2415 let bound_str = bounds
2417 .map(|ty_bound| ty_bound.rewrite(context, shape))
2418 .collect::<Option<Vec<_>>>()?;
2419 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2422 fn rewrite_where_clause_rfc_style(
2423 context: &RewriteContext,
2424 where_clause: &ast::WhereClause,
2427 span_end: Option<BytePos>,
2428 span_end_before_where: BytePos,
2429 where_clause_option: WhereClauseOption,
2430 ) -> Option<String> {
2431 let block_shape = shape.block().with_max_width(context.config);
2433 let (span_before, span_after) =
2434 missing_span_before_after_where(span_end_before_where, where_clause);
2435 let (comment_before, comment_after) =
2436 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2438 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2441 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2444 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2446 let clause_shape = clause_shape.sub_width(1)?;
2447 // each clause on one line, trailing comma (except if suppress_comma)
2448 let span_start = where_clause.predicates[0].span().lo();
2449 // If we don't have the start of the next span, then use the end of the
2450 // predicates, but that means we miss comments.
2451 let len = where_clause.predicates.len();
2452 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2453 let span_end = span_end.unwrap_or(end_of_preds);
2454 let items = itemize_list(
2456 where_clause.predicates.iter(),
2458 |pred| pred.span().lo(),
2459 |pred| pred.span().hi(),
2460 |pred| pred.rewrite(context, clause_shape),
2465 let comma_tactic = if where_clause_option.suppress_comma {
2466 SeparatorTactic::Never
2468 context.config.trailing_comma()
2471 let fmt = ListFormatting {
2472 tactic: DefinitiveListTactic::Vertical,
2474 trailing_separator: comma_tactic,
2475 separator_place: SeparatorPlace::Back,
2476 shape: clause_shape,
2477 ends_with_newline: true,
2478 preserve_newline: true,
2479 config: context.config,
2481 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2483 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2486 format!("\n{}", shape.indent.to_string(context.config))
2488 let newline_before_where = comment_separator(&comment_before, shape);
2489 let newline_after_where = comment_separator(&comment_after, clause_shape);
2492 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2493 && comment_after.is_empty() && !preds_str.contains('\n')
2494 && 6 + preds_str.len() <= shape.width
2498 format!("\n{}", clause_shape.indent.to_string(context.config))
2501 "{}{}{}where{}{}{}{}",
2504 newline_before_where,
2505 newline_after_where,
2512 fn rewrite_where_clause(
2513 context: &RewriteContext,
2514 where_clause: &ast::WhereClause,
2515 brace_style: BraceStyle,
2519 span_end: Option<BytePos>,
2520 span_end_before_where: BytePos,
2521 where_clause_option: WhereClauseOption,
2522 ) -> Option<String> {
2523 if where_clause.predicates.is_empty() {
2524 return Some(String::new());
2527 if context.config.where_style() == Style::Rfc {
2528 return rewrite_where_clause_rfc_style(
2534 span_end_before_where,
2535 where_clause_option,
2539 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2541 let offset = match context.config.where_pred_indent() {
2542 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2543 // 6 = "where ".len()
2544 IndentStyle::Visual => shape.indent + extra_indent + 6,
2546 // FIXME: if where_pred_indent != Visual, then the budgets below might
2547 // be out by a char or two.
2549 let budget = context.config.max_width() - offset.width();
2550 let span_start = where_clause.predicates[0].span().lo();
2551 // If we don't have the start of the next span, then use the end of the
2552 // predicates, but that means we miss comments.
2553 let len = where_clause.predicates.len();
2554 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2555 let span_end = span_end.unwrap_or(end_of_preds);
2556 let items = itemize_list(
2558 where_clause.predicates.iter(),
2560 |pred| pred.span().lo(),
2561 |pred| pred.span().hi(),
2562 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2567 let item_vec = items.collect::<Vec<_>>();
2568 // FIXME: we don't need to collect here if the where_layout isn't
2569 // HorizontalVertical.
2570 let tactic = definitive_tactic(
2572 context.config.where_layout(),
2577 let mut comma_tactic = context.config.trailing_comma();
2578 // Kind of a hack because we don't usually have trailing commas in where clauses.
2579 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2580 comma_tactic = SeparatorTactic::Never;
2583 let fmt = ListFormatting {
2586 trailing_separator: comma_tactic,
2587 separator_place: SeparatorPlace::Back,
2588 shape: Shape::legacy(budget, offset),
2589 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2590 preserve_newline: true,
2591 config: context.config,
2593 let preds_str = write_list(&item_vec, &fmt)?;
2595 let end_length = if terminator == "{" {
2596 // If the brace is on the next line we don't need to count it otherwise it needs two
2599 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2600 BraceStyle::PreferSameLine => 2,
2602 } else if terminator == "=" {
2607 if density == Density::Tall || preds_str.contains('\n')
2608 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2612 (shape.indent + extra_indent).to_string(context.config),
2616 Some(format!(" where {}", preds_str))
2620 fn missing_span_before_after_where(
2621 before_item_span_end: BytePos,
2622 where_clause: &ast::WhereClause,
2624 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2626 let pos_after_where = where_clause.span.lo() + BytePos(5);
2627 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2628 (missing_span_before, missing_span_after)
2631 fn rewrite_comments_before_after_where(
2632 context: &RewriteContext,
2633 span_before_where: Span,
2634 span_after_where: Span,
2636 ) -> Option<(String, String)> {
2637 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2638 let after_comment = rewrite_missing_comment(
2640 shape.block_indent(context.config.tab_spaces()),
2643 Some((before_comment, after_comment))
2646 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2647 format!("{}{}{}", format_visibility(vis), item_name, ident)
2651 context: &RewriteContext,
2652 generics: &ast::Generics,
2655 brace_style: BraceStyle,
2656 force_same_line_brace: bool,
2660 ) -> Option<String> {
2661 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2662 let mut result = rewrite_generics(context, generics, shape, span)?;
2664 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2665 let budget = context.budget(last_line_used_width(&result, offset.width()));
2666 let option = WhereClauseOption::snuggled(&result);
2667 let where_clause_str = rewrite_where_clause(
2669 &generics.where_clause,
2671 Shape::legacy(budget, offset.block_only()),
2678 result.push_str(&where_clause_str);
2679 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2680 || (generics.where_clause.predicates.is_empty()
2681 && trimmed_last_line_width(&result) == 1)
2683 force_same_line_brace || trimmed_last_line_width(&result) == 1
2684 || brace_style != BraceStyle::AlwaysNextLine
2686 let total_used_width = last_line_used_width(&result, used_width);
2687 let remaining_budget = context.budget(total_used_width);
2688 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2689 // and hence we take the closer into account as well for one line budget.
2690 // We assume that the closer has the same length as the opener.
2691 let overhead = if force_same_line_brace {
2692 1 + opener.len() + opener.len()
2696 let forbid_same_line_brace = overhead > remaining_budget;
2697 if !forbid_same_line_brace && same_line_brace {
2701 result.push_str(&offset.block_only().to_string(context.config));
2703 result.push_str(opener);
2708 impl Rewrite for ast::ForeignItem {
2709 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2710 let attrs_str = self.attrs.rewrite(context, shape)?;
2711 // Drop semicolon or it will be interpreted as comment.
2712 // FIXME: this may be a faulty span from libsyntax.
2713 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2715 let item_str = match self.node {
2716 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2721 &FnSig::new(fn_decl, generics, self.vis.clone()),
2725 ).map(|(s, _)| format!("{};", s))
2727 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2728 // FIXME(#21): we're dropping potential comments in between the
2729 // function keywords here.
2730 let vis = format_visibility(&self.vis);
2731 let mut_str = if is_mutable { "mut " } else { "" };
2732 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2734 let shape = shape.sub_width(1)?;
2735 ty.rewrite(context, shape).map(|ty_str| {
2736 // 1 = space between prefix and type.
2737 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2740 let nested_indent = shape.indent.block_indent(context.config);
2741 format!("\n{}", nested_indent.to_string(context.config))
2743 format!("{}{}{};", prefix, sep, ty_str)
2748 let missing_span = if self.attrs.is_empty() {
2749 mk_sp(self.span.lo(), self.span.lo())
2751 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2753 combine_strs_with_missing_comments(