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, stmt_expr,
37 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 = try_opt!(self.attrs.rewrite(context, shape));
66 let mut result = if attrs_str.is_empty() {
69 try_opt!(combine_strs_with_missing_comments(
74 self.attrs.last().map(|a| a.span.hi()).unwrap(),
83 let pat_shape = try_opt!(shape.offset_left(4));
85 let pat_shape = try_opt!(pat_shape.sub_width(1));
86 let pat_str = try_opt!(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 = try_opt!(shape.width.checked_sub(indent.width() + 1));
98 let rewrite = try_opt!(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 = try_opt!(shape.sub_width(1));
117 result = try_opt!(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) = try_opt!(rewrite_fn_base(
319 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
320 newline_brace = true;
321 } else if last_line_width(&result) + 2 > self.shape().width {
323 newline_brace = true;
324 } else if !result.contains('\n') {
325 newline_brace = false;
328 // Prepare for the function body by possibly adding a newline and
330 // FIXME we'll miss anything between the end of the signature and the
331 // start of the body, but we need more spans from the compiler to solve
335 result.push_str(&indent.to_string(self.config));
340 self.single_line_fn(&result, block).or_else(|| Some(result))
343 pub fn rewrite_required_fn(
347 sig: &ast::MethodSig,
349 ) -> Option<String> {
350 // Drop semicolon or it will be interpreted as comment.
351 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
352 let context = self.get_context();
354 let (mut result, _) = try_opt!(rewrite_fn_base(
358 &FnSig::from_method_sig(sig),
364 // Re-attach semicolon
370 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
371 if fn_str.contains('\n') {
375 let codemap = self.get_context().codemap;
377 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
378 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
380 return Some(format!("{}{{}}", fn_str));
383 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
385 if let Some(stmt) = block.stmts.first() {
386 match stmt_expr(stmt) {
388 let suffix = if semicolon_for_expr(&self.get_context(), e) {
394 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
396 .or_else(|| Some(self.snippet(e.span)))
398 None => stmt.rewrite(&self.get_context(), self.shape()),
405 if let Some(res) = rewrite {
406 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
407 if !res.contains('\n') && width <= self.config.max_width() {
408 return Some(format!("{}{{ {} }}", fn_str, res));
419 vis: &ast::Visibility,
420 enum_def: &ast::EnumDef,
421 generics: &ast::Generics,
424 let enum_header = format_header("enum ", ident, vis);
425 self.buffer.push_str(&enum_header);
427 let enum_snippet = self.snippet(span);
428 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
429 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
430 let generics_str = format_generics(
435 self.config.item_brace_style(),
436 enum_def.variants.is_empty(),
438 mk_sp(span.lo(), body_start),
439 last_line_width(&enum_header),
441 self.buffer.push_str(&generics_str);
443 self.last_pos = body_start;
445 self.block_indent = self.block_indent.block_indent(self.config);
446 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
448 Some(ref body_str) => self.buffer.push_str(body_str),
449 None => if contains_comment(&enum_snippet[brace_pos..]) {
450 self.format_missing_no_indent(span.hi() - BytePos(1))
453 self.block_indent = self.block_indent.block_unindent(self.config);
455 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
457 .push_str(&self.block_indent.to_string(self.config));
459 self.buffer.push_str("}");
460 self.last_pos = span.hi();
463 // Format the body of an enum definition
464 fn format_variant_list(
466 enum_def: &ast::EnumDef,
469 ) -> Option<String> {
470 if enum_def.variants.is_empty() {
473 let mut result = String::with_capacity(1024);
475 let indentation = self.block_indent.to_string(self.config);
476 result.push_str(&indentation);
478 let items = itemize_list(
480 enum_def.variants.iter(),
482 |f| if !f.node.attrs.is_empty() {
483 f.node.attrs[0].span.lo()
488 |f| self.format_variant(f),
494 let shape = self.shape().sub_width(2).unwrap();
495 let fmt = ListFormatting {
496 tactic: DefinitiveListTactic::Vertical,
498 trailing_separator: self.config.trailing_comma(),
499 separator_place: SeparatorPlace::Back,
501 ends_with_newline: true,
502 preserve_newline: true,
506 let list = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
507 result.push_str(&list);
512 // Variant of an enum.
513 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
514 if contains_skip(&field.node.attrs) {
515 let lo = field.node.attrs[0].span.lo();
516 let span = mk_sp(lo, field.span.hi());
517 return Some(self.snippet(span));
520 let context = self.get_context();
521 let indent = self.block_indent;
522 let shape = self.shape();
523 let attrs_str = try_opt!(field.node.attrs.rewrite(&context, shape));
528 .map_or(field.span.lo(), |attr| attr.span.hi());
529 let span = mk_sp(lo, field.span.lo());
531 let variant_body = match field.node.data {
532 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
533 // FIXME: Should limit the width, as we have a trailing comma
534 try_opt!(format_struct(
538 &ast::Visibility::Inherited,
543 Some(self.config.struct_variant_width()),
546 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
548 field.node.name.to_string().len() + self.snippet(expr.span).len() + 3;
549 if one_line_width <= shape.width {
550 format!("{} = {}", field.node.name, self.snippet(expr.span))
557 .block_indent(self.config)
558 .to_string(self.config),
559 self.snippet(expr.span)
563 String::from(field.node.name.to_string())
567 let attrs_extendable = attrs_str.is_empty()
568 || (context.config.attributes_on_same_line_as_variant()
569 && is_attributes_extendable(&attrs_str));
570 combine_strs_with_missing_comments(
582 context: &RewriteContext,
585 where_span_end: Option<BytePos>,
586 ) -> Option<String> {
587 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
588 let mut result = String::with_capacity(128);
589 let ref_and_type = try_opt!(format_impl_ref_and_type(context, item, offset));
590 let indent_str = offset.to_string(context.config);
591 let sep = format!("\n{}", &indent_str);
592 result.push_str(&ref_and_type);
594 let where_budget = if result.contains('\n') {
595 context.config.max_width()
597 context.budget(last_line_width(&result))
599 let option = WhereClauseOption::snuggled(&ref_and_type);
600 let where_clause_str = try_opt!(rewrite_where_clause(
602 &generics.where_clause,
603 context.config.item_brace_style(),
604 Shape::legacy(where_budget, offset.block_only()),
605 context.config.where_density(),
612 // If there is no where clause, we may have missing comments between the trait name and
613 // the opening brace.
614 if generics.where_clause.predicates.is_empty() {
615 if let Some(hi) = where_span_end {
616 match recover_missing_comment_in_span(
617 mk_sp(self_ty.span.hi(), hi),
618 Shape::indented(offset, context.config),
620 last_line_width(&result),
622 Some(ref missing_comment) if !missing_comment.is_empty() => {
623 result.push_str(missing_comment);
630 if try_opt!(is_impl_single_line(
637 result.push_str(&where_clause_str);
638 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
639 result.push_str(&format!("{}{{{}}}", &sep, &sep));
641 result.push_str(" {}");
646 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
648 let width = offset.block_indent + context.config.tab_spaces() - 1;
649 let where_indent = Indent::new(0, width);
650 result.push_str(&where_indent.to_string(context.config));
652 result.push_str(&where_clause_str);
654 match context.config.item_brace_style() {
655 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
656 BraceStyle::AlwaysNextLine => result.push_str(&sep),
657 BraceStyle::PreferSameLine => result.push(' '),
658 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
659 result.push_str(&sep);
667 let snippet = context.snippet(item.span);
668 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
670 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
671 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
672 visitor.block_indent = offset.block_only().block_indent(context.config);
673 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
675 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
677 visitor.visit_impl_item(item);
680 visitor.format_missing(item.span.hi() - BytePos(1));
682 let inner_indent_str = visitor.block_indent.to_string(context.config);
683 let outer_indent_str = offset.block_only().to_string(context.config);
686 result.push_str(&inner_indent_str);
687 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
689 result.push_str(&outer_indent_str);
692 if result.chars().last().unwrap() == '{' {
693 result.push_str(&sep);
703 fn is_impl_single_line(
704 context: &RewriteContext,
707 where_clause_str: &str,
710 let snippet = context.snippet(item.span);
711 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
714 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
715 && result.len() + where_clause_str.len() <= context.config.max_width()
716 && !contains_comment(&snippet[open_pos..]),
720 fn format_impl_ref_and_type(
721 context: &RewriteContext,
724 ) -> Option<String> {
725 if let ast::ItemKind::Impl(
735 let mut result = String::with_capacity(128);
737 result.push_str(&format_visibility(&item.vis));
738 result.push_str(format_defaultness(defaultness));
739 result.push_str(format_unsafety(unsafety));
740 result.push_str("impl");
742 let lo = context.codemap.span_after(item.span, "impl");
743 let hi = match *trait_ref {
744 Some(ref tr) => tr.path.span.lo(),
745 None => self_ty.span.lo(),
747 let shape = try_opt!(generics_shape_from_config(
749 Shape::indented(offset + last_line_width(&result), context.config),
752 let one_line_budget = try_opt!(shape.width.checked_sub(last_line_width(&result) + 2));
753 let generics_str = try_opt!(rewrite_generics_inner(
761 let polarity_str = if polarity == ast::ImplPolarity::Negative {
767 if let Some(ref trait_ref) = *trait_ref {
768 let result_len = result.len();
769 if let Some(trait_ref_str) = rewrite_trait_ref(
778 result.push_str(&trait_ref_str);
780 let generics_str = try_opt!(rewrite_generics_inner(
787 result.push_str(&try_opt!(rewrite_trait_ref(
798 result.push_str(&generics_str);
801 // Try to put the self type in a single line.
803 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
804 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
805 // If there is no where clause adapt budget for type formatting to take space and curly
806 // brace into account.
807 match context.config.item_brace_style() {
808 BraceStyle::AlwaysNextLine => 0,
814 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
815 // 1 = space before the type.
816 let budget = context.budget(used_space + 1);
817 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
818 if !self_ty_str.contains('\n') {
819 if trait_ref.is_some() {
820 result.push_str(" for ");
824 result.push_str(&self_ty_str);
829 // Couldn't fit the self type on a single line, put it on a new line.
831 // Add indentation of one additional tab.
832 let new_line_offset = offset.block_indent(context.config);
833 result.push_str(&new_line_offset.to_string(context.config));
834 if trait_ref.is_some() {
835 result.push_str("for ");
837 let budget = context.budget(last_line_width(&result));
838 let type_offset = match context.config.where_style() {
839 Style::Legacy => new_line_offset + trait_ref_overhead,
840 Style::Rfc => new_line_offset,
842 result.push_str(&*try_opt!(
843 self_ty.rewrite(context, Shape::legacy(budget, type_offset))
851 fn rewrite_trait_ref(
852 context: &RewriteContext,
853 trait_ref: &ast::TraitRef,
859 ) -> Option<String> {
860 // 1 = space between generics and trait_ref
861 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
862 let shape = Shape::indented(offset + used_space, context.config);
863 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
864 if !(retry && trait_ref_str.contains('\n')) {
873 // We could not make enough space for trait_ref, so put it on new line.
875 let offset = offset.block_indent(context.config);
876 let shape = Shape::indented(offset, context.config);
877 let trait_ref_str = try_opt!(trait_ref.rewrite(context, shape));
881 &offset.to_string(context.config),
890 pub fn format_struct(
891 context: &RewriteContext,
894 vis: &ast::Visibility,
895 struct_def: &ast::VariantData,
896 generics: Option<&ast::Generics>,
899 one_line_width: Option<usize>,
900 ) -> Option<String> {
902 ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
903 ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
913 ast::VariantData::Struct(ref fields, _) => format_struct_struct(
927 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
928 if let ast::ItemKind::Trait(unsafety, ref generics, ref type_param_bounds, ref trait_items) =
931 let mut result = String::with_capacity(128);
932 let header = format!(
934 format_visibility(&item.vis),
935 format_unsafety(unsafety),
939 result.push_str(&header);
941 let body_lo = context.codemap.span_after(item.span, "{");
943 let shape = Shape::indented(offset + last_line_width(&result), context.config);
944 let generics_str = try_opt!(rewrite_generics(
948 mk_sp(item.span.lo(), body_lo),
950 result.push_str(&generics_str);
952 let trait_bound_str = try_opt!(rewrite_trait_bounds(
955 Shape::indented(offset, context.config),
957 // If the trait, generics, and trait bound cannot fit on the same line,
958 // put the trait bounds on an indented new line
959 if offset.width() + last_line_width(&result) + trait_bound_str.len()
960 > context.config.comment_width()
963 let trait_indent = offset.block_only().block_indent(context.config);
964 result.push_str(&trait_indent.to_string(context.config));
966 result.push_str(&trait_bound_str);
968 let has_body = !trait_items.is_empty();
970 let where_density = if (context.config.where_density() == Density::Compressed
971 && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
972 || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
973 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
974 && !result.contains('\n'))
981 let where_budget = context.budget(last_line_width(&result));
982 let pos_before_where = if type_param_bounds.is_empty() {
983 generics.where_clause.span.lo()
985 type_param_bounds[type_param_bounds.len() - 1].span().hi()
987 let option = WhereClauseOption::snuggled(&generics_str);
988 let where_clause_str = try_opt!(rewrite_where_clause(
990 &generics.where_clause,
991 context.config.item_brace_style(),
992 Shape::legacy(where_budget, offset.block_only()),
999 // If the where clause cannot fit on the same line,
1000 // put the where clause on a new line
1001 if !where_clause_str.contains('\n')
1002 && last_line_width(&result) + where_clause_str.len() + offset.width()
1003 > context.config.comment_width()
1006 let width = offset.block_indent + context.config.tab_spaces() - 1;
1007 let where_indent = Indent::new(0, width);
1008 result.push_str(&where_indent.to_string(context.config));
1010 result.push_str(&where_clause_str);
1012 if generics.where_clause.predicates.is_empty() {
1013 let item_snippet = context.snippet(item.span);
1014 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
1016 let comment_hi = body_lo - BytePos(1);
1017 let comment_lo = item.span.lo() + BytePos(lo as u32);
1018 if comment_lo < comment_hi {
1019 match recover_missing_comment_in_span(
1020 mk_sp(comment_lo, comment_hi),
1021 Shape::indented(offset, context.config),
1023 last_line_width(&result),
1025 Some(ref missing_comment) if !missing_comment.is_empty() => {
1026 result.push_str(missing_comment);
1034 match context.config.item_brace_style() {
1035 _ if last_line_contains_single_line_comment(&result) => {
1037 result.push_str(&offset.to_string(context.config));
1039 BraceStyle::AlwaysNextLine => {
1041 result.push_str(&offset.to_string(context.config));
1043 BraceStyle::PreferSameLine => result.push(' '),
1044 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1045 && (!trait_items.is_empty() || result.contains('\n'))
1048 result.push_str(&offset.to_string(context.config));
1055 let snippet = context.snippet(item.span);
1056 let open_pos = try_opt!(snippet.find_uncommented("{")) + 1;
1058 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1059 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1060 visitor.block_indent = offset.block_only().block_indent(context.config);
1061 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1063 for item in trait_items {
1064 visitor.visit_trait_item(item);
1067 visitor.format_missing(item.span.hi() - BytePos(1));
1069 let inner_indent_str = visitor.block_indent.to_string(context.config);
1070 let outer_indent_str = offset.block_only().to_string(context.config);
1073 result.push_str(&inner_indent_str);
1074 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1076 result.push_str(&outer_indent_str);
1077 } else if result.contains('\n') {
1088 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1089 format!("{};", format_header(item_name, ident, vis))
1092 pub fn format_struct_struct(
1093 context: &RewriteContext,
1096 vis: &ast::Visibility,
1097 fields: &[ast::StructField],
1098 generics: Option<&ast::Generics>,
1101 one_line_width: Option<usize>,
1102 ) -> Option<String> {
1103 let mut result = String::with_capacity(1024);
1105 let header_str = format_header(item_name, ident, vis);
1106 result.push_str(&header_str);
1108 let body_lo = context.codemap.span_after(span, "{");
1110 let generics_str = match generics {
1111 Some(g) => try_opt!(format_generics(
1116 context.config.item_brace_style(),
1119 mk_sp(span.lo(), body_lo),
1120 last_line_width(&result),
1123 // 3 = ` {}`, 2 = ` {`.
1124 let overhead = if fields.is_empty() { 3 } else { 2 };
1125 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1126 && !fields.is_empty())
1127 || context.config.max_width() < overhead + result.len()
1129 format!("\n{}{{", offset.block_only().to_string(context.config))
1136 let overhead = if fields.is_empty() { 1 } else { 0 };
1137 let total_width = result.len() + generics_str.len() + overhead;
1138 if !generics_str.is_empty() && !generics_str.contains('\n')
1139 && total_width > context.config.max_width()
1142 result.push_str(&offset.to_string(context.config));
1143 result.push_str(generics_str.trim_left());
1145 result.push_str(&generics_str);
1148 if fields.is_empty() {
1149 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1150 if snippet.trim().is_empty() {
1152 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1154 result.push_str(snippet.trim_right());
1156 result.push_str(&offset.to_string(context.config));
1158 result.push_str(&snippet);
1161 return Some(result);
1165 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1166 let one_line_budget =
1167 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1169 let items_str = try_opt!(rewrite_with_alignment(
1172 Shape::indented(offset, context.config),
1173 mk_sp(body_lo, span.hi()),
1177 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1178 Some(format!("{} {} }}", result, items_str))
1184 .block_indent(context.config)
1185 .to_string(context.config),
1187 offset.to_string(context.config)
1192 fn format_tuple_struct(
1193 context: &RewriteContext,
1196 vis: &ast::Visibility,
1197 fields: &[ast::StructField],
1198 generics: Option<&ast::Generics>,
1201 ) -> Option<String> {
1202 let mut result = String::with_capacity(1024);
1204 let header_str = format_header(item_name, ident, vis);
1205 result.push_str(&header_str);
1207 let body_lo = if fields.is_empty() {
1208 context.codemap.span_after(span, "(")
1212 let body_hi = if fields.is_empty() {
1213 context.codemap.span_after(span, ")")
1215 // This is a dirty hack to work around a missing `)` from the span of the last field.
1216 let last_arg_span = fields[fields.len() - 1].span;
1217 if context.snippet(last_arg_span).ends_with(')') {
1222 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1226 let where_clause_str = match generics {
1228 let budget = context.budget(last_line_width(&header_str));
1229 let shape = Shape::legacy(budget, offset);
1230 let g_span = mk_sp(span.lo(), body_lo);
1231 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1232 result.push_str(&generics_str);
1234 let where_budget = context.budget(last_line_width(&result));
1235 let option = WhereClauseOption::new(true, false);
1236 try_opt!(rewrite_where_clause(
1238 &generics.where_clause,
1239 context.config.item_brace_style(),
1240 Shape::legacy(where_budget, offset.block_only()),
1241 Density::Compressed,
1248 None => "".to_owned(),
1251 if fields.is_empty() {
1253 let used_width = last_line_used_width(&result, offset.width()) + 3;
1254 if used_width > context.config.max_width() {
1256 result.push_str(&offset
1257 .block_indent(context.config)
1258 .to_string(context.config))
1261 let snippet = context.snippet(mk_sp(body_lo, context.codemap.span_before(span, ")")));
1262 if snippet.is_empty() {
1264 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1265 result.push_str(snippet.trim_right());
1267 result.push_str(&offset.to_string(context.config));
1269 result.push_str(&snippet);
1274 let body = try_opt!(rewrite_call_inner(
1277 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1279 Shape::legacy(context.budget(last_line_width(&result) + 3), offset),
1280 context.config.fn_call_width(),
1283 result.push_str(&body);
1286 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1287 && (result.contains('\n')
1288 || offset.block_indent + result.len() + where_clause_str.len() + 1
1289 > context.config.max_width())
1291 // We need to put the where clause on a new line, but we didn't
1292 // know that earlier, so the where clause will not be indented properly.
1294 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1295 .to_string(context.config));
1297 result.push_str(&where_clause_str);
1302 pub fn rewrite_type_alias(
1303 context: &RewriteContext,
1307 generics: &ast::Generics,
1308 vis: &ast::Visibility,
1310 ) -> Option<String> {
1311 let mut result = String::with_capacity(128);
1313 result.push_str(&format_visibility(vis));
1314 result.push_str("type ");
1315 result.push_str(&ident.to_string());
1318 let shape = try_opt!(Shape::indented(indent + result.len(), context.config).sub_width(2));
1319 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1320 let generics_str = try_opt!(rewrite_generics(context, generics, shape, g_span));
1321 result.push_str(&generics_str);
1323 let where_budget = context.budget(last_line_width(&result));
1324 let option = WhereClauseOption::snuggled(&result);
1325 let where_clause_str = try_opt!(rewrite_where_clause(
1327 &generics.where_clause,
1328 context.config.item_brace_style(),
1329 Shape::legacy(where_budget, indent),
1330 context.config.where_density(),
1336 result.push_str(&where_clause_str);
1337 if where_clause_str.is_empty() {
1338 result.push_str(" = ");
1340 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1343 let line_width = last_line_width(&result);
1344 // This checked_sub may fail as the extra space after '=' is not taken into account
1345 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1346 let budget = context.budget(indent.width() + line_width + ";".len());
1347 let type_indent = indent + line_width;
1348 // Try to fit the type on the same line
1349 let ty_str = try_opt!(
1350 ty.rewrite(context, Shape::legacy(budget, type_indent))
1352 // The line was too short, try to put the type on the next line
1354 // Remove the space after '='
1356 let type_indent = indent.block_indent(context.config);
1358 result.push_str(&type_indent.to_string(context.config));
1359 let budget = context.budget(type_indent.width() + ";".len());
1360 ty.rewrite(context, Shape::legacy(budget, type_indent))
1363 result.push_str(&ty_str);
1364 result.push_str(";");
1368 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1370 if config.space_before_type_annotation() {
1375 if config.space_after_type_annotation_colon() {
1383 pub fn rewrite_struct_field_prefix(
1384 context: &RewriteContext,
1385 field: &ast::StructField,
1386 ) -> Option<String> {
1387 let vis = format_visibility(&field.vis);
1388 let type_annotation_spacing = type_annotation_spacing(context.config);
1389 Some(match field.ident {
1390 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1391 None => format!("{}", vis),
1395 fn rewrite_struct_field_type(
1396 context: &RewriteContext,
1397 last_line_width: usize,
1398 field: &ast::StructField,
1401 ) -> Option<String> {
1402 let ty_shape = try_opt!(shape.offset_left(last_line_width + spacing.len()));
1405 .rewrite(context, ty_shape)
1406 .map(|ty| format!("{}{}", spacing, ty))
1409 impl Rewrite for ast::StructField {
1410 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1411 rewrite_struct_field(context, self, shape, 0)
1415 pub fn rewrite_struct_field(
1416 context: &RewriteContext,
1417 field: &ast::StructField,
1419 lhs_max_width: usize,
1420 ) -> Option<String> {
1421 if contains_skip(&field.attrs) {
1422 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1425 let type_annotation_spacing = type_annotation_spacing(context.config);
1426 let prefix = try_opt!(rewrite_struct_field_prefix(context, field));
1428 let attrs_str = try_opt!(field.attrs.rewrite(context, shape));
1429 let attrs_extendable = attrs_str.is_empty()
1430 || (context.config.attributes_on_same_line_as_field()
1431 && is_attributes_extendable(&attrs_str));
1432 let missing_span = if field.attrs.is_empty() {
1433 mk_sp(field.span.lo(), field.span.lo())
1435 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1437 let mut spacing = String::from(if field.ident.is_some() {
1438 type_annotation_spacing.1
1442 // Try to put everything on a single line.
1443 let attr_prefix = try_opt!(combine_strs_with_missing_comments(
1451 let overhead = last_line_width(&attr_prefix);
1452 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1453 for _ in 0..lhs_offset {
1456 // In this extreme case we will be missing a space betweeen an attribute and a field.
1457 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1460 let ty_rewritten = rewrite_struct_field_type(context, overhead, field, &spacing, shape);
1461 if let Some(ref ty) = ty_rewritten {
1462 if !ty.contains('\n') {
1463 return Some(attr_prefix + ty);
1467 // We must use multiline.
1468 let last_line_width = last_line_width(&prefix);
1469 let ty_rewritten = rewrite_struct_field_type(context, last_line_width, field, &spacing, shape);
1471 let type_offset = shape.indent.block_indent(context.config);
1472 let rewrite_type_in_next_line = || {
1475 .rewrite(context, Shape::indented(type_offset, context.config))
1478 let field_str = match ty_rewritten {
1479 // If we start from the next line and type fits in a single line, then do so.
1480 Some(ref ty) => match rewrite_type_in_next_line() {
1481 Some(ref new_ty) if !new_ty.contains('\n') => format!(
1484 type_offset.to_string(context.config),
1490 let ty = try_opt!(rewrite_type_in_next_line());
1494 type_offset.to_string(context.config),
1499 combine_strs_with_missing_comments(
1509 pub fn rewrite_static(
1511 vis: &ast::Visibility,
1514 mutability: ast::Mutability,
1515 expr_opt: Option<&ptr::P<ast::Expr>>,
1518 context: &RewriteContext,
1519 ) -> Option<String> {
1520 let colon = colon_spaces(
1521 context.config.space_before_type_annotation(),
1522 context.config.space_after_type_annotation_colon(),
1524 let prefix = format!(
1526 format_visibility(vis),
1528 format_mutability(mutability),
1533 let ty_str = try_opt!(ty.rewrite(
1536 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)
1540 if let Some(expr) = expr_opt {
1541 let lhs = format!("{}{} =", prefix, ty_str);
1543 let remaining_width = context.budget(offset.block_indent + 1);
1548 Shape::legacy(remaining_width, offset.block_only()),
1549 ).and_then(|res| recover_comment_removed(res, span, context))
1550 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1552 Some(format!("{}{};", prefix, ty_str))
1556 pub fn rewrite_associated_type(
1558 ty_opt: Option<&ptr::P<ast::Ty>>,
1559 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1560 context: &RewriteContext,
1562 ) -> Option<String> {
1563 let prefix = format!("type {}", ident);
1565 let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1567 let shape = try_opt!(Shape::indented(indent, context.config).offset_left(prefix.len() + 2));
1568 let bounds: &[_] = ty_param_bounds;
1569 let bound_str = try_opt!(
1572 .map(|ty_bound| ty_bound.rewrite(context, shape))
1573 .collect::<Option<Vec<_>>>()
1575 if !bounds.is_empty() {
1576 format!(": {}", join_bounds(context, shape, &bound_str))
1584 if let Some(ty) = ty_opt {
1585 let ty_str = try_opt!(ty.rewrite(
1588 context.budget(indent.block_indent + prefix.len() + 2),
1589 indent.block_only(),
1592 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1594 Some(format!("{}{};", prefix, type_bounds_str))
1598 pub fn rewrite_associated_impl_type(
1600 defaultness: ast::Defaultness,
1601 ty_opt: Option<&ptr::P<ast::Ty>>,
1602 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1603 context: &RewriteContext,
1605 ) -> Option<String> {
1606 let result = try_opt!(rewrite_associated_type(
1609 ty_param_bounds_opt,
1615 ast::Defaultness::Default => Some(format!("default {}", result)),
1620 impl Rewrite for ast::FunctionRetTy {
1621 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1623 ast::FunctionRetTy::Default(_) => Some(String::new()),
1624 ast::FunctionRetTy::Ty(ref ty) => {
1625 let inner_width = try_opt!(shape.width.checked_sub(3));
1626 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1627 .map(|r| format!("-> {}", r))
1633 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1635 ast::TyKind::Infer => {
1636 let original = context.snippet(ty.span);
1643 impl Rewrite for ast::Arg {
1644 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1645 if is_named_arg(self) {
1646 let mut result = try_opt!(
1648 .rewrite(context, Shape::legacy(shape.width, shape.indent))
1651 if !is_empty_infer(context, &*self.ty) {
1652 if context.config.space_before_type_annotation() {
1653 result.push_str(" ");
1655 result.push_str(":");
1656 if context.config.space_after_type_annotation_colon() {
1657 result.push_str(" ");
1659 let overhead = last_line_width(&result);
1660 let max_width = try_opt!(shape.width.checked_sub(overhead));
1661 let ty_str = try_opt!(
1663 .rewrite(context, Shape::legacy(max_width, shape.indent))
1665 result.push_str(&ty_str);
1670 self.ty.rewrite(context, shape)
1675 fn rewrite_explicit_self(
1676 explicit_self: &ast::ExplicitSelf,
1678 context: &RewriteContext,
1679 ) -> Option<String> {
1680 match explicit_self.node {
1681 ast::SelfKind::Region(lt, m) => {
1682 let mut_str = format_mutability(m);
1685 let lifetime_str = try_opt!(l.rewrite(
1687 Shape::legacy(context.config.max_width(), Indent::empty()),
1689 Some(format!("&{} {}self", lifetime_str, mut_str))
1691 None => Some(format!("&{}self", mut_str)),
1694 ast::SelfKind::Explicit(ref ty, _) => {
1695 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1697 let mutability = explicit_self_mutability(&args[0]);
1698 let type_str = try_opt!(ty.rewrite(
1700 Shape::legacy(context.config.max_width(), Indent::empty()),
1705 format_mutability(mutability),
1709 ast::SelfKind::Value(_) => {
1710 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1712 let mutability = explicit_self_mutability(&args[0]);
1714 Some(format!("{}self", format_mutability(mutability)))
1719 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1720 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1721 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1722 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1729 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1730 if is_named_arg(arg) {
1737 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1739 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1740 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1741 _ => arg.ty.span.hi(),
1745 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1746 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1747 ident.node != symbol::keywords::Invalid.ident()
1753 // Return type is (result, force_new_line_for_brace)
1755 context: &RewriteContext,
1760 newline_brace: bool,
1762 ) -> Option<(String, bool)> {
1763 let mut force_new_line_for_brace = false;
1765 let where_clause = &fn_sig.generics.where_clause;
1767 let mut result = String::with_capacity(1024);
1768 result.push_str(&fn_sig.to_str(context));
1771 result.push_str("fn ");
1772 result.push_str(&ident.to_string());
1775 let overhead = if has_body && !newline_brace {
1782 let used_width = last_line_used_width(&result, indent.width());
1783 let one_line_budget = context.budget(used_width + overhead);
1785 width: one_line_budget,
1789 let fd = fn_sig.decl;
1790 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1791 let generics_str = try_opt!(rewrite_generics(context, fn_sig.generics, shape, g_span));
1792 result.push_str(&generics_str);
1794 let snuggle_angle_bracket = generics_str
1797 .map_or(false, |l| l.trim_left().len() == 1);
1799 // Note that the width and indent don't really matter, we'll re-layout the
1800 // return type later anyway.
1801 let ret_str = try_opt!(
1803 .rewrite(context, Shape::indented(indent, context.config))
1806 let multi_line_ret_str = ret_str.contains('\n');
1807 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1810 let (one_line_budget, multi_line_budget, mut arg_indent) = try_opt!(compute_budgets_for_args(
1821 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1827 // Check if vertical layout was forced.
1828 if one_line_budget == 0 {
1829 if snuggle_angle_bracket {
1831 } else if context.config.fn_args_paren_newline() {
1833 result.push_str(&arg_indent.to_string(context.config));
1834 if context.config.fn_args_layout() == IndentStyle::Visual {
1835 arg_indent = arg_indent + 1; // extra space for `(`
1839 result.push_str("(");
1840 if context.config.fn_args_layout() == IndentStyle::Visual {
1842 result.push_str(&arg_indent.to_string(context.config));
1848 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1852 // A conservative estimation, to goal is to be over all parens in generics
1853 let args_start = fn_sig
1857 .map_or(span.lo(), |tp| end_typaram(tp));
1858 let args_end = if fd.inputs.is_empty() {
1861 .span_after(mk_sp(args_start, span.hi()), ")")
1863 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1864 context.codemap.span_after(last_span, ")")
1866 let args_span = mk_sp(
1869 .span_after(mk_sp(args_start, span.hi()), "("),
1872 let arg_str = try_opt!(rewrite_args(
1875 fd.get_self().as_ref(),
1882 generics_str.contains('\n'),
1885 let put_args_in_block = match context.config.fn_args_layout() {
1886 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1888 } && !fd.inputs.is_empty();
1890 let mut args_last_line_contains_comment = false;
1891 if put_args_in_block {
1892 arg_indent = indent.block_indent(context.config);
1894 result.push_str(&arg_indent.to_string(context.config));
1895 result.push_str(&arg_str);
1897 result.push_str(&indent.to_string(context.config));
1900 result.push_str(&arg_str);
1901 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1902 // Put the closing brace on the next line if it overflows the max width.
1904 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1907 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1910 // If the last line of args contains comment, we cannot put the closing paren
1911 // on the same line.
1915 .map_or(false, |last_line| last_line.contains("//"))
1917 args_last_line_contains_comment = true;
1919 result.push_str(&arg_indent.to_string(context.config));
1925 if let ast::FunctionRetTy::Ty(..) = fd.output {
1926 let ret_should_indent = match context.config.fn_args_layout() {
1927 // If our args are block layout then we surely must have space.
1928 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1929 _ if args_last_line_contains_comment => false,
1930 _ if result.contains('\n') || multi_line_ret_str => true,
1932 // If the return type would push over the max width, then put the return type on
1933 // a new line. With the +1 for the signature length an additional space between
1934 // the closing parenthesis of the argument and the arrow '->' is considered.
1935 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1937 // If there is no where clause, take into account the space after the return type
1939 if where_clause.predicates.is_empty() {
1943 sig_length > context.config.max_width()
1946 let ret_indent = if ret_should_indent {
1947 let indent = match context.config.fn_return_indent() {
1948 ReturnIndent::WithWhereClause => indent + 4,
1949 // Aligning with non-existent args looks silly.
1950 _ if arg_str.is_empty() => {
1951 force_new_line_for_brace = true;
1954 // FIXME: we might want to check that using the arg indent
1955 // doesn't blow our budget, and if it does, then fallback to
1956 // the where clause indent.
1961 result.push_str(&indent.to_string(context.config));
1965 Indent::new(indent.block_indent, last_line_width(&result))
1968 if multi_line_ret_str || ret_should_indent {
1969 // Now that we know the proper indent and width, we need to
1970 // re-layout the return type.
1971 let ret_str = try_opt!(
1973 .rewrite(context, Shape::indented(ret_indent, context.config))
1975 result.push_str(&ret_str);
1977 result.push_str(&ret_str);
1980 // Comment between return type and the end of the decl.
1981 let snippet_lo = fd.output.span().hi();
1982 if where_clause.predicates.is_empty() {
1983 let snippet_hi = span.hi();
1984 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1985 // Try to preserve the layout of the original snippet.
1986 let original_starts_with_newline = snippet
1988 .map_or(false, |i| snippet[i..].starts_with('\n'));
1989 let original_ends_with_newline = snippet
1990 .rfind(|c| c != ' ')
1991 .map_or(false, |i| snippet[i..].ends_with('\n'));
1992 let snippet = snippet.trim();
1993 if !snippet.is_empty() {
1994 result.push(if original_starts_with_newline {
1999 result.push_str(snippet);
2000 if original_ends_with_newline {
2001 force_new_line_for_brace = true;
2007 let should_compress_where = match context.config.where_density() {
2008 Density::Compressed => !result.contains('\n'),
2009 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
2013 let pos_before_where = match fd.output {
2014 ast::FunctionRetTy::Default(..) => args_span.hi(),
2015 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2018 if where_clause.predicates.len() == 1 && should_compress_where {
2019 let budget = context.budget(last_line_used_width(&result, indent.width()));
2020 if let Some(where_clause_str) = rewrite_where_clause(
2023 context.config.fn_brace_style(),
2024 Shape::legacy(budget, indent),
2025 Density::Compressed,
2029 WhereClauseOption::compressed(),
2031 result.push_str(&where_clause_str);
2032 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2033 return Some((result, force_new_line_for_brace));
2037 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2038 let where_clause_str = try_opt!(rewrite_where_clause(
2041 context.config.fn_brace_style(),
2042 Shape::indented(indent, context.config),
2049 // If there are neither where clause nor return type, we may be missing comments between
2051 if where_clause_str.is_empty() {
2052 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2053 match recover_missing_comment_in_span(
2054 mk_sp(args_span.hi(), ret_span.hi()),
2057 last_line_width(&result),
2059 Some(ref missing_comment) if !missing_comment.is_empty() => {
2060 result.push_str(missing_comment);
2061 force_new_line_for_brace = true;
2068 result.push_str(&where_clause_str);
2070 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2071 Some((result, force_new_line_for_brace))
2074 #[derive(Copy, Clone)]
2075 struct WhereClauseOption {
2076 suppress_comma: bool, // Force no trailing comma
2077 snuggle: bool, // Do not insert newline before `where`
2078 compress_where: bool, // Try single line where clause instead of vertical layout
2081 impl WhereClauseOption {
2082 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2084 suppress_comma: suppress_comma,
2086 compress_where: false,
2090 pub fn compressed() -> WhereClauseOption {
2092 suppress_comma: true,
2094 compress_where: true,
2098 pub fn snuggled(current: &str) -> WhereClauseOption {
2100 suppress_comma: false,
2101 snuggle: trimmed_last_line_width(current) == 1,
2102 compress_where: false,
2108 context: &RewriteContext,
2110 explicit_self: Option<&ast::ExplicitSelf>,
2111 one_line_budget: usize,
2112 multi_line_budget: usize,
2117 generics_str_contains_newline: bool,
2118 ) -> Option<String> {
2119 let mut arg_item_strs = try_opt!(
2122 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2124 .collect::<Option<Vec<_>>>()
2127 // Account for sugary self.
2128 // FIXME: the comment for the self argument is dropped. This is blocked
2129 // on rust issue #27522.
2130 let min_args = explicit_self
2131 .and_then(|explicit_self| {
2132 rewrite_explicit_self(explicit_self, args, context)
2134 .map_or(1, |self_str| {
2135 arg_item_strs[0] = self_str;
2139 // Comments between args.
2140 let mut arg_items = Vec::new();
2142 arg_items.push(ListItem::from_str(""));
2145 // FIXME(#21): if there are no args, there might still be a comment, but
2146 // without spans for the comment or parens, there is no chance of
2147 // getting it right. You also don't get to put a comment on self, unless
2149 if args.len() >= min_args || variadic {
2150 let comment_span_start = if min_args == 2 {
2151 let second_arg_start = if arg_has_pattern(&args[1]) {
2152 args[1].pat.span.lo()
2154 args[1].ty.span.lo()
2156 let reduced_span = mk_sp(span.lo(), second_arg_start);
2158 context.codemap.span_after_last(reduced_span, ",")
2163 enum ArgumentKind<'a> {
2164 Regular(&'a ast::Arg),
2168 let variadic_arg = if variadic {
2169 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2170 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2171 Some(ArgumentKind::Variadic(variadic_start))
2176 let more_items = itemize_list(
2178 args[min_args - 1..]
2180 .map(ArgumentKind::Regular)
2181 .chain(variadic_arg),
2184 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2185 ArgumentKind::Variadic(start) => start,
2188 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2189 ArgumentKind::Variadic(start) => start + BytePos(3),
2192 ArgumentKind::Regular(..) => None,
2193 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2200 arg_items.extend(more_items);
2203 let fits_in_one_line = !generics_str_contains_newline
2204 && (arg_items.is_empty()
2205 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2207 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2208 item.item = Some(arg);
2211 let last_line_ends_with_comment = arg_items
2214 .and_then(|item| item.post_comment.as_ref())
2215 .map_or(false, |s| s.trim().starts_with("//"));
2217 let (indent, trailing_comma) = match context.config.fn_args_layout() {
2218 IndentStyle::Block if fits_in_one_line => {
2219 (indent.block_indent(context.config), SeparatorTactic::Never)
2221 IndentStyle::Block => (
2222 indent.block_indent(context.config),
2223 context.config.trailing_comma(),
2225 IndentStyle::Visual if last_line_ends_with_comment => {
2226 (arg_indent, context.config.trailing_comma())
2228 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2231 let tactic = definitive_tactic(
2233 context.config.fn_args_density().to_list_tactic(),
2237 let budget = match tactic {
2238 DefinitiveListTactic::Horizontal => one_line_budget,
2239 _ => multi_line_budget,
2242 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2244 let fmt = ListFormatting {
2247 trailing_separator: if variadic {
2248 SeparatorTactic::Never
2252 separator_place: SeparatorPlace::Back,
2253 shape: Shape::legacy(budget, indent),
2254 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2255 preserve_newline: true,
2256 config: context.config,
2259 write_list(&arg_items, &fmt)
2262 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2263 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2264 ident.node != symbol::keywords::Invalid.ident()
2270 fn compute_budgets_for_args(
2271 context: &RewriteContext,
2275 newline_brace: bool,
2277 force_vertical_layout: bool,
2278 ) -> Option<((usize, usize, Indent))> {
2280 "compute_budgets_for_args {} {:?}, {}, {}",
2286 // Try keeping everything on the same line.
2287 if !result.contains('\n') && !force_vertical_layout {
2288 // 2 = `()`, 3 = `() `, space is before ret_string.
2289 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2290 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2300 let one_line_budget = context.budget(used_space);
2302 if one_line_budget > 0 {
2304 let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2305 IndentStyle::Block => {
2306 let indent = indent.block_indent(context.config);
2307 (indent, context.budget(indent.width() + 1))
2309 IndentStyle::Visual => {
2310 let indent = indent + result.len() + 1;
2311 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2312 (indent, context.budget(multi_line_overhead))
2316 return Some((one_line_budget, multi_line_budget, indent));
2320 // Didn't work. we must force vertical layout and put args on a newline.
2321 let new_indent = indent.block_indent(context.config);
2322 let used_space = match context.config.fn_args_layout() {
2324 IndentStyle::Block => new_indent.width() + 1,
2325 // Account for `)` and possibly ` {`.
2326 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2328 Some((0, context.budget(used_space), new_indent))
2331 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2332 match (config.fn_brace_style(), config.where_density()) {
2333 (BraceStyle::AlwaysNextLine, _) => true,
2334 (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2335 (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2336 (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2341 fn rewrite_generics(
2342 context: &RewriteContext,
2343 generics: &ast::Generics,
2346 ) -> Option<String> {
2347 let g_shape = try_opt!(generics_shape_from_config(context.config, shape, 0));
2348 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2349 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2350 rewrite_generics_inner(context, generics, g_shape, 0, span)
2354 fn rewrite_generics_inner(
2355 context: &RewriteContext,
2356 generics: &ast::Generics,
2358 one_line_width: usize,
2360 ) -> Option<String> {
2361 // FIXME: convert bounds to where clauses where they get too big or if
2362 // there is a where clause at all.
2365 enum GenericsArg<'a> {
2366 Lifetime(&'a ast::LifetimeDef),
2367 TyParam(&'a ast::TyParam),
2369 impl<'a> Rewrite for GenericsArg<'a> {
2370 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2372 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2373 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2377 impl<'a> Spanned for GenericsArg<'a> {
2378 fn span(&self) -> Span {
2380 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2381 GenericsArg::TyParam(ref ty) => ty.span(),
2386 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2387 return Some(String::new());
2390 let generics_args = generics
2393 .map(|lt| GenericsArg::Lifetime(lt))
2394 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2395 let items = itemize_list(
2399 |arg| arg.span().lo(),
2400 |arg| arg.span().hi(),
2401 |arg| arg.rewrite(context, shape),
2402 context.codemap.span_after(span, "<"),
2406 format_generics_item_list(context, items, shape, one_line_width)
2409 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2410 match config.generics_indent() {
2411 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2412 IndentStyle::Block => {
2416 .block_indent(config.tab_spaces())
2417 .with_max_width(config)
2423 pub fn format_generics_item_list<I>(
2424 context: &RewriteContext,
2427 one_line_budget: usize,
2430 I: Iterator<Item = ListItem>,
2432 let item_vec = items.collect::<Vec<_>>();
2434 let tactic = definitive_tactic(
2436 ListTactic::HorizontalVertical,
2440 let fmt = ListFormatting {
2443 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2444 SeparatorTactic::Never
2446 context.config.trailing_comma()
2448 separator_place: SeparatorPlace::Back,
2450 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2451 preserve_newline: true,
2452 config: context.config,
2455 let list_str = try_opt!(write_list(&item_vec, &fmt));
2457 Some(wrap_generics_with_angle_brackets(
2464 pub fn wrap_generics_with_angle_brackets(
2465 context: &RewriteContext,
2467 list_offset: Indent,
2469 if context.config.generics_indent() == IndentStyle::Block
2470 && (list_str.contains('\n') || list_str.ends_with(','))
2474 list_offset.to_string(context.config),
2477 .block_unindent(context.config)
2478 .to_string(context.config)
2480 } else if context.config.spaces_within_angle_brackets() {
2481 format!("< {} >", list_str)
2483 format!("<{}>", list_str)
2487 fn rewrite_trait_bounds(
2488 context: &RewriteContext,
2489 type_param_bounds: &ast::TyParamBounds,
2491 ) -> Option<String> {
2492 let bounds: &[_] = type_param_bounds;
2494 if bounds.is_empty() {
2495 return Some(String::new());
2497 let bound_str = try_opt!(
2500 .map(|ty_bound| ty_bound.rewrite(context, shape))
2501 .collect::<Option<Vec<_>>>()
2503 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2506 fn rewrite_where_clause_rfc_style(
2507 context: &RewriteContext,
2508 where_clause: &ast::WhereClause,
2511 span_end: Option<BytePos>,
2512 span_end_before_where: BytePos,
2513 where_clause_option: WhereClauseOption,
2514 ) -> Option<String> {
2515 let block_shape = shape.block().with_max_width(context.config);
2517 let (span_before, span_after) =
2518 missing_span_before_after_where(span_end_before_where, where_clause);
2519 let (comment_before, comment_after) = try_opt!(rewrite_comments_before_after_where(
2526 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2529 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2532 let clause_shape = block_shape.block_indent(context.config.tab_spaces());
2533 // each clause on one line, trailing comma (except if suppress_comma)
2534 let span_start = where_clause.predicates[0].span().lo();
2535 // If we don't have the start of the next span, then use the end of the
2536 // predicates, but that means we miss comments.
2537 let len = where_clause.predicates.len();
2538 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2539 let span_end = span_end.unwrap_or(end_of_preds);
2540 let items = itemize_list(
2542 where_clause.predicates.iter(),
2544 |pred| pred.span().lo(),
2545 |pred| pred.span().hi(),
2546 |pred| pred.rewrite(context, block_shape),
2551 let comma_tactic = if where_clause_option.suppress_comma {
2552 SeparatorTactic::Never
2554 context.config.trailing_comma()
2557 let fmt = ListFormatting {
2558 tactic: DefinitiveListTactic::Vertical,
2560 trailing_separator: comma_tactic,
2561 separator_place: SeparatorPlace::Back,
2562 shape: clause_shape,
2563 ends_with_newline: true,
2564 preserve_newline: true,
2565 config: context.config,
2567 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
2569 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2572 format!("\n{}", shape.indent.to_string(context.config))
2574 let newline_before_where = comment_separator(&comment_before, shape);
2575 let newline_after_where = comment_separator(&comment_after, clause_shape);
2578 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2579 && comment_after.is_empty() && !preds_str.contains('\n')
2580 && 6 + preds_str.len() <= shape.width
2584 format!("\n{}", clause_shape.indent.to_string(context.config))
2587 "{}{}{}where{}{}{}{}",
2590 newline_before_where,
2591 newline_after_where,
2598 fn rewrite_where_clause(
2599 context: &RewriteContext,
2600 where_clause: &ast::WhereClause,
2601 brace_style: BraceStyle,
2605 span_end: Option<BytePos>,
2606 span_end_before_where: BytePos,
2607 where_clause_option: WhereClauseOption,
2608 ) -> Option<String> {
2609 if where_clause.predicates.is_empty() {
2610 return Some(String::new());
2613 if context.config.where_style() == Style::Rfc {
2614 return rewrite_where_clause_rfc_style(
2620 span_end_before_where,
2621 where_clause_option,
2625 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2627 let offset = match context.config.where_pred_indent() {
2628 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2629 // 6 = "where ".len()
2630 IndentStyle::Visual => shape.indent + extra_indent + 6,
2632 // FIXME: if where_pred_indent != Visual, then the budgets below might
2633 // be out by a char or two.
2635 let budget = context.config.max_width() - offset.width();
2636 let span_start = where_clause.predicates[0].span().lo();
2637 // If we don't have the start of the next span, then use the end of the
2638 // predicates, but that means we miss comments.
2639 let len = where_clause.predicates.len();
2640 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2641 let span_end = span_end.unwrap_or(end_of_preds);
2642 let items = itemize_list(
2644 where_clause.predicates.iter(),
2646 |pred| pred.span().lo(),
2647 |pred| pred.span().hi(),
2648 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2653 let item_vec = items.collect::<Vec<_>>();
2654 // FIXME: we don't need to collect here if the where_layout isn't
2655 // HorizontalVertical.
2656 let tactic = definitive_tactic(
2658 context.config.where_layout(),
2663 let mut comma_tactic = context.config.trailing_comma();
2664 // Kind of a hack because we don't usually have trailing commas in where clauses.
2665 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2666 comma_tactic = SeparatorTactic::Never;
2669 let fmt = ListFormatting {
2672 trailing_separator: comma_tactic,
2673 separator_place: SeparatorPlace::Back,
2674 shape: Shape::legacy(budget, offset),
2675 ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2676 preserve_newline: true,
2677 config: context.config,
2679 let preds_str = try_opt!(write_list(&item_vec, &fmt));
2681 let end_length = if terminator == "{" {
2682 // If the brace is on the next line we don't need to count it otherwise it needs two
2685 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2686 BraceStyle::PreferSameLine => 2,
2688 } else if terminator == "=" {
2693 if density == Density::Tall || preds_str.contains('\n')
2694 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2698 (shape.indent + extra_indent).to_string(context.config),
2702 Some(format!(" where {}", preds_str))
2706 fn missing_span_before_after_where(
2707 before_item_span_end: BytePos,
2708 where_clause: &ast::WhereClause,
2710 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2712 let pos_after_where = where_clause.span.lo() + BytePos(5);
2713 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2714 (missing_span_before, missing_span_after)
2717 fn rewrite_comments_before_after_where(
2718 context: &RewriteContext,
2719 span_before_where: Span,
2720 span_after_where: Span,
2722 ) -> Option<(String, String)> {
2723 let before_comment = try_opt!(rewrite_missing_comment(span_before_where, shape, context));
2724 let after_comment = try_opt!(rewrite_missing_comment(
2726 shape.block_indent(context.config.tab_spaces()),
2729 Some((before_comment, after_comment))
2732 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2733 format!("{}{}{}", format_visibility(vis), item_name, ident)
2737 context: &RewriteContext,
2738 generics: &ast::Generics,
2741 brace_style: BraceStyle,
2742 force_same_line_brace: bool,
2746 ) -> Option<String> {
2747 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2748 let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
2750 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2751 let budget = context.budget(last_line_used_width(&result, offset.width()));
2752 let option = WhereClauseOption::snuggled(&result);
2753 let where_clause_str = try_opt!(rewrite_where_clause(
2755 &generics.where_clause,
2757 Shape::legacy(budget, offset.block_only()),
2764 result.push_str(&where_clause_str);
2765 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2766 || (generics.where_clause.predicates.is_empty()
2767 && trimmed_last_line_width(&result) == 1)
2769 force_same_line_brace || trimmed_last_line_width(&result) == 1
2770 || brace_style != BraceStyle::AlwaysNextLine
2772 let total_used_width = last_line_used_width(&result, used_width);
2773 let remaining_budget = context.budget(total_used_width);
2774 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2775 // and hence we take the closer into account as well for one line budget.
2776 // We assume that the closer has the same length as the opener.
2777 let overhead = if force_same_line_brace {
2778 1 + opener.len() + opener.len()
2782 let forbid_same_line_brace = overhead > remaining_budget;
2783 if !forbid_same_line_brace && same_line_brace {
2787 result.push_str(&offset.block_only().to_string(context.config));
2789 result.push_str(opener);
2794 impl Rewrite for ast::ForeignItem {
2795 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2796 let attrs_str = try_opt!(self.attrs.rewrite(context, shape));
2797 // Drop semicolon or it will be interpreted as comment.
2798 // FIXME: this may be a faulty span from libsyntax.
2799 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2801 let item_str = try_opt!(match self.node {
2802 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2807 &FnSig::new(fn_decl, generics, self.vis.clone()),
2811 ).map(|(s, _)| format!("{};", s))
2813 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2814 // FIXME(#21): we're dropping potential comments in between the
2815 // function keywords here.
2816 let vis = format_visibility(&self.vis);
2817 let mut_str = if is_mutable { "mut " } else { "" };
2818 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2820 let shape = try_opt!(shape.sub_width(1));
2821 ty.rewrite(context, shape).map(|ty_str| {
2822 // 1 = space between prefix and type.
2823 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2826 let nested_indent = shape.indent.block_indent(context.config);
2827 format!("\n{}", nested_indent.to_string(context.config))
2829 format!("{}{}{};", prefix, sep, ty_str)
2834 let missing_span = if self.attrs.is_empty() {
2835 mk_sp(self.span.lo(), self.span.lo())
2837 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2839 combine_strs_with_missing_comments(