1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
16 use syntax::{abi, ast, ptr, symbol};
17 use syntax::ast::{CrateSugar, ImplItem};
18 use syntax::codemap::{BytePos, Span};
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
26 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27 rewrite_call_inner, ExprType};
28 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
29 ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
32 use types::join_bounds;
33 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
34 format_constness, format_defaultness, format_mutability, format_unsafety,
35 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
36 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
37 stmt_expr, trim_newlines, trimmed_last_line_width};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
41 fn type_annotation_separator(config: &Config) -> &str {
43 config.space_before_type_annotation(),
44 config.space_after_type_annotation_colon(),
48 // Statements of the form
49 // let pat: ty = init;
50 impl Rewrite for ast::Local {
51 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
53 "Local::rewrite {:?} {} {:?}",
59 skip_out_of_file_lines_range!(context, self.span);
61 if contains_skip(&self.attrs) {
65 let attrs_str = self.attrs.rewrite(context, shape)?;
66 let mut result = if attrs_str.is_empty() {
69 combine_strs_with_missing_comments(
74 self.attrs.last().map(|a| a.span.hi()).unwrap(),
83 let pat_shape = shape.offset_left(4)?;
85 let pat_shape = pat_shape.sub_width(1)?;
86 let pat_str = self.pat.rewrite(context, pat_shape)?;
87 result.push_str(&pat_str);
89 // String that is placed within the assignment pattern and expression.
91 let mut infix = String::with_capacity(32);
93 if let Some(ref ty) = self.ty {
94 let separator = type_annotation_separator(context.config);
95 let indent = shape.indent + last_line_width(&result) + separator.len();
97 let budget = shape.width.checked_sub(indent.width() + 1)?;
98 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
100 infix.push_str(separator);
101 infix.push_str(&rewrite);
104 if self.init.is_some() {
105 infix.push_str(" =");
111 result.push_str(&infix);
113 if let Some(ref ex) = self.init {
114 // 1 = trailing semicolon;
115 let nested_shape = shape.sub_width(1)?;
117 result = rewrite_assign_rhs(context, result, ex, nested_shape)?;
125 // TODO convert to using rewrite style rather than visitor
126 // TODO format modules in this style
129 keyword: &'static str,
130 abi: Cow<'static, str>,
131 vis: Option<&'a ast::Visibility>,
132 body: Vec<BodyElement<'a>>,
137 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
140 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
144 .map(|i| BodyElement::ForeignItem(i))
151 enum BodyElement<'a> {
152 // Stmt(&'a ast::Stmt),
153 // Field(&'a ast::Field),
154 // Variant(&'a ast::Variant),
155 // Item(&'a ast::Item),
156 ForeignItem(&'a ast::ForeignItem),
159 /// Represents a fn's signature.
160 pub struct FnSig<'a> {
161 decl: &'a ast::FnDecl,
162 generics: &'a ast::Generics,
164 constness: ast::Constness,
165 defaultness: ast::Defaultness,
166 unsafety: ast::Unsafety,
167 visibility: ast::Visibility,
172 decl: &'a ast::FnDecl,
173 generics: &'a ast::Generics,
174 vis: ast::Visibility,
180 constness: ast::Constness::NotConst,
181 defaultness: ast::Defaultness::Final,
182 unsafety: ast::Unsafety::Normal,
187 pub fn from_method_sig(
188 method_sig: &'a ast::MethodSig,
189 generics: &'a ast::Generics,
192 unsafety: method_sig.unsafety,
193 constness: method_sig.constness.node,
194 defaultness: ast::Defaultness::Final,
196 decl: &*method_sig.decl,
198 visibility: ast::Visibility::Inherited,
203 fn_kind: &'a visit::FnKind,
204 generics: &'a ast::Generics,
205 decl: &'a ast::FnDecl,
206 defualtness: ast::Defaultness,
209 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
213 constness: constness.node,
214 defaultness: defualtness,
216 visibility: visibility.clone(),
218 visit::FnKind::Method(_, method_sig, vis, _) => {
219 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
220 fn_sig.defaultness = defualtness;
221 if let Some(vis) = vis {
222 fn_sig.visibility = vis.clone();
230 fn to_str(&self, context: &RewriteContext) -> String {
231 let mut result = String::with_capacity(128);
232 // Vis defaultness constness unsafety abi.
233 result.push_str(&*format_visibility(&self.visibility));
234 result.push_str(format_defaultness(self.defaultness));
235 result.push_str(format_constness(self.constness));
236 result.push_str(format_unsafety(self.unsafety));
237 result.push_str(&format_abi(
239 context.config.force_explicit_abi(),
246 impl<'a> FmtVisitor<'a> {
247 fn format_item(&mut self, item: Item) {
248 self.buffer.push_str(&item.abi);
250 let snippet = self.snippet(item.span);
251 let brace_pos = snippet.find_uncommented("{").unwrap();
253 self.buffer.push_str("{");
254 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
255 // FIXME: this skips comments between the extern keyword and the opening
257 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
258 self.block_indent = self.block_indent.block_indent(self.config);
260 if item.body.is_empty() {
261 self.format_missing_no_indent(item.span.hi() - BytePos(1));
262 self.block_indent = self.block_indent.block_unindent(self.config);
265 .push_str(&self.block_indent.to_string(self.config));
267 for item in &item.body {
268 self.format_body_element(item);
271 self.block_indent = self.block_indent.block_unindent(self.config);
272 self.format_missing_with_indent(item.span.hi() - BytePos(1));
276 self.buffer.push_str("}");
277 self.last_pos = item.span.hi();
280 fn format_body_element(&mut self, element: &BodyElement) {
282 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
286 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
287 let item = Item::from_foreign_mod(fm, span, self.config);
288 self.format_item(item);
292 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
293 let rewrite = item.rewrite(&self.get_context(), self.shape());
294 self.push_rewrite(item.span(), rewrite);
295 self.last_pos = item.span.hi();
305 ) -> Option<String> {
306 let context = self.get_context();
309 !is_empty_block(block, self.codemap) || !context.config.fn_empty_single_line();
310 let mut newline_brace =
311 newline_for_brace(self.config, &fn_sig.generics.where_clause, has_body);
313 let (mut result, force_newline_brace) =
314 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
317 if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
318 || last_line_width(&result) + 2 > self.shape().width
320 newline_brace = true;
321 } else if !result.contains('\n') {
322 newline_brace = false;
325 // Prepare for the function body by possibly adding a newline and
327 // FIXME we'll miss anything between the end of the signature and the
328 // start of the body, but we need more spans from the compiler to solve
332 result.push_str(&indent.to_string(self.config));
337 self.single_line_fn(&result, block).or_else(|| Some(result))
340 pub fn rewrite_required_fn(
344 sig: &ast::MethodSig,
345 generics: &ast::Generics,
347 ) -> Option<String> {
348 // Drop semicolon or it will be interpreted as comment.
349 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
350 let context = self.get_context();
352 let (mut result, _) = rewrite_fn_base(
356 &FnSig::from_method_sig(sig, generics),
362 // Re-attach semicolon
368 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
369 if fn_str.contains('\n') {
373 let codemap = self.get_context().codemap;
375 if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
376 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
378 return Some(format!("{}{{}}", fn_str));
381 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
383 if let Some(stmt) = block.stmts.first() {
384 match stmt_expr(stmt) {
386 let suffix = if semicolon_for_expr(&self.get_context(), e) {
392 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
394 .or_else(|| Some(self.snippet(e.span)))
396 None => stmt.rewrite(&self.get_context(), self.shape()),
403 if let Some(res) = rewrite {
404 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
405 if !res.contains('\n') && width <= self.config.max_width() {
406 return Some(format!("{}{{ {} }}", fn_str, res));
414 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
415 let is_tuple = struct_parts.def.is_tuple();
416 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
417 .map(|s| if is_tuple { s + ";" } else { s });
418 self.push_rewrite(struct_parts.span, rewrite);
424 vis: &ast::Visibility,
425 enum_def: &ast::EnumDef,
426 generics: &ast::Generics,
429 let enum_header = format_header("enum ", ident, vis);
430 self.buffer.push_str(&enum_header);
432 let enum_snippet = self.snippet(span);
433 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
434 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
435 let generics_str = format_generics(
438 self.config.item_brace_style(),
439 enum_def.variants.is_empty(),
441 mk_sp(span.lo(), body_start),
442 last_line_width(&enum_header),
444 self.buffer.push_str(&generics_str);
446 self.last_pos = body_start;
448 self.block_indent = self.block_indent.block_indent(self.config);
449 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
451 Some(ref body_str) => self.buffer.push_str(body_str),
452 None => if contains_comment(&enum_snippet[brace_pos..]) {
453 self.format_missing_no_indent(span.hi() - BytePos(1))
456 self.block_indent = self.block_indent.block_unindent(self.config);
458 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
460 .push_str(&self.block_indent.to_string(self.config));
462 self.buffer.push_str("}");
463 self.last_pos = span.hi();
466 // Format the body of an enum definition
467 fn format_variant_list(
469 enum_def: &ast::EnumDef,
472 ) -> Option<String> {
473 if enum_def.variants.is_empty() {
476 let mut result = String::with_capacity(1024);
478 let indentation = self.block_indent.to_string(self.config);
479 result.push_str(&indentation);
481 let items = itemize_list(
483 enum_def.variants.iter(),
485 |f| if !f.node.attrs.is_empty() {
486 f.node.attrs[0].span.lo()
491 |f| self.format_variant(f),
497 let shape = self.shape().sub_width(2).unwrap();
498 let fmt = ListFormatting {
499 tactic: DefinitiveListTactic::Vertical,
501 trailing_separator: self.config.trailing_comma(),
502 separator_place: SeparatorPlace::Back,
504 ends_with_newline: true,
505 preserve_newline: true,
509 let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
510 result.push_str(&list);
515 // Variant of an enum.
516 fn format_variant(&self, field: &ast::Variant) -> Option<String> {
517 if contains_skip(&field.node.attrs) {
518 let lo = field.node.attrs[0].span.lo();
519 let span = mk_sp(lo, field.span.hi());
520 return Some(self.snippet(span));
523 let context = self.get_context();
524 let indent = self.block_indent;
525 let shape = self.shape();
526 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
531 .map_or(field.span.lo(), |attr| attr.span.hi());
532 let span = mk_sp(lo, field.span.lo());
534 let variant_body = match field.node.data {
535 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
536 // FIXME: Should limit the width, as we have a trailing comma
539 &StructParts::from_variant(field),
541 Some(self.config.struct_variant_width()),
544 ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
545 let lhs = format!("{} =", field.node.name);
547 rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
549 field.node.name.to_string()
553 let attrs_extendable = attrs_str.is_empty()
554 || (context.config.attributes_on_same_line_as_variant()
555 && is_attributes_extendable(&attrs_str));
556 combine_strs_with_missing_comments(
568 context: &RewriteContext,
571 where_span_end: Option<BytePos>,
572 ) -> Option<String> {
573 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
574 let mut result = String::with_capacity(128);
575 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
576 let indent_str = offset.to_string(context.config);
577 let sep = format!("\n{}", &indent_str);
578 result.push_str(&ref_and_type);
580 let where_budget = if result.contains('\n') {
581 context.config.max_width()
583 context.budget(last_line_width(&result))
585 let option = WhereClauseOption::snuggled(&ref_and_type);
586 let where_clause_str = rewrite_where_clause(
588 &generics.where_clause,
589 context.config.item_brace_style(),
590 Shape::legacy(where_budget, offset.block_only()),
591 context.config.where_density(),
599 // If there is no where clause, we may have missing comments between the trait name and
600 // the opening brace.
601 if generics.where_clause.predicates.is_empty() {
602 if let Some(hi) = where_span_end {
603 match recover_missing_comment_in_span(
604 mk_sp(self_ty.span.hi(), hi),
605 Shape::indented(offset, context.config),
607 last_line_width(&result),
609 Some(ref missing_comment) if !missing_comment.is_empty() => {
610 result.push_str(missing_comment);
617 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
618 result.push_str(&where_clause_str);
619 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
620 result.push_str(&format!("{}{{{}}}", &sep, &sep));
622 result.push_str(" {}");
627 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
629 let width = offset.block_indent + context.config.tab_spaces() - 1;
630 let where_indent = Indent::new(0, width);
631 result.push_str(&where_indent.to_string(context.config));
633 result.push_str(&where_clause_str);
635 match context.config.item_brace_style() {
636 _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
637 BraceStyle::AlwaysNextLine => result.push_str(&sep),
638 BraceStyle::PreferSameLine => result.push(' '),
639 BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
640 result.push_str(&sep);
648 let snippet = context.snippet(item.span);
649 let open_pos = snippet.find_uncommented("{")? + 1;
651 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
652 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
653 visitor.block_indent = offset.block_only().block_indent(context.config);
654 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
656 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
658 visitor.visit_impl_item(item);
661 visitor.format_missing(item.span.hi() - BytePos(1));
663 let inner_indent_str = visitor.block_indent.to_string(context.config);
664 let outer_indent_str = offset.block_only().to_string(context.config);
667 result.push_str(&inner_indent_str);
668 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
670 result.push_str(&outer_indent_str);
673 if result.ends_with('{') {
674 result.push_str(&sep);
684 fn is_impl_single_line(
685 context: &RewriteContext,
688 where_clause_str: &str,
691 let snippet = context.snippet(item.span);
692 let open_pos = snippet.find_uncommented("{")? + 1;
695 context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
696 && result.len() + where_clause_str.len() <= context.config.max_width()
697 && !contains_comment(&snippet[open_pos..]),
701 fn format_impl_ref_and_type(
702 context: &RewriteContext,
705 ) -> Option<String> {
706 if let ast::ItemKind::Impl(
716 let mut result = String::with_capacity(128);
718 result.push_str(&format_visibility(&item.vis));
719 result.push_str(format_defaultness(defaultness));
720 result.push_str(format_unsafety(unsafety));
721 result.push_str("impl");
723 let lo = context.codemap.span_after(item.span, "impl");
724 let hi = match *trait_ref {
725 Some(ref tr) => tr.path.span.lo(),
726 None => self_ty.span.lo(),
728 let shape = generics_shape_from_config(
730 Shape::indented(offset + last_line_width(&result), context.config),
733 let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
735 rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
737 let polarity_str = if polarity == ast::ImplPolarity::Negative {
743 if let Some(ref trait_ref) = *trait_ref {
744 let result_len = result.len();
745 if let Some(trait_ref_str) = rewrite_trait_ref(
754 result.push_str(&trait_ref_str);
757 rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
758 result.push_str(&rewrite_trait_ref(
769 result.push_str(&generics_str);
772 // Try to put the self type in a single line.
774 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
775 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
776 // If there is no where clause adapt budget for type formatting to take space and curly
777 // brace into account.
778 match context.config.item_brace_style() {
779 BraceStyle::AlwaysNextLine => 0,
785 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
786 // 1 = space before the type.
787 let budget = context.budget(used_space + 1);
788 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
789 if !self_ty_str.contains('\n') {
790 if trait_ref.is_some() {
791 result.push_str(" for ");
795 result.push_str(&self_ty_str);
800 // Couldn't fit the self type on a single line, put it on a new line.
802 // Add indentation of one additional tab.
803 let new_line_offset = offset.block_indent(context.config);
804 result.push_str(&new_line_offset.to_string(context.config));
805 if trait_ref.is_some() {
806 result.push_str("for ");
808 let budget = context.budget(last_line_width(&result));
809 let type_offset = match context.config.where_style() {
810 Style::Legacy => new_line_offset + trait_ref_overhead,
811 Style::Rfc => new_line_offset,
813 result.push_str(&*self_ty
814 .rewrite(context, Shape::legacy(budget, type_offset))?);
821 fn rewrite_trait_ref(
822 context: &RewriteContext,
823 trait_ref: &ast::TraitRef,
829 ) -> Option<String> {
830 // 1 = space between generics and trait_ref
831 let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
832 let shape = Shape::indented(offset + used_space, context.config);
833 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
834 if !(retry && trait_ref_str.contains('\n')) {
843 // We could not make enough space for trait_ref, so put it on new line.
845 let offset = offset.block_indent(context.config);
846 let shape = Shape::indented(offset, context.config);
847 let trait_ref_str = trait_ref.rewrite(context, shape)?;
851 &offset.to_string(context.config),
860 pub struct StructParts<'a> {
863 vis: &'a ast::Visibility,
864 def: &'a ast::VariantData,
865 generics: Option<&'a ast::Generics>,
869 impl<'a> StructParts<'a> {
870 fn format_header(&self) -> String {
871 format_header(self.prefix, self.ident, self.vis)
874 fn from_variant(variant: &'a ast::Variant) -> Self {
877 ident: variant.node.name,
878 vis: &ast::Visibility::Inherited,
879 def: &variant.node.data,
885 pub fn from_item(item: &'a ast::Item) -> Self {
886 let (prefix, def, generics) = match item.node {
887 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
888 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
896 generics: Some(generics),
903 context: &RewriteContext,
904 struct_parts: &StructParts,
906 one_line_width: Option<usize>,
907 ) -> Option<String> {
908 match *struct_parts.def {
909 ast::VariantData::Unit(..) => Some(format_unit_struct(struct_parts)),
910 ast::VariantData::Tuple(ref fields, _) => {
911 format_tuple_struct(context, struct_parts, fields, offset)
913 ast::VariantData::Struct(ref fields, _) => {
914 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
919 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
920 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
923 let mut result = String::with_capacity(128);
924 let header = format!(
926 format_visibility(&item.vis),
927 format_unsafety(unsafety),
931 result.push_str(&header);
933 let body_lo = context.codemap.span_after(item.span, "{");
935 let shape = Shape::indented(offset + last_line_width(&result), context.config);
937 rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
938 result.push_str(&generics_str);
940 let trait_bound_str = rewrite_trait_bounds(
943 Shape::indented(offset, context.config),
945 // If the trait, generics, and trait bound cannot fit on the same line,
946 // put the trait bounds on an indented new line
947 if offset.width() + last_line_width(&result) + trait_bound_str.len()
948 > context.config.comment_width()
951 let trait_indent = offset.block_only().block_indent(context.config);
952 result.push_str(&trait_indent.to_string(context.config));
954 result.push_str(&trait_bound_str);
956 let has_body = !trait_items.is_empty();
958 let where_density = if (context.config.where_density() == Density::Compressed
959 && (!result.contains('\n') || context.config.fn_args_indent() == IndentStyle::Block))
960 || (context.config.fn_args_indent() == IndentStyle::Block && result.is_empty())
961 || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
962 && !result.contains('\n'))
969 let where_budget = context.budget(last_line_width(&result));
970 let pos_before_where = if type_param_bounds.is_empty() {
971 generics.where_clause.span.lo()
973 type_param_bounds[type_param_bounds.len() - 1].span().hi()
975 let option = WhereClauseOption::snuggled(&generics_str);
976 let where_clause_str = rewrite_where_clause(
978 &generics.where_clause,
979 context.config.item_brace_style(),
980 Shape::legacy(where_budget, offset.block_only()),
988 // If the where clause cannot fit on the same line,
989 // put the where clause on a new line
990 if !where_clause_str.contains('\n')
991 && last_line_width(&result) + where_clause_str.len() + offset.width()
992 > context.config.comment_width()
995 let width = offset.block_indent + context.config.tab_spaces() - 1;
996 let where_indent = Indent::new(0, width);
997 result.push_str(&where_indent.to_string(context.config));
999 result.push_str(&where_clause_str);
1001 if generics.where_clause.predicates.is_empty() {
1002 let item_snippet = context.snippet(item.span);
1003 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
1005 let comment_hi = body_lo - BytePos(1);
1006 let comment_lo = item.span.lo() + BytePos(lo as u32);
1007 if comment_lo < comment_hi {
1008 match recover_missing_comment_in_span(
1009 mk_sp(comment_lo, comment_hi),
1010 Shape::indented(offset, context.config),
1012 last_line_width(&result),
1014 Some(ref missing_comment) if !missing_comment.is_empty() => {
1015 result.push_str(missing_comment);
1023 match context.config.item_brace_style() {
1024 _ if last_line_contains_single_line_comment(&result) => {
1026 result.push_str(&offset.to_string(context.config));
1028 BraceStyle::AlwaysNextLine => {
1030 result.push_str(&offset.to_string(context.config));
1032 BraceStyle::PreferSameLine => result.push(' '),
1033 BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1034 && (!trait_items.is_empty() || result.contains('\n'))
1037 result.push_str(&offset.to_string(context.config));
1044 let snippet = context.snippet(item.span);
1045 let open_pos = snippet.find_uncommented("{")? + 1;
1047 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1048 let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1049 visitor.block_indent = offset.block_only().block_indent(context.config);
1050 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1052 for item in trait_items {
1053 visitor.visit_trait_item(item);
1056 visitor.format_missing(item.span.hi() - BytePos(1));
1058 let inner_indent_str = visitor.block_indent.to_string(context.config);
1059 let outer_indent_str = offset.block_only().to_string(context.config);
1062 result.push_str(&inner_indent_str);
1063 result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1065 result.push_str(&outer_indent_str);
1066 } else if result.contains('\n') {
1077 fn format_unit_struct(p: &StructParts) -> String {
1078 format!("{};", format_header(p.prefix, p.ident, p.vis))
1081 pub fn format_struct_struct(
1082 context: &RewriteContext,
1083 struct_parts: &StructParts,
1084 fields: &[ast::StructField],
1086 one_line_width: Option<usize>,
1087 ) -> Option<String> {
1088 let mut result = String::with_capacity(1024);
1089 let span = struct_parts.span;
1091 let header_str = struct_parts.format_header();
1092 result.push_str(&header_str);
1094 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1095 let body_lo = context.codemap.span_after(span, "{");
1097 let generics_str = match struct_parts.generics {
1098 Some(g) => format_generics(
1101 context.config.item_brace_style(),
1104 mk_sp(header_hi, body_lo),
1105 last_line_width(&result),
1108 // 3 = ` {}`, 2 = ` {`.
1109 let overhead = if fields.is_empty() { 3 } else { 2 };
1110 if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1111 && !fields.is_empty())
1112 || context.config.max_width() < overhead + result.len()
1114 format!("\n{}{{", offset.block_only().to_string(context.config))
1121 let overhead = if fields.is_empty() { 1 } else { 0 };
1122 let total_width = result.len() + generics_str.len() + overhead;
1123 if !generics_str.is_empty() && !generics_str.contains('\n')
1124 && total_width > context.config.max_width()
1127 result.push_str(&offset.to_string(context.config));
1128 result.push_str(generics_str.trim_left());
1130 result.push_str(&generics_str);
1133 if fields.is_empty() {
1134 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1135 if snippet.trim().is_empty() {
1137 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1139 result.push_str(snippet.trim_right());
1141 result.push_str(&offset.to_string(context.config));
1143 result.push_str(&snippet);
1146 return Some(result);
1150 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1151 let one_line_budget =
1152 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1154 let items_str = rewrite_with_alignment(
1157 Shape::indented(offset, context.config),
1158 mk_sp(body_lo, span.hi()),
1162 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1163 Some(format!("{} {} }}", result, items_str))
1169 .block_indent(context.config)
1170 .to_string(context.config),
1172 offset.to_string(context.config)
1177 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1178 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1179 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1180 fn get_bytepos_after_visibility(
1181 context: &RewriteContext,
1182 vis: &ast::Visibility,
1187 ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1189 .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1190 ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1191 ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1192 _ => default_span.lo(),
1196 fn format_tuple_struct(
1197 context: &RewriteContext,
1198 struct_parts: &StructParts,
1199 fields: &[ast::StructField],
1201 ) -> Option<String> {
1202 let mut result = String::with_capacity(1024);
1203 let span = struct_parts.span;
1205 let header_str = struct_parts.format_header();
1206 result.push_str(&header_str);
1208 let body_lo = if fields.is_empty() {
1209 let lo = get_bytepos_after_visibility(context, vis, span, ")");
1210 context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1214 let body_hi = if fields.is_empty() {
1215 context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1217 // This is a dirty hack to work around a missing `)` from the span of the last field.
1218 let last_arg_span = fields[fields.len() - 1].span;
1219 if context.snippet(last_arg_span).ends_with(')') {
1224 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1228 let where_clause_str = match struct_parts.generics {
1230 let budget = context.budget(last_line_width(&header_str));
1231 let shape = Shape::legacy(budget, offset);
1232 let g_span = mk_sp(span.lo(), body_lo);
1233 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1234 result.push_str(&generics_str);
1236 let where_budget = context.budget(last_line_width(&result));
1237 let option = WhereClauseOption::new(true, false);
1238 rewrite_where_clause(
1240 &generics.where_clause,
1241 context.config.item_brace_style(),
1242 Shape::legacy(where_budget, offset.block_only()),
1243 Density::Compressed,
1251 None => "".to_owned(),
1254 if fields.is_empty() {
1256 let used_width = last_line_used_width(&result, offset.width()) + 3;
1257 if used_width > context.config.max_width() {
1259 result.push_str(&offset
1260 .block_indent(context.config)
1261 .to_string(context.config))
1264 let snippet = context.snippet(mk_sp(
1266 context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1268 if snippet.is_empty() {
1270 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1271 result.push_str(snippet.trim_right());
1273 result.push_str(&offset.to_string(context.config));
1275 result.push_str(&snippet);
1280 let body = rewrite_call_inner(
1283 &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1285 Shape::indented(offset, context.config).sub_width(1)?,
1286 context.config.fn_call_width(),
1289 result.push_str(&body);
1292 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1293 && (result.contains('\n')
1294 || offset.block_indent + result.len() + where_clause_str.len() + 1
1295 > context.config.max_width())
1297 // We need to put the where clause on a new line, but we didn't
1298 // know that earlier, so the where clause will not be indented properly.
1300 result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1301 .to_string(context.config));
1303 result.push_str(&where_clause_str);
1308 pub fn rewrite_type_alias(
1309 context: &RewriteContext,
1313 generics: &ast::Generics,
1314 vis: &ast::Visibility,
1316 ) -> Option<String> {
1317 let mut result = String::with_capacity(128);
1319 result.push_str(&format_visibility(vis));
1320 result.push_str("type ");
1321 result.push_str(&ident.to_string());
1324 let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1325 let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1326 let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1327 result.push_str(&generics_str);
1329 let where_budget = context.budget(last_line_width(&result));
1330 let option = WhereClauseOption::snuggled(&result);
1331 let where_clause_str = rewrite_where_clause(
1333 &generics.where_clause,
1334 context.config.item_brace_style(),
1335 Shape::legacy(where_budget, indent),
1336 context.config.where_density(),
1343 result.push_str(&where_clause_str);
1344 if where_clause_str.is_empty() {
1345 result.push_str(" = ");
1347 result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1350 let line_width = last_line_width(&result);
1351 // This checked_sub may fail as the extra space after '=' is not taken into account
1352 // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1353 let budget = context.budget(indent.width() + line_width + ";".len());
1354 let type_indent = indent + line_width;
1355 // Try to fit the type on the same line
1356 let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1358 // The line was too short, try to put the type on the next line
1360 // Remove the space after '='
1362 let type_indent = indent.block_indent(context.config);
1364 result.push_str(&type_indent.to_string(context.config));
1365 let budget = context.budget(type_indent.width() + ";".len());
1366 ty.rewrite(context, Shape::legacy(budget, type_indent))
1368 result.push_str(&ty_str);
1369 result.push_str(";");
1373 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1375 if config.space_before_type_annotation() {
1380 if config.space_after_type_annotation_colon() {
1388 pub fn rewrite_struct_field_prefix(
1389 context: &RewriteContext,
1390 field: &ast::StructField,
1391 ) -> Option<String> {
1392 let vis = format_visibility(&field.vis);
1393 let type_annotation_spacing = type_annotation_spacing(context.config);
1394 Some(match field.ident {
1395 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1396 None => format!("{}", vis),
1400 impl Rewrite for ast::StructField {
1401 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1402 rewrite_struct_field(context, self, shape, 0)
1406 pub fn rewrite_struct_field(
1407 context: &RewriteContext,
1408 field: &ast::StructField,
1410 lhs_max_width: usize,
1411 ) -> Option<String> {
1412 if contains_skip(&field.attrs) {
1413 return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1416 let type_annotation_spacing = type_annotation_spacing(context.config);
1417 let prefix = rewrite_struct_field_prefix(context, field)?;
1419 let attrs_str = field.attrs.rewrite(context, shape)?;
1420 let attrs_extendable = attrs_str.is_empty()
1421 || (context.config.attributes_on_same_line_as_field()
1422 && is_attributes_extendable(&attrs_str));
1423 let missing_span = if field.attrs.is_empty() {
1424 mk_sp(field.span.lo(), field.span.lo())
1426 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1428 let mut spacing = String::from(if field.ident.is_some() {
1429 type_annotation_spacing.1
1433 // Try to put everything on a single line.
1434 let attr_prefix = combine_strs_with_missing_comments(
1442 let overhead = last_line_width(&attr_prefix);
1443 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1444 for _ in 0..lhs_offset {
1447 // In this extreme case we will be missing a space betweeen an attribute and a field.
1448 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1451 let ty_shape = shape.offset_left(overhead + spacing.len())?;
1452 if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1453 if !ty.contains('\n') {
1454 return Some(attr_prefix + &spacing + ty);
1458 // We must use multiline.
1459 let new_shape = shape.with_max_width(context.config);
1460 let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1462 let field_str = if prefix.is_empty() {
1464 } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1465 prefix + " " + &ty_rewritten
1467 let type_offset = shape.indent.block_indent(context.config);
1468 let nested_shape = Shape::indented(type_offset, context.config);
1469 let nested_ty = field.ty.rewrite(context, nested_shape)?;
1470 prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1472 combine_strs_with_missing_comments(
1482 pub struct StaticParts<'a> {
1483 vis: &'a ast::Visibility,
1486 mutability: ast::Mutability,
1487 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1490 impl<'a> StaticParts<'a> {
1492 vis: &'a ast::Visibility,
1495 mutability: ast::Mutability,
1496 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1497 ) -> StaticParts<'a> {
1508 pub fn rewrite_static(
1510 static_parts: &StaticParts,
1513 context: &RewriteContext,
1514 ) -> Option<String> {
1522 let colon = colon_spaces(
1523 context.config.space_before_type_annotation(),
1524 context.config.space_after_type_annotation_colon(),
1526 let prefix = format!(
1528 format_visibility(vis),
1530 format_mutability(mutability),
1535 let ty_str = ty.rewrite(
1537 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 = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1568 let bounds: &[_] = ty_param_bounds;
1569 let bound_str = bounds
1571 .map(|ty_bound| ty_bound.rewrite(context, shape))
1572 .collect::<Option<Vec<_>>>()?;
1573 if !bounds.is_empty() {
1574 format!(": {}", join_bounds(context, shape, &bound_str))
1582 if let Some(ty) = ty_opt {
1583 let ty_str = ty.rewrite(
1586 context.budget(indent.block_indent + prefix.len() + 2),
1587 indent.block_only(),
1590 Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1592 Some(format!("{}{};", prefix, type_bounds_str))
1596 pub fn rewrite_associated_impl_type(
1598 defaultness: ast::Defaultness,
1599 ty_opt: Option<&ptr::P<ast::Ty>>,
1600 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1601 context: &RewriteContext,
1603 ) -> Option<String> {
1604 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1607 ast::Defaultness::Default => Some(format!("default {}", result)),
1612 impl Rewrite for ast::FunctionRetTy {
1613 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1615 ast::FunctionRetTy::Default(_) => Some(String::new()),
1616 ast::FunctionRetTy::Ty(ref ty) => {
1617 let inner_width = shape.width.checked_sub(3)?;
1618 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1619 .map(|r| format!("-> {}", r))
1625 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1627 ast::TyKind::Infer => {
1628 let original = context.snippet(ty.span);
1635 impl Rewrite for ast::Arg {
1636 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1637 if is_named_arg(self) {
1638 let mut result = self.pat
1639 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1641 if !is_empty_infer(context, &*self.ty) {
1642 if context.config.space_before_type_annotation() {
1643 result.push_str(" ");
1645 result.push_str(":");
1646 if context.config.space_after_type_annotation_colon() {
1647 result.push_str(" ");
1649 let overhead = last_line_width(&result);
1650 let max_width = shape.width.checked_sub(overhead)?;
1651 let ty_str = self.ty
1652 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1653 result.push_str(&ty_str);
1658 self.ty.rewrite(context, shape)
1663 fn rewrite_explicit_self(
1664 explicit_self: &ast::ExplicitSelf,
1666 context: &RewriteContext,
1667 ) -> Option<String> {
1668 match explicit_self.node {
1669 ast::SelfKind::Region(lt, m) => {
1670 let mut_str = format_mutability(m);
1673 let lifetime_str = l.rewrite(
1675 Shape::legacy(context.config.max_width(), Indent::empty()),
1677 Some(format!("&{} {}self", lifetime_str, mut_str))
1679 None => Some(format!("&{}self", mut_str)),
1682 ast::SelfKind::Explicit(ref ty, _) => {
1683 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1685 let mutability = explicit_self_mutability(&args[0]);
1686 let type_str = ty.rewrite(
1688 Shape::legacy(context.config.max_width(), Indent::empty()),
1693 format_mutability(mutability),
1697 ast::SelfKind::Value(_) => {
1698 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1700 let mutability = explicit_self_mutability(&args[0]);
1702 Some(format!("{}self", format_mutability(mutability)))
1707 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1708 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1709 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1710 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1717 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1718 if is_named_arg(arg) {
1725 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1727 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1728 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1729 _ => arg.ty.span.hi(),
1733 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1734 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1735 ident.node != symbol::keywords::Invalid.ident()
1741 // Return type is (result, force_new_line_for_brace)
1743 context: &RewriteContext,
1748 newline_brace: bool,
1750 ) -> Option<(String, bool)> {
1751 let mut force_new_line_for_brace = false;
1753 let where_clause = &fn_sig.generics.where_clause;
1755 let mut result = String::with_capacity(1024);
1756 result.push_str(&fn_sig.to_str(context));
1759 result.push_str("fn ");
1760 result.push_str(&ident.to_string());
1763 let overhead = if has_body && !newline_brace {
1770 let used_width = last_line_used_width(&result, indent.width());
1771 let one_line_budget = context.budget(used_width + overhead);
1773 width: one_line_budget,
1777 let fd = fn_sig.decl;
1778 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1779 let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1780 result.push_str(&generics_str);
1782 let snuggle_angle_bracket = generics_str
1785 .map_or(false, |l| l.trim_left().len() == 1);
1787 // Note that the width and indent don't really matter, we'll re-layout the
1788 // return type later anyway.
1789 let ret_str = fd.output
1790 .rewrite(context, Shape::indented(indent, context.config))?;
1792 let multi_line_ret_str = ret_str.contains('\n');
1793 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1796 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1807 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1813 // Check if vertical layout was forced.
1814 if one_line_budget == 0 {
1815 if snuggle_angle_bracket {
1817 } else if context.config.fn_args_paren_newline() {
1819 result.push_str(&arg_indent.to_string(context.config));
1820 if context.config.fn_args_indent() == IndentStyle::Visual {
1821 arg_indent = arg_indent + 1; // extra space for `(`
1825 result.push_str("(");
1826 if context.config.fn_args_indent() == IndentStyle::Visual {
1828 result.push_str(&arg_indent.to_string(context.config));
1834 if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1838 // Skip `pub(crate)`.
1839 let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1840 // A conservative estimation, to goal is to be over all parens in generics
1841 let args_start = fn_sig
1845 .map_or(lo_after_visibility, |tp| end_typaram(tp));
1846 let args_end = if fd.inputs.is_empty() {
1849 .span_after(mk_sp(args_start, span.hi()), ")")
1851 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1852 context.codemap.span_after(last_span, ")")
1854 let args_span = mk_sp(
1857 .span_after(mk_sp(args_start, span.hi()), "("),
1860 let arg_str = rewrite_args(
1863 fd.get_self().as_ref(),
1870 generics_str.contains('\n'),
1873 let put_args_in_block = match context.config.fn_args_indent() {
1874 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1876 } && !fd.inputs.is_empty();
1878 let mut args_last_line_contains_comment = false;
1879 if put_args_in_block {
1880 arg_indent = indent.block_indent(context.config);
1882 result.push_str(&arg_indent.to_string(context.config));
1883 result.push_str(&arg_str);
1885 result.push_str(&indent.to_string(context.config));
1888 result.push_str(&arg_str);
1889 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1890 // Put the closing brace on the next line if it overflows the max width.
1892 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1895 if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1898 // If the last line of args contains comment, we cannot put the closing paren
1899 // on the same line.
1903 .map_or(false, |last_line| last_line.contains("//"))
1905 args_last_line_contains_comment = true;
1907 result.push_str(&arg_indent.to_string(context.config));
1913 if let ast::FunctionRetTy::Ty(..) = fd.output {
1914 let ret_should_indent = match context.config.fn_args_indent() {
1915 // If our args are block layout then we surely must have space.
1916 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1917 _ if args_last_line_contains_comment => false,
1918 _ if result.contains('\n') || multi_line_ret_str => true,
1920 // If the return type would push over the max width, then put the return type on
1921 // a new line. With the +1 for the signature length an additional space between
1922 // the closing parenthesis of the argument and the arrow '->' is considered.
1923 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1925 // If there is no where clause, take into account the space after the return type
1927 if where_clause.predicates.is_empty() {
1931 sig_length > context.config.max_width()
1934 let ret_indent = if ret_should_indent {
1935 let indent = match context.config.fn_return_indent() {
1936 ReturnIndent::WithWhereClause => indent + 4,
1937 // Aligning with non-existent args looks silly.
1938 _ if arg_str.is_empty() => {
1939 force_new_line_for_brace = true;
1942 // FIXME: we might want to check that using the arg indent
1943 // doesn't blow our budget, and if it does, then fallback to
1944 // the where clause indent.
1949 result.push_str(&indent.to_string(context.config));
1953 Indent::new(indent.block_indent, last_line_width(&result))
1956 if multi_line_ret_str || ret_should_indent {
1957 // Now that we know the proper indent and width, we need to
1958 // re-layout the return type.
1959 let ret_str = fd.output
1960 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1961 result.push_str(&ret_str);
1963 result.push_str(&ret_str);
1966 // Comment between return type and the end of the decl.
1967 let snippet_lo = fd.output.span().hi();
1968 if where_clause.predicates.is_empty() {
1969 let snippet_hi = span.hi();
1970 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1971 // Try to preserve the layout of the original snippet.
1972 let original_starts_with_newline = snippet
1974 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1975 let original_ends_with_newline = snippet
1976 .rfind(|c| c != ' ')
1977 .map_or(false, |i| snippet[i..].ends_with('\n'));
1978 let snippet = snippet.trim();
1979 if !snippet.is_empty() {
1980 result.push(if original_starts_with_newline {
1985 result.push_str(snippet);
1986 if original_ends_with_newline {
1987 force_new_line_for_brace = true;
1993 let should_compress_where = match context.config.where_density() {
1994 Density::Compressed => !result.contains('\n'),
1995 Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1999 let pos_before_where = match fd.output {
2000 ast::FunctionRetTy::Default(..) => args_span.hi(),
2001 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2004 let is_args_multi_lined = arg_str.contains('\n');
2006 if where_clause.predicates.len() == 1 && should_compress_where {
2007 let budget = context.budget(last_line_used_width(&result, indent.width()));
2008 if let Some(where_clause_str) = rewrite_where_clause(
2011 context.config.fn_brace_style(),
2012 Shape::legacy(budget, indent),
2013 Density::Compressed,
2017 WhereClauseOption::compressed(),
2018 is_args_multi_lined,
2020 result.push_str(&where_clause_str);
2021 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2022 return Some((result, force_new_line_for_brace));
2026 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2027 let where_clause_str = rewrite_where_clause(
2030 context.config.fn_brace_style(),
2031 Shape::indented(indent, context.config),
2037 is_args_multi_lined,
2039 // If there are neither where clause nor return type, we may be missing comments between
2041 if where_clause_str.is_empty() {
2042 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2043 match recover_missing_comment_in_span(
2044 mk_sp(args_span.hi(), ret_span.hi()),
2047 last_line_width(&result),
2049 Some(ref missing_comment) if !missing_comment.is_empty() => {
2050 result.push_str(missing_comment);
2051 force_new_line_for_brace = true;
2058 result.push_str(&where_clause_str);
2060 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2061 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2062 Some((result, force_new_line_for_brace))
2065 #[derive(Copy, Clone)]
2066 struct WhereClauseOption {
2067 suppress_comma: bool, // Force no trailing comma
2068 snuggle: bool, // Do not insert newline before `where`
2069 compress_where: bool, // Try single line where clause instead of vertical layout
2072 impl WhereClauseOption {
2073 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2075 suppress_comma: suppress_comma,
2077 compress_where: false,
2081 pub fn compressed() -> WhereClauseOption {
2083 suppress_comma: true,
2085 compress_where: true,
2089 pub fn snuggled(current: &str) -> WhereClauseOption {
2091 suppress_comma: false,
2092 snuggle: trimmed_last_line_width(current) == 1,
2093 compress_where: false,
2099 context: &RewriteContext,
2101 explicit_self: Option<&ast::ExplicitSelf>,
2102 one_line_budget: usize,
2103 multi_line_budget: usize,
2108 generics_str_contains_newline: bool,
2109 ) -> Option<String> {
2110 let mut arg_item_strs = args.iter()
2111 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2112 .collect::<Option<Vec<_>>>()?;
2114 // Account for sugary self.
2115 // FIXME: the comment for the self argument is dropped. This is blocked
2116 // on rust issue #27522.
2117 let min_args = explicit_self
2118 .and_then(|explicit_self| {
2119 rewrite_explicit_self(explicit_self, args, context)
2121 .map_or(1, |self_str| {
2122 arg_item_strs[0] = self_str;
2126 // Comments between args.
2127 let mut arg_items = Vec::new();
2129 arg_items.push(ListItem::from_str(""));
2132 // FIXME(#21): if there are no args, there might still be a comment, but
2133 // without spans for the comment or parens, there is no chance of
2134 // getting it right. You also don't get to put a comment on self, unless
2136 if args.len() >= min_args || variadic {
2137 let comment_span_start = if min_args == 2 {
2138 let second_arg_start = if arg_has_pattern(&args[1]) {
2139 args[1].pat.span.lo()
2141 args[1].ty.span.lo()
2143 let reduced_span = mk_sp(span.lo(), second_arg_start);
2145 context.codemap.span_after_last(reduced_span, ",")
2150 enum ArgumentKind<'a> {
2151 Regular(&'a ast::Arg),
2155 let variadic_arg = if variadic {
2156 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2157 let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2158 Some(ArgumentKind::Variadic(variadic_start))
2163 let more_items = itemize_list(
2165 args[min_args - 1..]
2167 .map(ArgumentKind::Regular)
2168 .chain(variadic_arg),
2171 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2172 ArgumentKind::Variadic(start) => start,
2175 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2176 ArgumentKind::Variadic(start) => start + BytePos(3),
2179 ArgumentKind::Regular(..) => None,
2180 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2187 arg_items.extend(more_items);
2190 let fits_in_one_line = !generics_str_contains_newline
2191 && (arg_items.is_empty()
2192 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2194 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2195 item.item = Some(arg);
2198 let last_line_ends_with_comment = arg_items
2201 .and_then(|item| item.post_comment.as_ref())
2202 .map_or(false, |s| s.trim().starts_with("//"));
2204 let (indent, trailing_comma) = match context.config.fn_args_indent() {
2205 IndentStyle::Block if fits_in_one_line => {
2206 (indent.block_indent(context.config), SeparatorTactic::Never)
2208 IndentStyle::Block => (
2209 indent.block_indent(context.config),
2210 context.config.trailing_comma(),
2212 IndentStyle::Visual if last_line_ends_with_comment => {
2213 (arg_indent, context.config.trailing_comma())
2215 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2218 let tactic = definitive_tactic(
2220 context.config.fn_args_density().to_list_tactic(),
2224 let budget = match tactic {
2225 DefinitiveListTactic::Horizontal => one_line_budget,
2226 _ => multi_line_budget,
2229 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2231 let fmt = ListFormatting {
2234 trailing_separator: if variadic {
2235 SeparatorTactic::Never
2239 separator_place: SeparatorPlace::Back,
2240 shape: Shape::legacy(budget, indent),
2241 ends_with_newline: tactic.ends_with_newline(context.config.fn_args_indent()),
2242 preserve_newline: true,
2243 config: context.config,
2246 write_list(&arg_items, &fmt)
2249 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2250 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2251 ident.node != symbol::keywords::Invalid.ident()
2257 fn compute_budgets_for_args(
2258 context: &RewriteContext,
2262 newline_brace: bool,
2264 force_vertical_layout: bool,
2265 ) -> Option<((usize, usize, Indent))> {
2267 "compute_budgets_for_args {} {:?}, {}, {}",
2273 // Try keeping everything on the same line.
2274 if !result.contains('\n') && !force_vertical_layout {
2275 // 2 = `()`, 3 = `() `, space is before ret_string.
2276 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2277 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2287 let one_line_budget = context.budget(used_space);
2289 if one_line_budget > 0 {
2291 let (indent, multi_line_budget) = match context.config.fn_args_indent() {
2292 IndentStyle::Block => {
2293 let indent = indent.block_indent(context.config);
2294 (indent, context.budget(indent.width() + 1))
2296 IndentStyle::Visual => {
2297 let indent = indent + result.len() + 1;
2298 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2299 (indent, context.budget(multi_line_overhead))
2303 return Some((one_line_budget, multi_line_budget, indent));
2307 // Didn't work. we must force vertical layout and put args on a newline.
2308 let new_indent = indent.block_indent(context.config);
2309 let used_space = match context.config.fn_args_indent() {
2311 IndentStyle::Block => new_indent.width() + 1,
2312 // Account for `)` and possibly ` {`.
2313 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2315 Some((0, context.budget(used_space), new_indent))
2318 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2319 let predicate_count = where_clause.predicates.len();
2321 if config.where_single_line() && predicate_count == 1 {
2324 match (config.fn_brace_style(), config.where_density()) {
2325 (BraceStyle::AlwaysNextLine, _) => true,
2326 (_, Density::Compressed) if predicate_count == 1 => false,
2327 (_, Density::CompressedIfEmpty) if predicate_count == 1 && !has_body => false,
2328 (BraceStyle::SameLineWhere, _) if predicate_count > 0 => true,
2333 fn rewrite_generics(
2334 context: &RewriteContext,
2335 generics: &ast::Generics,
2338 ) -> Option<String> {
2339 let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2340 let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2341 rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2342 rewrite_generics_inner(context, generics, g_shape, 0, span)
2346 fn rewrite_generics_inner(
2347 context: &RewriteContext,
2348 generics: &ast::Generics,
2350 one_line_width: usize,
2352 ) -> Option<String> {
2353 // FIXME: convert bounds to where clauses where they get too big or if
2354 // there is a where clause at all.
2357 enum GenericsArg<'a> {
2358 Lifetime(&'a ast::LifetimeDef),
2359 TyParam(&'a ast::TyParam),
2361 impl<'a> Rewrite for GenericsArg<'a> {
2362 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2364 GenericsArg::Lifetime(lifetime) => lifetime.rewrite(context, shape),
2365 GenericsArg::TyParam(ty) => ty.rewrite(context, shape),
2369 impl<'a> Spanned for GenericsArg<'a> {
2370 fn span(&self) -> Span {
2372 GenericsArg::Lifetime(lifetime) => lifetime.span(),
2373 GenericsArg::TyParam(ty) => ty.span(),
2378 if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2379 return Some(String::new());
2382 let generics_args = generics
2385 .map(|lt| GenericsArg::Lifetime(lt))
2386 .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2387 let items = itemize_list(
2391 |arg| arg.span().lo(),
2392 |arg| arg.span().hi(),
2393 |arg| arg.rewrite(context, shape),
2394 context.codemap.span_after(span, "<"),
2398 format_generics_item_list(context, items, shape, one_line_width)
2401 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2402 match config.generics_indent() {
2403 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2404 IndentStyle::Block => {
2408 .block_indent(config.tab_spaces())
2409 .with_max_width(config)
2415 pub fn format_generics_item_list<I>(
2416 context: &RewriteContext,
2419 one_line_budget: usize,
2422 I: Iterator<Item = ListItem>,
2424 let item_vec = items.collect::<Vec<_>>();
2426 let tactic = definitive_tactic(
2428 ListTactic::HorizontalVertical,
2432 let fmt = ListFormatting {
2435 trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2436 SeparatorTactic::Never
2438 context.config.trailing_comma()
2440 separator_place: SeparatorPlace::Back,
2442 ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2443 preserve_newline: true,
2444 config: context.config,
2447 let list_str = write_list(&item_vec, &fmt)?;
2449 Some(wrap_generics_with_angle_brackets(
2456 pub fn wrap_generics_with_angle_brackets(
2457 context: &RewriteContext,
2459 list_offset: Indent,
2461 if context.config.generics_indent() == IndentStyle::Block
2462 && (list_str.contains('\n') || list_str.ends_with(','))
2466 list_offset.to_string(context.config),
2469 .block_unindent(context.config)
2470 .to_string(context.config)
2472 } else if context.config.spaces_within_angle_brackets() {
2473 format!("< {} >", list_str)
2475 format!("<{}>", list_str)
2479 fn rewrite_trait_bounds(
2480 context: &RewriteContext,
2481 type_param_bounds: &ast::TyParamBounds,
2483 ) -> Option<String> {
2484 let bounds: &[_] = type_param_bounds;
2486 if bounds.is_empty() {
2487 return Some(String::new());
2489 let bound_str = bounds
2491 .map(|ty_bound| ty_bound.rewrite(context, shape))
2492 .collect::<Option<Vec<_>>>()?;
2493 Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2496 fn rewrite_where_clause_rfc_style(
2497 context: &RewriteContext,
2498 where_clause: &ast::WhereClause,
2501 span_end: Option<BytePos>,
2502 span_end_before_where: BytePos,
2503 where_clause_option: WhereClauseOption,
2504 is_args_multi_line: bool,
2505 ) -> Option<String> {
2506 let block_shape = shape.block().with_max_width(context.config);
2508 let (span_before, span_after) =
2509 missing_span_before_after_where(span_end_before_where, where_clause);
2510 let (comment_before, comment_after) =
2511 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2513 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2516 "\n".to_owned() + &block_shape.indent.to_string(context.config)
2519 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2521 let clause_shape = clause_shape.sub_width(1)?;
2522 // each clause on one line, trailing comma (except if suppress_comma)
2523 let span_start = where_clause.predicates[0].span().lo();
2524 // If we don't have the start of the next span, then use the end of the
2525 // predicates, but that means we miss comments.
2526 let len = where_clause.predicates.len();
2527 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2528 let span_end = span_end.unwrap_or(end_of_preds);
2529 let items = itemize_list(
2531 where_clause.predicates.iter(),
2533 |pred| pred.span().lo(),
2534 |pred| pred.span().hi(),
2535 |pred| pred.rewrite(context, clause_shape),
2540 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2541 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2542 SeparatorTactic::Never
2544 context.config.trailing_comma()
2547 // shape should be vertical only and only if we have `where_single_line` option enabled
2548 // and the number of items of the where clause is equal to 1
2549 let shape_tactic = if where_single_line {
2550 DefinitiveListTactic::Horizontal
2552 DefinitiveListTactic::Vertical
2555 let fmt = ListFormatting {
2556 tactic: shape_tactic,
2558 trailing_separator: comma_tactic,
2559 separator_place: SeparatorPlace::Back,
2560 shape: clause_shape,
2561 ends_with_newline: true,
2562 preserve_newline: true,
2563 config: context.config,
2565 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2567 let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2570 format!("\n{}", shape.indent.to_string(context.config))
2572 let newline_before_where = comment_separator(&comment_before, shape);
2573 let newline_after_where = comment_separator(&comment_after, clause_shape);
2576 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2577 && comment_after.is_empty() && !preds_str.contains('\n')
2578 && 6 + preds_str.len() <= shape.width || where_single_line
2582 format!("\n{}", clause_shape.indent.to_string(context.config))
2585 "{}{}{}where{}{}{}{}",
2588 newline_before_where,
2589 newline_after_where,
2596 fn rewrite_where_clause(
2597 context: &RewriteContext,
2598 where_clause: &ast::WhereClause,
2599 brace_style: BraceStyle,
2603 span_end: Option<BytePos>,
2604 span_end_before_where: BytePos,
2605 where_clause_option: WhereClauseOption,
2606 is_args_multi_line: bool,
2607 ) -> Option<String> {
2608 if where_clause.predicates.is_empty() {
2609 return Some(String::new());
2612 if context.config.where_style() == Style::Rfc {
2613 return rewrite_where_clause_rfc_style(
2619 span_end_before_where,
2620 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 = 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 = rewrite_missing_comment(span_before_where, shape, context)?;
2724 let after_comment = 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,
2739 brace_style: BraceStyle,
2740 force_same_line_brace: bool,
2744 ) -> Option<String> {
2745 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2746 let mut result = rewrite_generics(context, generics, shape, span)?;
2748 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2749 let budget = context.budget(last_line_used_width(&result, offset.width()));
2750 let option = WhereClauseOption::snuggled(&result);
2751 // If the generics are not parameterized then generics.span.hi() == 0,
2752 // so we use span.lo(), which is the position after `struct Foo`.
2753 let span_end_before_where = if generics.is_parameterized() {
2758 let where_clause_str = rewrite_where_clause(
2760 &generics.where_clause,
2762 Shape::legacy(budget, offset.block_only()),
2766 span_end_before_where,
2770 result.push_str(&where_clause_str);
2771 force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2772 || (generics.where_clause.predicates.is_empty()
2773 && trimmed_last_line_width(&result) == 1)
2775 force_same_line_brace || trimmed_last_line_width(&result) == 1
2776 || brace_style != BraceStyle::AlwaysNextLine
2778 let total_used_width = last_line_used_width(&result, used_width);
2779 let remaining_budget = context.budget(total_used_width);
2780 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2781 // and hence we take the closer into account as well for one line budget.
2782 // We assume that the closer has the same length as the opener.
2783 let overhead = if force_same_line_brace {
2790 let forbid_same_line_brace = overhead > remaining_budget;
2791 if !forbid_same_line_brace && same_line_brace {
2795 result.push_str(&offset.block_only().to_string(context.config));
2802 impl Rewrite for ast::ForeignItem {
2803 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2804 let attrs_str = self.attrs.rewrite(context, shape)?;
2805 // Drop semicolon or it will be interpreted as comment.
2806 // FIXME: this may be a faulty span from libsyntax.
2807 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2809 let item_str = match self.node {
2810 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2814 &FnSig::new(fn_decl, generics, self.vis.clone()),
2818 ).map(|(s, _)| format!("{};", s)),
2819 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2820 // FIXME(#21): we're dropping potential comments in between the
2821 // function keywords here.
2822 let vis = format_visibility(&self.vis);
2823 let mut_str = if is_mutable { "mut " } else { "" };
2824 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2826 let shape = shape.sub_width(1)?;
2827 ty.rewrite(context, shape).map(|ty_str| {
2828 // 1 = space between prefix and type.
2829 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2832 let nested_indent = shape.indent.block_indent(context.config);
2833 format!("\n{}", nested_indent.to_string(context.config))
2835 format!("{}{}{};", prefix, sep, ty_str)
2838 ast::ForeignItemKind::Ty => {
2839 let vis = format_visibility(&self.vis);
2840 Some(format!("{}type {};", vis, self.ident))
2844 let missing_span = if self.attrs.is_empty() {
2845 mk_sp(self.span.lo(), self.span.lo())
2847 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2849 combine_strs_with_missing_comments(