1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
16 use syntax::{abi, ast, ptr, symbol};
17 use syntax::ast::{CrateSugar, ImplItem};
18 use syntax::codemap::{BytePos, Span};
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle};
26 use expr::{choose_rhs, 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 {
42 colon_spaces(config.space_before_colon(), config.space_after_colon())
45 // Statements of the form
46 // let pat: ty = init;
47 impl Rewrite for ast::Local {
48 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
50 "Local::rewrite {:?} {} {:?}",
56 skip_out_of_file_lines_range!(context, self.span);
58 if contains_skip(&self.attrs) {
62 let attrs_str = self.attrs.rewrite(context, shape)?;
63 let mut result = if attrs_str.is_empty() {
66 combine_strs_with_missing_comments(
71 self.attrs.last().map(|a| a.span.hi()).unwrap(),
80 let pat_shape = shape.offset_left(4)?;
82 let pat_shape = pat_shape.sub_width(1)?;
83 let pat_str = self.pat.rewrite(context, pat_shape)?;
84 result.push_str(&pat_str);
86 // String that is placed within the assignment pattern and expression.
88 let mut infix = String::with_capacity(32);
90 if let Some(ref ty) = self.ty {
91 let separator = type_annotation_separator(context.config);
92 let indent = shape.indent + last_line_width(&result) + separator.len();
94 let budget = shape.width.checked_sub(indent.width() + 1)?;
95 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
97 infix.push_str(separator);
98 infix.push_str(&rewrite);
101 if self.init.is_some() {
102 infix.push_str(" =");
108 result.push_str(&infix);
110 if let Some(ref ex) = self.init {
111 // 1 = trailing semicolon;
112 let nested_shape = shape.sub_width(1)?;
114 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
122 // TODO convert to using rewrite style rather than visitor
123 // TODO format modules in this style
126 keyword: &'static str,
127 abi: Cow<'static, str>,
128 vis: Option<&'a ast::Visibility>,
129 body: Vec<BodyElement<'a>>,
134 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
137 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
141 .map(|i| BodyElement::ForeignItem(i))
148 enum BodyElement<'a> {
149 // Stmt(&'a ast::Stmt),
150 // Field(&'a ast::Field),
151 // Variant(&'a ast::Variant),
152 // Item(&'a ast::Item),
153 ForeignItem(&'a ast::ForeignItem),
156 /// Represents a fn's signature.
157 pub struct FnSig<'a> {
158 decl: &'a ast::FnDecl,
159 generics: &'a ast::Generics,
161 constness: ast::Constness,
162 defaultness: ast::Defaultness,
163 unsafety: ast::Unsafety,
164 visibility: ast::Visibility,
169 decl: &'a ast::FnDecl,
170 generics: &'a ast::Generics,
171 vis: ast::Visibility,
177 constness: ast::Constness::NotConst,
178 defaultness: ast::Defaultness::Final,
179 unsafety: ast::Unsafety::Normal,
184 pub fn from_method_sig(
185 method_sig: &'a ast::MethodSig,
186 generics: &'a ast::Generics,
189 unsafety: method_sig.unsafety,
190 constness: method_sig.constness.node,
191 defaultness: ast::Defaultness::Final,
193 decl: &*method_sig.decl,
195 visibility: ast::Visibility::Inherited,
200 fn_kind: &'a visit::FnKind,
201 generics: &'a ast::Generics,
202 decl: &'a ast::FnDecl,
203 defualtness: ast::Defaultness,
206 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
210 constness: constness.node,
211 defaultness: defualtness,
213 visibility: visibility.clone(),
215 visit::FnKind::Method(_, method_sig, vis, _) => {
216 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
217 fn_sig.defaultness = defualtness;
218 if let Some(vis) = vis {
219 fn_sig.visibility = vis.clone();
227 fn to_str(&self, context: &RewriteContext) -> String {
228 let mut result = String::with_capacity(128);
229 // Vis defaultness constness unsafety abi.
230 result.push_str(&*format_visibility(&self.visibility));
231 result.push_str(format_defaultness(self.defaultness));
232 result.push_str(format_constness(self.constness));
233 result.push_str(format_unsafety(self.unsafety));
234 result.push_str(&format_abi(
236 context.config.force_explicit_abi(),
243 impl<'a> FmtVisitor<'a> {
244 fn format_item(&mut self, item: Item) {
245 self.buffer.push_str(&item.abi);
247 let snippet = self.snippet(item.span);
248 let brace_pos = snippet.find_uncommented("{").unwrap();
250 self.buffer.push_str("{");
251 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
252 // FIXME: this skips comments between the extern keyword and the opening
254 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
255 self.block_indent = self.block_indent.block_indent(self.config);
257 if item.body.is_empty() {
258 self.format_missing_no_indent(item.span.hi() - BytePos(1));
259 self.block_indent = self.block_indent.block_unindent(self.config);
262 .push_str(&self.block_indent.to_string(self.config));
264 for item in &item.body {
265 self.format_body_element(item);
268 self.block_indent = self.block_indent.block_unindent(self.config);
269 self.format_missing_with_indent(item.span.hi() - BytePos(1));
273 self.buffer.push_str("}");
274 self.last_pos = item.span.hi();
277 fn format_body_element(&mut self, element: &BodyElement) {
279 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
283 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
284 let item = Item::from_foreign_mod(fm, span, self.config);
285 self.format_item(item);
289 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
290 let rewrite = item.rewrite(&self.get_context(), self.shape());
291 self.push_rewrite(item.span(), rewrite);
292 self.last_pos = item.span.hi();
302 ) -> Option<String> {
303 let context = self.get_context();
305 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
307 let (mut result, force_newline_brace) =
308 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
311 if self.config.brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
312 || last_line_width(&result) + 2 > self.shape().width
314 newline_brace = true;
315 } else if !result.contains('\n') {
316 newline_brace = false;
319 // Prepare for the function body by possibly adding a newline and
321 // FIXME we'll miss anything between the end of the signature and the
322 // start of the body, but we need more spans from the compiler to solve
326 result.push_str(&indent.to_string(self.config));
331 self.single_line_fn(&result, block).or_else(|| Some(result))
334 pub fn rewrite_required_fn(
338 sig: &ast::MethodSig,
339 generics: &ast::Generics,
341 ) -> Option<String> {
342 // Drop semicolon or it will be interpreted as comment.
343 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
344 let context = self.get_context();
346 let (mut result, _) = rewrite_fn_base(
350 &FnSig::from_method_sig(sig, generics),
356 // Re-attach semicolon
362 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
363 if fn_str.contains('\n') {
367 let codemap = self.get_context().codemap;
369 if self.config.empty_item_single_line() && is_empty_block(block, codemap)
370 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
372 return Some(format!("{}{{}}", fn_str));
375 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
377 if let Some(stmt) = block.stmts.first() {
378 match stmt_expr(stmt) {
380 let suffix = if semicolon_for_expr(&self.get_context(), e) {
386 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
388 .or_else(|| Some(self.snippet(e.span)))
390 None => stmt.rewrite(&self.get_context(), self.shape()),
397 if let Some(res) = rewrite {
398 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
399 if !res.contains('\n') && width <= self.config.max_width() {
400 return Some(format!("{}{{ {} }}", fn_str, res));
408 pub fn visit_static(&mut self, static_parts: &StaticParts) {
409 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
410 self.push_rewrite(static_parts.span, rewrite);
413 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
414 let is_tuple = struct_parts.def.is_tuple();
415 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
416 .map(|s| if is_tuple { s + ";" } else { s });
417 self.push_rewrite(struct_parts.span, rewrite);
423 vis: &ast::Visibility,
424 enum_def: &ast::EnumDef,
425 generics: &ast::Generics,
428 let enum_header = format_header("enum ", ident, vis);
429 self.buffer.push_str(&enum_header);
431 let enum_snippet = self.snippet(span);
432 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
433 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
434 let generics_str = format_generics(
437 self.config.brace_style(),
438 if enum_def.variants.is_empty() {
439 BracePos::ForceSameLine
444 mk_sp(span.lo(), body_start),
445 last_line_width(&enum_header),
447 self.buffer.push_str(&generics_str);
449 self.last_pos = body_start;
451 self.block_indent = self.block_indent.block_indent(self.config);
452 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
454 Some(ref body_str) => self.buffer.push_str(body_str),
455 None => self.format_missing_no_indent(span.hi() - BytePos(1)),
457 self.block_indent = self.block_indent.block_unindent(self.config);
459 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
461 .push_str(&self.block_indent.to_string(self.config));
463 self.buffer.push_str("}");
464 self.last_pos = span.hi();
467 // Format the body of an enum definition
468 fn format_variant_list(
470 enum_def: &ast::EnumDef,
473 ) -> Option<String> {
474 if enum_def.variants.is_empty() {
477 let mut result = String::with_capacity(1024);
479 let indentation = self.block_indent.to_string(self.config);
480 result.push_str(&indentation);
482 let itemize_list_with = |one_line_width: usize| {
485 enum_def.variants.iter(),
488 |f| if !f.node.attrs.is_empty() {
489 f.node.attrs[0].span.lo()
494 |f| self.format_variant(f, one_line_width),
500 let mut items: Vec<_> =
501 itemize_list_with(self.config.width_heuristics().struct_variant_width);
502 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
503 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
504 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
505 if has_multiline_variant && has_single_line_variant {
506 items = itemize_list_with(0);
509 let shape = self.shape().sub_width(2).unwrap();
510 let fmt = ListFormatting {
511 tactic: DefinitiveListTactic::Vertical,
513 trailing_separator: self.config.trailing_comma(),
514 separator_place: SeparatorPlace::Back,
516 ends_with_newline: true,
517 preserve_newline: true,
521 let list = write_list(&items, &fmt)?;
522 result.push_str(&list);
527 // Variant of an enum.
528 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
529 if contains_skip(&field.node.attrs) {
530 let lo = field.node.attrs[0].span.lo();
531 let span = mk_sp(lo, field.span.hi());
532 return Some(self.snippet(span));
535 let context = self.get_context();
537 let shape = self.shape().sub_width(1)?;
538 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
543 .map_or(field.span.lo(), |attr| attr.span.hi());
544 let span = mk_sp(lo, field.span.lo());
546 let variant_body = match field.node.data {
547 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
549 &StructParts::from_variant(field),
551 Some(one_line_width),
553 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
554 let lhs = format!("{} =", field.node.name);
555 rewrite_assign_rhs(&context, lhs, &**expr, shape)?
557 field.node.name.to_string()
561 let attrs_extendable = attrs_str.is_empty()
562 || (context.config.same_line_attributes() && 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.brace_style(),
597 Shape::legacy(where_budget, offset.block_only()),
606 // If there is no where clause, we may have missing comments between the trait name and
607 // the opening brace.
608 if generics.where_clause.predicates.is_empty() {
609 if let Some(hi) = where_span_end {
610 match recover_missing_comment_in_span(
611 mk_sp(self_ty.span.hi(), hi),
612 Shape::indented(offset, context.config),
614 last_line_width(&result),
616 Some(ref missing_comment) if !missing_comment.is_empty() => {
617 result.push_str(missing_comment);
624 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
625 result.push_str(&where_clause_str);
626 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
627 result.push_str(&format!("{}{{{}}}", &sep, &sep));
629 result.push_str(" {}");
634 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
636 let width = offset.block_indent + context.config.tab_spaces() - 1;
637 let where_indent = Indent::new(0, width);
638 result.push_str(&where_indent.to_string(context.config));
640 result.push_str(&where_clause_str);
642 match context.config.brace_style() {
643 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
644 BraceStyle::AlwaysNextLine => result.push_str(&sep),
645 BraceStyle::PreferSameLine => result.push(' '),
646 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
647 result.push_str(&sep);
655 let snippet = context.snippet(item.span);
656 let open_pos = snippet.find_uncommented("{")? + 1;
658 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
659 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
660 visitor.block_indent = offset.block_only().block_indent(context.config);
661 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
663 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
665 visitor.visit_impl_item(item);
668 visitor.format_missing(item.span.hi() - BytePos(1));
670 let inner_indent_str = visitor.block_indent.to_string(context.config);
671 let outer_indent_str = offset.block_only().to_string(context.config);
674 result.push_str(&inner_indent_str);
675 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
677 result.push_str(&outer_indent_str);
680 if result.ends_with('{') {
681 result.push_str(&sep);
691 fn is_impl_single_line(
692 context: &RewriteContext,
695 where_clause_str: &str,
698 let snippet = context.snippet(item.span);
699 let open_pos = snippet.find_uncommented("{")? + 1;
702 context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
703 && result.len() + where_clause_str.len() <= context.config.max_width()
704 && !contains_comment(&snippet[open_pos..]),
708 fn format_impl_ref_and_type(
709 context: &RewriteContext,
712 ) -> Option<String> {
713 if let ast::ItemKind::Impl(
723 let mut result = String::with_capacity(128);
725 result.push_str(&format_visibility(&item.vis));
726 result.push_str(format_defaultness(defaultness));
727 result.push_str(format_unsafety(unsafety));
728 result.push_str("impl");
730 let lo = context.codemap.span_after(item.span, "impl");
731 let hi = match *trait_ref {
732 Some(ref tr) => tr.path.span.lo(),
733 None => self_ty.span.lo(),
735 let shape = generics_shape_from_config(
737 Shape::indented(offset + last_line_width(&result), context.config),
740 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
742 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
744 let polarity_str = if polarity == ast::ImplPolarity::Negative {
750 if let Some(ref trait_ref) = *trait_ref {
751 let result_len = result.len();
752 if let Some(trait_ref_str) = rewrite_trait_ref(
761 result.push_str(&trait_ref_str);
764 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
765 result.push_str(&rewrite_trait_ref(
776 result.push_str(&generics_str);
779 // Try to put the self type in a single line.
781 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
782 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
783 // If there is no where clause adapt budget for type formatting to take space and curly
784 // brace into account.
785 match context.config.brace_style() {
786 BraceStyle::AlwaysNextLine => 0,
792 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
793 // 1 = space before the type.
794 let budget = context.budget(used_space + 1);
795 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
796 if !self_ty_str.contains('\n') {
797 if trait_ref.is_some() {
798 result.push_str(" for ");
802 result.push_str(&self_ty_str);
807 // Couldn't fit the self type on a single line, put it on a new line.
809 // Add indentation of one additional tab.
810 let new_line_offset = offset.block_indent(context.config);
811 result.push_str(&new_line_offset.to_string(context.config));
812 if trait_ref.is_some() {
813 result.push_str("for ");
815 let budget = context.budget(last_line_width(&result));
816 let type_offset = match context.config.indent_style() {
817 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
818 IndentStyle::Block => new_line_offset,
820 result.push_str(&*self_ty.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 struct StructParts<'a> {
869 vis: &'a ast::Visibility,
870 def: &'a ast::VariantData,
871 generics: Option<&'a ast::Generics>,
875 impl<'a> StructParts<'a> {
876 fn format_header(&self) -> String {
877 format_header(self.prefix, self.ident, self.vis)
880 fn from_variant(variant: &'a ast::Variant) -> Self {
883 ident: variant.node.name,
884 vis: &ast::Visibility::Inherited,
885 def: &variant.node.data,
891 pub fn from_item(item: &'a ast::Item) -> Self {
892 let (prefix, def, generics) = match item.node {
893 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
894 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
902 generics: Some(generics),
909 context: &RewriteContext,
910 struct_parts: &StructParts,
912 one_line_width: Option<usize>,
913 ) -> Option<String> {
914 match *struct_parts.def {
915 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
916 ast::VariantData::Tuple(ref fields, _) => {
917 format_tuple_struct(context, struct_parts, fields, offset)
919 ast::VariantData::Struct(ref fields, _) => {
920 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
925 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
926 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
929 let mut result = String::with_capacity(128);
930 let header = format!(
932 format_visibility(&item.vis),
933 format_unsafety(unsafety),
937 result.push_str(&header);
939 let body_lo = context.codemap.span_after(item.span, "{");
941 let shape = Shape::indented(offset, context.config);
943 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
944 result.push_str(&generics_str);
946 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
947 if !type_param_bounds.is_empty() {
948 let ident_hi = context.codemap.span_after(item.span, &format!("{}", item.ident));
949 let bound_hi = type_param_bounds.last().unwrap().span().hi();
950 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
951 if contains_comment(&snippet) {
955 let trait_bound_str = rewrite_trait_bounds(
958 Shape::indented(offset, context.config),
960 // If the trait, generics, and trait bound cannot fit on the same line,
961 // put the trait bounds on an indented new line
962 if offset.width() + last_line_width(&result) + trait_bound_str.len()
963 > context.config.comment_width()
966 let trait_indent = offset.block_only().block_indent(context.config);
967 result.push_str(&trait_indent.to_string(context.config));
969 result.push_str(&trait_bound_str);
972 if context.config.indent_style() == IndentStyle::Block && result.is_empty() {
978 let where_budget = context.budget(last_line_width(&result));
979 let pos_before_where = if type_param_bounds.is_empty() {
980 generics.where_clause.span.lo()
982 type_param_bounds[type_param_bounds.len() - 1].span().hi()
984 let option = WhereClauseOption::snuggled(&generics_str);
985 let where_clause_str = rewrite_where_clause(
987 &generics.where_clause,
988 context.config.brace_style(),
989 Shape::legacy(where_budget, offset.block_only()),
997 // If the where clause cannot fit on the same line,
998 // put the where clause on a new line
999 if !where_clause_str.contains('\n')
1000 && last_line_width(&result) + where_clause_str.len() + offset.width()
1001 > context.config.comment_width()
1004 let width = offset.block_indent + context.config.tab_spaces() - 1;
1005 let where_indent = Indent::new(0, width);
1006 result.push_str(&where_indent.to_string(context.config));
1008 result.push_str(&where_clause_str);
1010 if generics.where_clause.predicates.is_empty() {
1011 let item_snippet = context.snippet(item.span);
1012 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
1014 let comment_hi = body_lo - BytePos(1);
1015 let comment_lo = item.span.lo() + BytePos(lo as u32);
1016 if comment_lo < comment_hi {
1017 match recover_missing_comment_in_span(
1018 mk_sp(comment_lo, comment_hi),
1019 Shape::indented(offset, context.config),
1021 last_line_width(&result),
1023 Some(ref missing_comment) if !missing_comment.is_empty() => {
1024 result.push_str(missing_comment);
1032 match context.config.brace_style() {
1033 _ if last_line_contains_single_line_comment(&result) => {
1035 result.push_str(&offset.to_string(context.config));
1037 BraceStyle::AlwaysNextLine => {
1039 result.push_str(&offset.to_string(context.config));
1041 BraceStyle::PreferSameLine => result.push(' '),
1042 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1043 && (!trait_items.is_empty() || result.contains('\n'))
1046 result.push_str(&offset.to_string(context.config));
1053 let snippet = context.snippet(item.span);
1054 let open_pos = snippet.find_uncommented("{")? + 1;
1056 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1057 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1058 visitor.block_indent = offset.block_only().block_indent(context.config);
1059 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1061 for item in trait_items {
1062 visitor.visit_trait_item(item);
1065 visitor.format_missing(item.span.hi() - BytePos(1));
1067 let inner_indent_str = visitor.block_indent.to_string(context.config);
1068 let outer_indent_str = offset.block_only().to_string(context.config);
1071 result.push_str(&inner_indent_str);
1072 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1074 result.push_str(&outer_indent_str);
1075 } else if result.contains('\n') {
1086 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1087 let header_str = format_header(p.prefix, p.ident, p.vis);
1088 let generics_str = if let Some(generics) = p.generics {
1089 let hi = if generics.where_clause.predicates.is_empty() {
1092 generics.where_clause.span.hi()
1097 context.config.brace_style(),
1100 mk_sp(generics.span.lo(), hi),
1101 last_line_width(&header_str),
1106 Some(format!("{}{};", header_str, generics_str))
1109 pub fn format_struct_struct(
1110 context: &RewriteContext,
1111 struct_parts: &StructParts,
1112 fields: &[ast::StructField],
1114 one_line_width: Option<usize>,
1115 ) -> Option<String> {
1116 let mut result = String::with_capacity(1024);
1117 let span = struct_parts.span;
1119 let header_str = struct_parts.format_header();
1120 result.push_str(&header_str);
1122 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1123 let body_lo = context.codemap.span_after(span, "{");
1125 let generics_str = match struct_parts.generics {
1126 Some(g) => format_generics(
1129 context.config.brace_style(),
1130 if fields.is_empty() {
1131 BracePos::ForceSameLine
1136 mk_sp(header_hi, body_lo),
1137 last_line_width(&result),
1140 // 3 = ` {}`, 2 = ` {`.
1141 let overhead = if fields.is_empty() { 3 } else { 2 };
1142 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1143 || context.config.max_width() < overhead + result.len()
1145 format!("\n{}{{", offset.block_only().to_string(context.config))
1152 let overhead = if fields.is_empty() { 1 } else { 0 };
1153 let total_width = result.len() + generics_str.len() + overhead;
1154 if !generics_str.is_empty() && !generics_str.contains('\n')
1155 && total_width > context.config.max_width()
1158 result.push_str(&offset.to_string(context.config));
1159 result.push_str(generics_str.trim_left());
1161 result.push_str(&generics_str);
1164 if fields.is_empty() {
1165 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1166 if snippet.trim().is_empty() {
1168 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1170 result.push_str(snippet.trim_right());
1172 result.push_str(&offset.to_string(context.config));
1174 result.push_str(&snippet);
1177 return Some(result);
1181 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1182 let one_line_budget =
1183 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1185 let items_str = rewrite_with_alignment(
1188 Shape::indented(offset, context.config).sub_width(1)?,
1189 mk_sp(body_lo, span.hi()),
1193 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1194 Some(format!("{} {} }}", result, items_str))
1200 .block_indent(context.config)
1201 .to_string(context.config),
1203 offset.to_string(context.config)
1208 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1209 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1210 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1211 fn get_bytepos_after_visibility(
1212 context: &RewriteContext,
1213 vis: &ast::Visibility,
1218 ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1220 .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1221 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1222 ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1223 _ => default_span.lo(),
1227 fn format_tuple_struct(
1228 context: &RewriteContext,
1229 struct_parts: &StructParts,
1230 fields: &[ast::StructField],
1232 ) -> Option<String> {
1233 let mut result = String::with_capacity(1024);
1234 let span = struct_parts.span;
1236 let header_str = struct_parts.format_header();
1237 result.push_str(&header_str);
1239 let body_lo = if fields.is_empty() {
1240 let lo = get_bytepos_after_visibility(context, struct_parts.vis, span, ")");
1241 context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1245 let body_hi = if fields.is_empty() {
1246 context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1248 // This is a dirty hack to work around a missing `)` from the span of the last field.
1249 let last_arg_span = fields[fields.len() - 1].span;
1250 if context.snippet(last_arg_span).ends_with(')') {
1255 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1259 let where_clause_str = match struct_parts.generics {
1261 let budget = context.budget(last_line_width(&header_str));
1262 let shape = Shape::legacy(budget, offset);
1263 let g_span = mk_sp(span.lo(), body_lo);
1264 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1265 result.push_str(&generics_str);
1267 let where_budget = context.budget(last_line_width(&result));
1268 let option = WhereClauseOption::new(true, false);
1269 rewrite_where_clause(
1271 &generics.where_clause,
1272 context.config.brace_style(),
1273 Shape::legacy(where_budget, offset.block_only()),
1274 Density::Compressed,
1282 None => "".to_owned(),
1285 if fields.is_empty() {
1287 let used_width = last_line_used_width(&result, offset.width()) + 3;
1288 if used_width > context.config.max_width() {
1290 result.push_str(&offset
1291 .block_indent(context.config)
1292 .to_string(context.config))
1295 let snippet = context.snippet(mk_sp(
1297 context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1299 if snippet.is_empty() {
1301 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1302 result.push_str(snippet.trim_right());
1304 result.push_str(&offset.to_string(context.config));
1306 result.push_str(&snippet);
1310 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1311 let fields = &fields.iter().collect::<Vec<_>>()[..];
1312 let one_line_width = context.config.width_heuristics().fn_call_width;
1313 result = rewrite_call_inner(context, &result, fields, span, shape, one_line_width, false)?;
1316 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1317 && (result.contains('\n')
1318 || offset.block_indent + result.len() + where_clause_str.len() + 1
1319 > context.config.max_width())
1321 // We need to put the where clause on a new line, but we didn't
1322 // know that earlier, so the where clause will not be indented properly.
1324 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1325 .to_string(context.config));
1327 result.push_str(&where_clause_str);
1332 pub fn rewrite_type_alias(
1333 context: &RewriteContext,
1337 generics: &ast::Generics,
1338 vis: &ast::Visibility,
1340 ) -> Option<String> {
1341 let mut result = String::with_capacity(128);
1343 result.push_str(&format_visibility(vis));
1344 result.push_str("type ");
1345 result.push_str(&ident.to_string());
1348 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1349 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1350 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1351 result.push_str(&generics_str);
1353 let where_budget = context.budget(last_line_width(&result));
1354 let option = WhereClauseOption::snuggled(&result);
1355 let where_clause_str = rewrite_where_clause(
1357 &generics.where_clause,
1358 context.config.brace_style(),
1359 Shape::legacy(where_budget, indent),
1367 result.push_str(&where_clause_str);
1368 if where_clause_str.is_empty() {
1369 result.push_str(" = ");
1371 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1374 let line_width = last_line_width(&result);
1375 // This checked_sub may fail as the extra space after '=' is not taken into account
1376 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1377 let budget = context.budget(indent.width() + line_width + ";".len());
1378 let type_indent = indent + line_width;
1379 // Try to fit the type on the same line
1380 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1382 // The line was too short, try to put the type on the next line
1384 // Remove the space after '='
1386 let type_indent = indent.block_indent(context.config);
1388 result.push_str(&type_indent.to_string(context.config));
1389 let budget = context.budget(type_indent.width() + ";".len());
1390 ty.rewrite(context, Shape::legacy(budget, type_indent))
1392 result.push_str(&ty_str);
1393 result.push_str(";");
1397 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1399 if config.space_before_colon() { " " } else { "" },
1400 if config.space_after_colon() { " " } else { "" },
1404 pub fn rewrite_struct_field_prefix(
1405 context: &RewriteContext,
1406 field: &ast::StructField,
1407 ) -> Option<String> {
1408 let vis = format_visibility(&field.vis);
1409 let type_annotation_spacing = type_annotation_spacing(context.config);
1410 Some(match field.ident {
1411 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1412 None => format!("{}", vis),
1416 impl Rewrite for ast::StructField {
1417 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1418 rewrite_struct_field(context, self, shape, 0)
1422 pub fn rewrite_struct_field(
1423 context: &RewriteContext,
1424 field: &ast::StructField,
1426 lhs_max_width: usize,
1427 ) -> Option<String> {
1428 if contains_skip(&field.attrs) {
1429 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1432 let type_annotation_spacing = type_annotation_spacing(context.config);
1433 let prefix = rewrite_struct_field_prefix(context, field)?;
1435 let attrs_str = field.attrs.rewrite(context, shape)?;
1436 let attrs_extendable = attrs_str.is_empty()
1437 || (context.config.same_line_attributes() && is_attributes_extendable(&attrs_str));
1438 let missing_span = if field.attrs.is_empty() {
1439 mk_sp(field.span.lo(), field.span.lo())
1441 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1443 let mut spacing = String::from(if field.ident.is_some() {
1444 type_annotation_spacing.1
1448 // Try to put everything on a single line.
1449 let attr_prefix = combine_strs_with_missing_comments(
1457 let overhead = last_line_width(&attr_prefix);
1458 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1459 for _ in 0..lhs_offset {
1462 // In this extreme case we will be missing a space betweeen an attribute and a field.
1463 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1466 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1467 let mut orig_ty = field.ty.rewrite(context, ty_shape);
1468 if let Some(ref ty) = orig_ty {
1469 if !ty.contains('\n') {
1470 return Some(attr_prefix + &spacing + ty);
1474 // We must use multiline. We are going to put attributes and a field on different lines.
1476 let rhs_shape = shape.offset_left(last_line_width(&prefix) + 1)?;
1477 orig_ty = field.ty.rewrite(context, rhs_shape);
1478 let field_str = if prefix.is_empty() {
1481 prefix + &choose_rhs(context, &*field.ty, rhs_shape, orig_ty)?
1483 combine_strs_with_missing_comments(context, &attrs_str, &field_str, missing_span, shape, false)
1486 pub struct StaticParts<'a> {
1488 vis: &'a ast::Visibility,
1491 mutability: ast::Mutability,
1492 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1496 impl<'a> StaticParts<'a> {
1497 pub fn from_item(item: &'a ast::Item) -> Self {
1498 let (prefix, ty, mutability, expr) = match item.node {
1499 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1500 ast::ItemKind::Const(ref ty, ref expr) => {
1501 ("const", ty, ast::Mutability::Immutable, expr)
1503 _ => unreachable!(),
1510 mutability: mutability,
1511 expr_opt: Some(expr),
1516 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1517 let (ty, expr_opt) = match ti.node {
1518 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1519 _ => unreachable!(),
1523 vis: &ast::Visibility::Inherited,
1526 mutability: ast::Mutability::Immutable,
1527 expr_opt: expr_opt.as_ref(),
1532 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1533 let (ty, expr) = match ii.node {
1534 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1535 _ => unreachable!(),
1542 mutability: ast::Mutability::Immutable,
1543 expr_opt: Some(expr),
1550 context: &RewriteContext,
1551 static_parts: &StaticParts,
1553 ) -> Option<String> {
1554 let colon = colon_spaces(
1555 context.config.space_before_colon(),
1556 context.config.space_after_colon(),
1558 let prefix = format!(
1560 format_visibility(static_parts.vis),
1561 static_parts.prefix,
1562 format_mutability(static_parts.mutability),
1568 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1569 let ty_str = static_parts.ty.rewrite(context, ty_shape)?;
1571 if let Some(expr) = static_parts.expr_opt {
1572 let lhs = format!("{}{} =", prefix, ty_str);
1574 let remaining_width = context.budget(offset.block_indent + 1);
1579 Shape::legacy(remaining_width, offset.block_only()),
1580 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1581 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1583 Some(format!("{}{};", prefix, ty_str))
1587 pub fn rewrite_associated_type(
1589 ty_opt: Option<&ptr::P<ast::Ty>>,
1590 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1591 context: &RewriteContext,
1593 ) -> Option<String> {
1594 let prefix = format!("type {}", ident);
1596 let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1598 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1599 let bound_str = bounds
1601 .map(|ty_bound| ty_bound.rewrite(context, shape))
1602 .collect::<Option<Vec<_>>>()?;
1603 if !bounds.is_empty() {
1604 format!(": {}", join_bounds(context, shape, &bound_str))
1612 if let Some(ty) = ty_opt {
1614 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1615 let lhs = format!("{}{} =", prefix, type_bounds_str);
1616 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1618 Some(format!("{}{};", prefix, type_bounds_str))
1622 pub fn rewrite_associated_impl_type(
1624 defaultness: ast::Defaultness,
1625 ty_opt: Option<&ptr::P<ast::Ty>>,
1626 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1627 context: &RewriteContext,
1629 ) -> Option<String> {
1630 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1633 ast::Defaultness::Default => Some(format!("default {}", result)),
1638 impl Rewrite for ast::FunctionRetTy {
1639 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1641 ast::FunctionRetTy::Default(_) => Some(String::new()),
1642 ast::FunctionRetTy::Ty(ref ty) => {
1643 let inner_width = shape.width.checked_sub(3)?;
1644 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1645 .map(|r| format!("-> {}", r))
1651 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1653 ast::TyKind::Infer => {
1654 let original = context.snippet(ty.span);
1661 impl Rewrite for ast::Arg {
1662 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1663 if is_named_arg(self) {
1664 let mut result = self.pat
1665 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1667 if !is_empty_infer(context, &*self.ty) {
1668 if context.config.space_before_colon() {
1669 result.push_str(" ");
1671 result.push_str(":");
1672 if context.config.space_after_colon() {
1673 result.push_str(" ");
1675 let overhead = last_line_width(&result);
1676 let max_width = shape.width.checked_sub(overhead)?;
1677 let ty_str = self.ty
1678 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1679 result.push_str(&ty_str);
1684 self.ty.rewrite(context, shape)
1689 fn rewrite_explicit_self(
1690 explicit_self: &ast::ExplicitSelf,
1692 context: &RewriteContext,
1693 ) -> Option<String> {
1694 match explicit_self.node {
1695 ast::SelfKind::Region(lt, m) => {
1696 let mut_str = format_mutability(m);
1699 let lifetime_str = l.rewrite(
1701 Shape::legacy(context.config.max_width(), Indent::empty()),
1703 Some(format!("&{} {}self", lifetime_str, mut_str))
1705 None => Some(format!("&{}self", mut_str)),
1708 ast::SelfKind::Explicit(ref ty, _) => {
1709 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1711 let mutability = explicit_self_mutability(&args[0]);
1712 let type_str = ty.rewrite(
1714 Shape::legacy(context.config.max_width(), Indent::empty()),
1719 format_mutability(mutability),
1723 ast::SelfKind::Value(_) => {
1724 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1726 let mutability = explicit_self_mutability(&args[0]);
1728 Some(format!("{}self", format_mutability(mutability)))
1733 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1734 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1735 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1736 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1743 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1744 if is_named_arg(arg) {
1751 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1753 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1754 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1755 _ => arg.ty.span.hi(),
1759 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1760 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1761 ident.node != symbol::keywords::Invalid.ident()
1767 // Return type is (result, force_new_line_for_brace)
1769 context: &RewriteContext,
1774 newline_brace: bool,
1776 ) -> Option<(String, bool)> {
1777 let mut force_new_line_for_brace = false;
1779 let where_clause = &fn_sig.generics.where_clause;
1781 let mut result = String::with_capacity(1024);
1782 result.push_str(&fn_sig.to_str(context));
1785 result.push_str("fn ");
1786 result.push_str(&ident.to_string());
1789 let overhead = if has_body && !newline_brace {
1796 let used_width = last_line_used_width(&result, indent.width());
1797 let one_line_budget = context.budget(used_width + overhead);
1799 width: one_line_budget,
1803 let fd = fn_sig.decl;
1804 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1805 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1806 result.push_str(&generics_str);
1808 let snuggle_angle_bracket = generics_str
1811 .map_or(false, |l| l.trim_left().len() == 1);
1813 // Note that the width and indent don't really matter, we'll re-layout the
1814 // return type later anyway.
1815 let ret_str = fd.output
1816 .rewrite(context, Shape::indented(indent, context.config))?;
1818 let multi_line_ret_str = ret_str.contains('\n');
1819 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1822 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1833 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1839 // Check if vertical layout was forced.
1840 if one_line_budget == 0 {
1841 if snuggle_angle_bracket {
1844 result.push_str("(");
1845 if context.config.indent_style() == IndentStyle::Visual {
1847 result.push_str(&arg_indent.to_string(context.config));
1853 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1854 && result.ends_with('(')
1859 // Skip `pub(crate)`.
1860 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1861 // A conservative estimation, to goal is to be over all parens in generics
1862 let args_start = fn_sig
1866 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1867 let args_end = if fd.inputs.is_empty() {
1870 .span_after(mk_sp(args_start, span.hi()), ")")
1872 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1873 context.codemap.span_after(last_span, ")")
1875 let args_span = mk_sp(
1878 .span_after(mk_sp(args_start, span.hi()), "("),
1881 let arg_str = rewrite_args(
1884 fd.get_self().as_ref(),
1891 generics_str.contains('\n'),
1894 let put_args_in_block = match context.config.indent_style() {
1895 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1897 } && !fd.inputs.is_empty();
1899 let mut args_last_line_contains_comment = false;
1900 if put_args_in_block {
1901 arg_indent = indent.block_indent(context.config);
1903 result.push_str(&arg_indent.to_string(context.config));
1904 result.push_str(&arg_str);
1906 result.push_str(&indent.to_string(context.config));
1909 result.push_str(&arg_str);
1910 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1911 // Put the closing brace on the next line if it overflows the max width.
1913 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1916 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1919 // If the last line of args contains comment, we cannot put the closing paren
1920 // on the same line.
1924 .map_or(false, |last_line| last_line.contains("//"))
1926 args_last_line_contains_comment = true;
1928 result.push_str(&arg_indent.to_string(context.config));
1934 if let ast::FunctionRetTy::Ty(..) = fd.output {
1935 let ret_should_indent = match context.config.indent_style() {
1936 // If our args are block layout then we surely must have space.
1937 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1938 _ if args_last_line_contains_comment => false,
1939 _ if result.contains('\n') || multi_line_ret_str => true,
1941 // If the return type would push over the max width, then put the return type on
1942 // a new line. With the +1 for the signature length an additional space between
1943 // the closing parenthesis of the argument and the arrow '->' is considered.
1944 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1946 // If there is no where clause, take into account the space after the return type
1948 if where_clause.predicates.is_empty() {
1952 sig_length > context.config.max_width()
1955 let ret_indent = if ret_should_indent {
1956 let indent = if arg_str.is_empty() {
1957 // Aligning with non-existent args looks silly.
1958 force_new_line_for_brace = true;
1961 // FIXME: we might want to check that using the arg indent
1962 // doesn't blow our budget, and if it does, then fallback to
1963 // the where clause indent.
1968 result.push_str(&indent.to_string(context.config));
1972 Indent::new(indent.block_indent, last_line_width(&result))
1975 if multi_line_ret_str || ret_should_indent {
1976 // Now that we know the proper indent and width, we need to
1977 // re-layout the return type.
1978 let ret_str = fd.output
1979 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1980 result.push_str(&ret_str);
1982 result.push_str(&ret_str);
1985 // Comment between return type and the end of the decl.
1986 let snippet_lo = fd.output.span().hi();
1987 if where_clause.predicates.is_empty() {
1988 let snippet_hi = span.hi();
1989 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1990 // Try to preserve the layout of the original snippet.
1991 let original_starts_with_newline = snippet
1993 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1994 let original_ends_with_newline = snippet
1995 .rfind(|c| c != ' ')
1996 .map_or(false, |i| snippet[i..].ends_with('\n'));
1997 let snippet = snippet.trim();
1998 if !snippet.is_empty() {
1999 result.push(if original_starts_with_newline {
2004 result.push_str(snippet);
2005 if original_ends_with_newline {
2006 force_new_line_for_brace = true;
2012 let pos_before_where = match fd.output {
2013 ast::FunctionRetTy::Default(..) => args_span.hi(),
2014 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2017 let is_args_multi_lined = arg_str.contains('\n');
2019 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2020 let where_clause_str = rewrite_where_clause(
2023 context.config.brace_style(),
2024 Shape::indented(indent, context.config),
2030 is_args_multi_lined,
2032 // If there are neither where clause nor return type, we may be missing comments between
2034 if where_clause_str.is_empty() {
2035 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2036 match recover_missing_comment_in_span(
2037 mk_sp(args_span.hi(), ret_span.hi()),
2040 last_line_width(&result),
2042 Some(ref missing_comment) if !missing_comment.is_empty() => {
2043 result.push_str(missing_comment);
2044 force_new_line_for_brace = true;
2051 result.push_str(&where_clause_str);
2053 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2054 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2055 Some((result, force_new_line_for_brace))
2058 #[derive(Copy, Clone)]
2059 struct WhereClauseOption {
2060 suppress_comma: bool, // Force no trailing comma
2061 snuggle: bool, // Do not insert newline before `where`
2062 compress_where: bool, // Try single line where clause instead of vertical layout
2065 impl WhereClauseOption {
2066 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2068 suppress_comma: suppress_comma,
2070 compress_where: false,
2074 pub fn snuggled(current: &str) -> WhereClauseOption {
2076 suppress_comma: false,
2077 snuggle: trimmed_last_line_width(current) == 1,
2078 compress_where: false,
2084 context: &RewriteContext,
2086 explicit_self: Option<&ast::ExplicitSelf>,
2087 one_line_budget: usize,
2088 multi_line_budget: usize,
2093 generics_str_contains_newline: bool,
2094 ) -> Option<String> {
2095 let mut arg_item_strs = args.iter()
2096 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2097 .collect::<Option<Vec<_>>>()?;
2099 // Account for sugary self.
2100 // FIXME: the comment for the self argument is dropped. This is blocked
2101 // on rust issue #27522.
2102 let min_args = explicit_self
2103 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2104 .map_or(1, |self_str| {
2105 arg_item_strs[0] = self_str;
2109 // Comments between args.
2110 let mut arg_items = Vec::new();
2112 arg_items.push(ListItem::from_str(""));
2115 // FIXME(#21): if there are no args, there might still be a comment, but
2116 // without spans for the comment or parens, there is no chance of
2117 // getting it right. You also don't get to put a comment on self, unless
2119 if args.len() >= min_args || variadic {
2120 let comment_span_start = if min_args == 2 {
2121 let second_arg_start = if arg_has_pattern(&args[1]) {
2122 args[1].pat.span.lo()
2124 args[1].ty.span.lo()
2126 let reduced_span = mk_sp(span.lo(), second_arg_start);
2128 context.codemap.span_after_last(reduced_span, ",")
2133 enum ArgumentKind<'a> {
2134 Regular(&'a ast::Arg),
2138 let variadic_arg = if variadic {
2139 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2140 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2141 Some(ArgumentKind::Variadic(variadic_start))
2146 let more_items = itemize_list(
2148 args[min_args - 1..]
2150 .map(ArgumentKind::Regular)
2151 .chain(variadic_arg),
2155 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2156 ArgumentKind::Variadic(start) => start,
2159 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2160 ArgumentKind::Variadic(start) => start + BytePos(3),
2163 ArgumentKind::Regular(..) => None,
2164 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2171 arg_items.extend(more_items);
2174 let fits_in_one_line = !generics_str_contains_newline
2175 && (arg_items.is_empty()
2176 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2178 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2179 item.item = Some(arg);
2182 let last_line_ends_with_comment = arg_items
2185 .and_then(|item| item.post_comment.as_ref())
2186 .map_or(false, |s| s.trim().starts_with("//"));
2188 let (indent, trailing_comma) = match context.config.indent_style() {
2189 IndentStyle::Block if fits_in_one_line => {
2190 (indent.block_indent(context.config), SeparatorTactic::Never)
2192 IndentStyle::Block => (
2193 indent.block_indent(context.config),
2194 context.config.trailing_comma(),
2196 IndentStyle::Visual if last_line_ends_with_comment => {
2197 (arg_indent, context.config.trailing_comma())
2199 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2202 let tactic = definitive_tactic(
2204 context.config.fn_args_density().to_list_tactic(),
2208 let budget = match tactic {
2209 DefinitiveListTactic::Horizontal => one_line_budget,
2210 _ => multi_line_budget,
2213 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2215 let fmt = ListFormatting {
2218 trailing_separator: if variadic {
2219 SeparatorTactic::Never
2223 separator_place: SeparatorPlace::Back,
2224 shape: Shape::legacy(budget, indent),
2225 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2226 preserve_newline: true,
2227 config: context.config,
2230 write_list(&arg_items, &fmt)
2233 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2234 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2235 ident.node != symbol::keywords::Invalid.ident()
2241 fn compute_budgets_for_args(
2242 context: &RewriteContext,
2246 newline_brace: bool,
2248 force_vertical_layout: bool,
2249 ) -> Option<((usize, usize, Indent))> {
2251 "compute_budgets_for_args {} {:?}, {}, {}",
2257 // Try keeping everything on the same line.
2258 if !result.contains('\n') && !force_vertical_layout {
2259 // 2 = `()`, 3 = `() `, space is before ret_string.
2260 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2261 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2271 let one_line_budget = context.budget(used_space);
2273 if one_line_budget > 0 {
2275 let (indent, multi_line_budget) = match context.config.indent_style() {
2276 IndentStyle::Block => {
2277 let indent = indent.block_indent(context.config);
2278 (indent, context.budget(indent.width() + 1))
2280 IndentStyle::Visual => {
2281 let indent = indent + result.len() + 1;
2282 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2283 (indent, context.budget(multi_line_overhead))
2287 return Some((one_line_budget, multi_line_budget, indent));
2291 // Didn't work. we must force vertical layout and put args on a newline.
2292 let new_indent = indent.block_indent(context.config);
2293 let used_space = match context.config.indent_style() {
2295 IndentStyle::Block => new_indent.width() + 1,
2296 // Account for `)` and possibly ` {`.
2297 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2299 Some((0, context.budget(used_space), new_indent))
2302 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2303 let predicate_count = where_clause.predicates.len();
2305 if config.where_single_line() && predicate_count == 1 {
2308 let brace_style = config.brace_style();
2310 brace_style == BraceStyle::AlwaysNextLine
2311 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2314 fn rewrite_generics(
2315 context: &RewriteContext,
2316 generics: &ast::Generics,
2319 ) -> Option<String> {
2320 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2321 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2322 rewrite_generics_inner(context, generics, g_shape, one_line_width, span)
2323 .or_else(|| rewrite_generics_inner(context, generics, g_shape, 0, span))
2326 fn rewrite_generics_inner(
2327 context: &RewriteContext,
2328 generics: &ast::Generics,
2330 one_line_width: usize,
2332 ) -> Option<String> {
2333 // FIXME: convert bounds to where clauses where they get too big or if
2334 // there is a where clause at all.
2337 enum GenericsArg<'a> {
2338 Lifetime(&'a ast::LifetimeDef),
2339 TyParam(&'a ast::TyParam),
2341 impl<'a> Rewrite for GenericsArg<'a> {
2342 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2344 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2345 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2349 impl<'a> Spanned for GenericsArg<'a> {
2350 fn span(&self) -> Span {
2352 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2353 GenericsArg::TyParam(ty) => ty.span(),
2358 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2359 return Some(String::new());
2362 let generics_args = generics
2365 .map(|lt| GenericsArg::Lifetime(lt))
2366 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2367 let items = itemize_list(
2372 |arg| arg.span().lo(),
2373 |arg| arg.span().hi(),
2374 |arg| arg.rewrite(context, shape),
2375 context.codemap.span_after(span, "<"),
2379 format_generics_item_list(context, items, shape, one_line_width)
2382 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2383 match config.indent_style() {
2384 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2385 IndentStyle::Block => {
2389 .block_indent(config.tab_spaces())
2390 .with_max_width(config)
2396 pub fn format_generics_item_list<I>(
2397 context: &RewriteContext,
2400 one_line_budget: usize,
2403 I: Iterator<Item = ListItem>,
2405 let item_vec = items.collect::<Vec<_>>();
2407 let tactic = definitive_tactic(
2409 ListTactic::HorizontalVertical,
2413 let fmt = ListFormatting {
2416 trailing_separator: if context.config.indent_style() == IndentStyle::Visual {
2417 SeparatorTactic::Never
2419 context.config.trailing_comma()
2421 separator_place: SeparatorPlace::Back,
2423 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2424 preserve_newline: true,
2425 config: context.config,
2428 let list_str = write_list(&item_vec, &fmt)?;
2430 Some(wrap_generics_with_angle_brackets(
2437 pub fn wrap_generics_with_angle_brackets(
2438 context: &RewriteContext,
2440 list_offset: Indent,
2442 if context.config.indent_style() == IndentStyle::Block
2443 && (list_str.contains('\n') || list_str.ends_with(','))
2447 list_offset.to_string(context.config),
2450 .block_unindent(context.config)
2451 .to_string(context.config)
2453 } else if context.config.spaces_within_parens_and_brackets() {
2454 format!("< {} >", list_str)
2456 format!("<{}>", list_str)
2460 fn rewrite_trait_bounds(
2461 context: &RewriteContext,
2462 bounds: &[ast::TyParamBound],
2464 ) -> Option<String> {
2465 if bounds.is_empty() {
2466 return Some(String::new());
2468 let bound_str = bounds
2470 .map(|ty_bound| ty_bound.rewrite(context, shape))
2471 .collect::<Option<Vec<_>>>()?;
2472 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2475 fn rewrite_where_clause_rfc_style(
2476 context: &RewriteContext,
2477 where_clause: &ast::WhereClause,
2480 span_end: Option<BytePos>,
2481 span_end_before_where: BytePos,
2482 where_clause_option: WhereClauseOption,
2483 is_args_multi_line: bool,
2484 ) -> Option<String> {
2485 let block_shape = shape.block().with_max_width(context.config);
2487 let (span_before, span_after) =
2488 missing_span_before_after_where(span_end_before_where, where_clause);
2489 let (comment_before, comment_after) =
2490 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2492 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2495 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2498 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2500 let clause_shape = clause_shape.sub_width(1)?;
2501 // each clause on one line, trailing comma (except if suppress_comma)
2502 let span_start = where_clause.predicates[0].span().lo();
2503 // If we don't have the start of the next span, then use the end of the
2504 // predicates, but that means we miss comments.
2505 let len = where_clause.predicates.len();
2506 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2507 let span_end = span_end.unwrap_or(end_of_preds);
2508 let items = itemize_list(
2510 where_clause.predicates.iter(),
2513 |pred| pred.span().lo(),
2514 |pred| pred.span().hi(),
2515 |pred| pred.rewrite(context, clause_shape),
2520 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2521 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2522 SeparatorTactic::Never
2524 context.config.trailing_comma()
2527 // shape should be vertical only and only if we have `where_single_line` option enabled
2528 // and the number of items of the where clause is equal to 1
2529 let shape_tactic = if where_single_line {
2530 DefinitiveListTactic::Horizontal
2532 DefinitiveListTactic::Vertical
2535 let fmt = ListFormatting {
2536 tactic: shape_tactic,
2538 trailing_separator: comma_tactic,
2539 separator_place: SeparatorPlace::Back,
2540 shape: clause_shape,
2541 ends_with_newline: true,
2542 preserve_newline: true,
2543 config: context.config,
2545 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2547 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2550 format!("\n{}", shape.indent.to_string(context.config))
2552 let newline_before_where = comment_separator(&comment_before, shape);
2553 let newline_after_where = comment_separator(&comment_after, clause_shape);
2556 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2557 && comment_after.is_empty() && !preds_str.contains('\n')
2558 && 6 + preds_str.len() <= shape.width || where_single_line
2562 format!("\n{}", clause_shape.indent.to_string(context.config))
2565 "{}{}{}where{}{}{}{}",
2568 newline_before_where,
2569 newline_after_where,
2576 fn rewrite_where_clause(
2577 context: &RewriteContext,
2578 where_clause: &ast::WhereClause,
2579 brace_style: BraceStyle,
2583 span_end: Option<BytePos>,
2584 span_end_before_where: BytePos,
2585 where_clause_option: WhereClauseOption,
2586 is_args_multi_line: bool,
2587 ) -> Option<String> {
2588 if where_clause.predicates.is_empty() {
2589 return Some(String::new());
2592 if context.config.indent_style() == IndentStyle::Block {
2593 return rewrite_where_clause_rfc_style(
2599 span_end_before_where,
2600 where_clause_option,
2605 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2607 let offset = match context.config.indent_style() {
2608 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2609 // 6 = "where ".len()
2610 IndentStyle::Visual => shape.indent + extra_indent + 6,
2612 // FIXME: if indent_style != Visual, then the budgets below might
2613 // be out by a char or two.
2615 let budget = context.config.max_width() - offset.width();
2616 let span_start = where_clause.predicates[0].span().lo();
2617 // If we don't have the start of the next span, then use the end of the
2618 // predicates, but that means we miss comments.
2619 let len = where_clause.predicates.len();
2620 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2621 let span_end = span_end.unwrap_or(end_of_preds);
2622 let items = itemize_list(
2624 where_clause.predicates.iter(),
2627 |pred| pred.span().lo(),
2628 |pred| pred.span().hi(),
2629 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2634 let item_vec = items.collect::<Vec<_>>();
2635 // FIXME: we don't need to collect here
2636 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2638 let mut comma_tactic = context.config.trailing_comma();
2639 // Kind of a hack because we don't usually have trailing commas in where clauses.
2640 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2641 comma_tactic = SeparatorTactic::Never;
2644 let fmt = ListFormatting {
2647 trailing_separator: comma_tactic,
2648 separator_place: SeparatorPlace::Back,
2649 shape: Shape::legacy(budget, offset),
2650 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2651 preserve_newline: true,
2652 config: context.config,
2654 let preds_str = write_list(&item_vec, &fmt)?;
2656 let end_length = if terminator == "{" {
2657 // If the brace is on the next line we don't need to count it otherwise it needs two
2660 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2661 BraceStyle::PreferSameLine => 2,
2663 } else if terminator == "=" {
2668 if density == Density::Tall || preds_str.contains('\n')
2669 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2673 (shape.indent + extra_indent).to_string(context.config),
2677 Some(format!(" where {}", preds_str))
2681 fn missing_span_before_after_where(
2682 before_item_span_end: BytePos,
2683 where_clause: &ast::WhereClause,
2685 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2687 let pos_after_where = where_clause.span.lo() + BytePos(5);
2688 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2689 (missing_span_before, missing_span_after)
2692 fn rewrite_comments_before_after_where(
2693 context: &RewriteContext,
2694 span_before_where: Span,
2695 span_after_where: Span,
2697 ) -> Option<(String, String)> {
2698 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2699 let after_comment = rewrite_missing_comment(
2701 shape.block_indent(context.config.tab_spaces()),
2704 Some((before_comment, after_comment))
2707 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2708 format!("{}{}{}", format_visibility(vis), item_name, ident)
2711 #[derive(PartialEq, Eq)]
2719 context: &RewriteContext,
2720 generics: &ast::Generics,
2721 brace_style: BraceStyle,
2722 brace_pos: BracePos,
2726 ) -> Option<String> {
2727 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2728 let mut result = rewrite_generics(context, generics, shape, span)?;
2730 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2731 let budget = context.budget(last_line_used_width(&result, offset.width()));
2732 let mut option = WhereClauseOption::snuggled(&result);
2733 if brace_pos == BracePos::None {
2734 option.suppress_comma = true;
2736 // If the generics are not parameterized then generics.span.hi() == 0,
2737 // so we use span.lo(), which is the position after `struct Foo`.
2738 let span_end_before_where = if generics.is_parameterized() {
2743 let where_clause_str = rewrite_where_clause(
2745 &generics.where_clause,
2747 Shape::legacy(budget, offset.block_only()),
2751 span_end_before_where,
2755 result.push_str(&where_clause_str);
2756 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2757 || (generics.where_clause.predicates.is_empty()
2758 && trimmed_last_line_width(&result) == 1)
2760 brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2761 || brace_style != BraceStyle::AlwaysNextLine
2763 if brace_pos == BracePos::None {
2764 return Some(result);
2766 let total_used_width = last_line_used_width(&result, used_width);
2767 let remaining_budget = context.budget(total_used_width);
2768 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2769 // and hence we take the closer into account as well for one line budget.
2770 // We assume that the closer has the same length as the opener.
2771 let overhead = if brace_pos == BracePos::ForceSameLine {
2778 let forbid_same_line_brace = overhead > remaining_budget;
2779 if !forbid_same_line_brace && same_line_brace {
2783 result.push_str(&offset.block_only().to_string(context.config));
2790 impl Rewrite for ast::ForeignItem {
2791 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2792 let attrs_str = self.attrs.rewrite(context, shape)?;
2793 // Drop semicolon or it will be interpreted as comment.
2794 // FIXME: this may be a faulty span from libsyntax.
2795 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2797 let item_str = match self.node {
2798 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2803 &FnSig::new(fn_decl, generics, self.vis.clone()),
2807 ).map(|(s, _)| format!("{};", s))
2809 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2810 // FIXME(#21): we're dropping potential comments in between the
2811 // function keywords here.
2812 let vis = format_visibility(&self.vis);
2813 let mut_str = if is_mutable { "mut " } else { "" };
2814 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2816 let shape = shape.sub_width(1)?;
2817 ty.rewrite(context, shape).map(|ty_str| {
2818 // 1 = space between prefix and type.
2819 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2822 let nested_indent = shape.indent.block_indent(context.config);
2823 format!("\n{}", nested_indent.to_string(context.config))
2825 format!("{}{}{};", prefix, sep, ty_str)
2828 ast::ForeignItemKind::Ty => {
2829 let vis = format_visibility(&self.vis);
2830 Some(format!("{}type {};", vis, self.ident))
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(