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.
14 use std::cmp::{min, Ordering};
18 use syntax::codemap::{self, BytePos, Span};
20 use syntax::{abi, ast, ptr, symbol};
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::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27 rewrite_assign_rhs_with, ExprType, RhsTactics};
28 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
29 use macros::{rewrite_macro, MacroPosition};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
34 use types::TraitTyParamBounds;
35 use utils::{colon_spaces, contains_skip, first_line_width, format_abi, format_auto,
36 format_constness, format_defaultness, format_mutability, format_unsafety,
37 format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
38 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
39 stmt_expr, trimmed_last_line_width};
40 use vertical::rewrite_with_alignment;
41 use visitor::FmtVisitor;
43 const DEFAULT_VISIBILITY: ast::Visibility = codemap::Spanned {
44 node: ast::VisibilityKind::Inherited,
45 span: codemap::DUMMY_SP,
48 fn type_annotation_separator(config: &Config) -> &str {
49 colon_spaces(config.space_before_colon(), config.space_after_colon())
52 // Statements of the form
53 // let pat: ty = init;
54 impl Rewrite for ast::Local {
55 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
57 "Local::rewrite {:?} {} {:?}",
58 self, shape.width, shape.indent
61 skip_out_of_file_lines_range!(context, self.span);
63 if contains_skip(&self.attrs) {
67 let attrs_str = self.attrs.rewrite(context, shape)?;
68 let mut result = if attrs_str.is_empty() {
71 combine_strs_with_missing_comments(
76 self.attrs.last().map(|a| a.span.hi()).unwrap(),
85 let pat_shape = shape.offset_left(4)?;
87 let pat_shape = pat_shape.sub_width(1)?;
88 let pat_str = self.pat.rewrite(context, pat_shape)?;
89 result.push_str(&pat_str);
91 // String that is placed within the assignment pattern and expression.
93 let mut infix = String::with_capacity(32);
95 if let Some(ref ty) = self.ty {
96 let separator = type_annotation_separator(context.config);
97 let indent = shape.indent + last_line_width(&result) + separator.len();
99 let budget = shape.width.checked_sub(indent.width() + 1)?;
100 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
102 infix.push_str(separator);
103 infix.push_str(&rewrite);
106 if self.init.is_some() {
107 infix.push_str(" =");
113 result.push_str(&infix);
115 if let Some(ref ex) = self.init {
116 // 1 = trailing semicolon;
117 let nested_shape = shape.sub_width(1)?;
119 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
127 // TODO convert to using rewrite style rather than visitor
128 // TODO format modules in this style
131 keyword: &'static str,
132 abi: Cow<'static, str>,
133 vis: Option<&'a ast::Visibility>,
134 body: Vec<BodyElement<'a>>,
139 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
142 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
146 .map(|i| BodyElement::ForeignItem(i))
153 enum BodyElement<'a> {
154 // Stmt(&'a ast::Stmt),
155 // Field(&'a ast::Field),
156 // Variant(&'a ast::Variant),
157 // Item(&'a ast::Item),
158 ForeignItem(&'a ast::ForeignItem),
161 /// Represents a fn's signature.
162 pub struct FnSig<'a> {
163 decl: &'a ast::FnDecl,
164 generics: &'a ast::Generics,
166 constness: ast::Constness,
167 defaultness: ast::Defaultness,
168 unsafety: ast::Unsafety,
169 visibility: ast::Visibility,
174 decl: &'a ast::FnDecl,
175 generics: &'a ast::Generics,
176 vis: ast::Visibility,
182 constness: ast::Constness::NotConst,
183 defaultness: ast::Defaultness::Final,
184 unsafety: ast::Unsafety::Normal,
189 pub fn from_method_sig(
190 method_sig: &'a ast::MethodSig,
191 generics: &'a ast::Generics,
194 unsafety: method_sig.unsafety,
195 constness: method_sig.constness.node,
196 defaultness: ast::Defaultness::Final,
198 decl: &*method_sig.decl,
200 visibility: DEFAULT_VISIBILITY,
205 fn_kind: &'a visit::FnKind,
206 generics: &'a ast::Generics,
207 decl: &'a ast::FnDecl,
208 defaultness: ast::Defaultness,
211 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
215 constness: constness.node,
218 visibility: visibility.clone(),
220 visit::FnKind::Method(_, method_sig, vis, _) => {
221 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
222 fn_sig.defaultness = defaultness;
223 if let Some(vis) = vis {
224 fn_sig.visibility = vis.clone();
232 fn to_str(&self, context: &RewriteContext) -> String {
233 let mut result = String::with_capacity(128);
234 // Vis defaultness constness unsafety abi.
235 result.push_str(&*format_visibility(&self.visibility));
236 result.push_str(format_defaultness(self.defaultness));
237 result.push_str(format_constness(self.constness));
238 result.push_str(format_unsafety(self.unsafety));
239 result.push_str(&format_abi(
241 context.config.force_explicit_abi(),
248 impl<'a> FmtVisitor<'a> {
249 fn format_item(&mut self, item: &Item) {
250 self.buffer.push_str(&item.abi);
252 let snippet = self.snippet(item.span);
253 let brace_pos = snippet.find_uncommented("{").unwrap();
256 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
257 // FIXME: this skips comments between the extern keyword and the opening
259 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
260 self.block_indent = self.block_indent.block_indent(self.config);
262 if item.body.is_empty() {
263 self.format_missing_no_indent(item.span.hi() - BytePos(1));
264 self.block_indent = self.block_indent.block_unindent(self.config);
265 let indent_str = self.block_indent.to_string(self.config);
266 self.push_str(&indent_str);
268 for item in &item.body {
269 self.format_body_element(item);
272 self.block_indent = self.block_indent.block_unindent(self.config);
273 self.format_missing_with_indent(item.span.hi() - BytePos(1));
278 self.last_pos = item.span.hi();
281 fn format_body_element(&mut self, element: &BodyElement) {
283 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
287 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
288 let item = Item::from_foreign_mod(fm, span, self.config);
289 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 inner_attrs: Option<&[ast::Attribute]>,
306 ) -> Option<String> {
307 let context = self.get_context();
309 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
311 let (mut result, force_newline_brace) =
312 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
315 if self.config.brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
316 || last_line_width(&result) + 2 > self.shape().width
318 newline_brace = true;
319 } else if !result.contains('\n') {
320 newline_brace = false;
323 // Prepare for the function body by possibly adding a newline and
325 // FIXME we'll miss anything between the end of the signature and the
326 // start of the body, but we need more spans from the compiler to solve
329 result.push_str(&indent.to_string_with_newline(self.config));
334 self.single_line_fn(&result, block, inner_attrs)
335 .or_else(|| Some(result))
338 pub fn rewrite_required_fn(
342 sig: &ast::MethodSig,
343 generics: &ast::Generics,
345 ) -> Option<String> {
346 // Drop semicolon or it will be interpreted as comment.
347 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
348 let context = self.get_context();
350 let (mut result, _) = rewrite_fn_base(
354 &FnSig::from_method_sig(sig, generics),
360 // Re-attach semicolon
370 inner_attrs: Option<&[ast::Attribute]>,
371 ) -> Option<String> {
372 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
376 let codemap = self.get_context().codemap;
378 if self.config.empty_item_single_line() && is_empty_block(block, None, codemap)
379 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
381 return Some(format!("{}{{}}", fn_str));
384 if self.config.fn_single_line() && is_simple_block_stmt(block, None, codemap) {
386 if let Some(stmt) = block.stmts.first() {
387 match stmt_expr(stmt) {
389 let suffix = if semicolon_for_expr(&self.get_context(), e) {
395 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
397 .or_else(|| Some(self.snippet(e.span).to_owned()))
399 None => stmt.rewrite(&self.get_context(), self.shape()),
406 if let Some(res) = rewrite {
407 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
408 if !res.contains('\n') && width <= self.config.max_width() {
409 return Some(format!("{}{{ {} }}", fn_str, res));
417 pub fn visit_static(&mut self, static_parts: &StaticParts) {
418 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
419 self.push_rewrite(static_parts.span, rewrite);
422 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
423 let is_tuple = struct_parts.def.is_tuple();
424 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
425 .map(|s| if is_tuple { s + ";" } else { s });
426 self.push_rewrite(struct_parts.span, rewrite);
432 vis: &ast::Visibility,
433 enum_def: &ast::EnumDef,
434 generics: &ast::Generics,
437 let enum_header = format_header("enum ", ident, vis);
438 self.push_str(&enum_header);
440 let enum_snippet = self.snippet(span);
441 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
442 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
443 let generics_str = format_generics(
446 self.config.brace_style(),
447 if enum_def.variants.is_empty() {
448 BracePos::ForceSameLine
453 mk_sp(span.lo(), body_start),
454 last_line_width(&enum_header),
456 self.push_str(&generics_str);
458 self.last_pos = body_start;
460 self.block_indent = self.block_indent.block_indent(self.config);
461 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
463 Some(ref body_str) => self.push_str(body_str),
464 None => self.format_missing_no_indent(span.hi() - BytePos(1)),
466 self.block_indent = self.block_indent.block_unindent(self.config);
468 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
469 let indent_str = self.block_indent.to_string(self.config);
470 self.push_str(&indent_str);
473 self.last_pos = span.hi();
476 // Format the body of an enum definition
477 fn format_variant_list(
479 enum_def: &ast::EnumDef,
482 ) -> Option<String> {
483 if enum_def.variants.is_empty() {
486 let mut result = String::with_capacity(1024);
487 let indentation = self.block_indent.to_string_with_newline(self.config);
488 result.push_str(&indentation);
490 let itemize_list_with = |one_line_width: usize| {
492 self.snippet_provider,
493 enum_def.variants.iter(),
497 if !f.node.attrs.is_empty() {
498 f.node.attrs[0].span.lo()
504 |f| self.format_variant(f, one_line_width),
510 let mut items: Vec<_> =
511 itemize_list_with(self.config.width_heuristics().struct_variant_width);
512 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
513 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
514 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
515 if has_multiline_variant && has_single_line_variant {
516 items = itemize_list_with(0);
519 let shape = self.shape().sub_width(2)?;
520 let fmt = ListFormatting {
521 tactic: DefinitiveListTactic::Vertical,
523 trailing_separator: self.config.trailing_comma(),
524 separator_place: SeparatorPlace::Back,
526 ends_with_newline: true,
527 preserve_newline: true,
531 let list = write_list(&items, &fmt)?;
532 result.push_str(&list);
537 // Variant of an enum.
538 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
539 if contains_skip(&field.node.attrs) {
540 let lo = field.node.attrs[0].span.lo();
541 let span = mk_sp(lo, field.span.hi());
542 return Some(self.snippet(span).to_owned());
545 let context = self.get_context();
547 let shape = self.shape().sub_width(1)?;
548 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
553 .map_or(field.span.lo(), |attr| attr.span.hi());
554 let span = mk_sp(lo, field.span.lo());
556 let variant_body = match field.node.data {
557 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
559 &StructParts::from_variant(field),
561 Some(one_line_width),
563 ast::VariantData::Unit(..) => {
564 if let Some(ref expr) = field.node.disr_expr {
565 let lhs = format!("{} =", field.node.ident.name);
566 rewrite_assign_rhs(&context, lhs, &**expr, shape)?
568 field.node.ident.name.to_string()
573 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
578 context: &RewriteContext,
581 where_span_end: Option<BytePos>,
582 ) -> Option<String> {
583 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
584 let mut result = String::with_capacity(128);
585 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
586 let sep = offset.to_string_with_newline(context.config);
587 result.push_str(&ref_and_type);
589 let where_budget = if result.contains('\n') {
590 context.config.max_width()
592 context.budget(last_line_width(&result))
594 let option = WhereClauseOption::snuggled(&ref_and_type);
595 let where_clause_str = rewrite_where_clause(
597 &generics.where_clause,
598 context.config.brace_style(),
599 Shape::legacy(where_budget, offset.block_only()),
608 // If there is no where clause, we may have missing comments between the trait name and
609 // the opening brace.
610 if generics.where_clause.predicates.is_empty() {
611 if let Some(hi) = where_span_end {
612 match recover_missing_comment_in_span(
613 mk_sp(self_ty.span.hi(), hi),
614 Shape::indented(offset, context.config),
616 last_line_width(&result),
618 Some(ref missing_comment) if !missing_comment.is_empty() => {
619 result.push_str(missing_comment);
626 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
627 result.push_str(&where_clause_str);
628 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
629 result.push_str(&format!("{}{{{}}}", &sep, &sep));
631 result.push_str(" {}");
636 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
637 let width = offset.block_indent + context.config.tab_spaces() - 1;
638 let where_indent = Indent::new(0, width);
639 result.push_str(&where_indent.to_string_with_newline(context.config));
641 result.push_str(&where_clause_str);
643 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
644 match context.config.brace_style() {
645 _ if need_newline => result.push_str(&sep),
646 BraceStyle::AlwaysNextLine => result.push_str(&sep),
647 BraceStyle::PreferSameLine => result.push(' '),
648 BraceStyle::SameLineWhere => {
649 if !where_clause_str.is_empty() {
650 result.push_str(&sep);
659 let snippet = context.snippet(item.span);
660 let open_pos = snippet.find_uncommented("{")? + 1;
662 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
663 let mut visitor = FmtVisitor::from_context(context);
664 let item_indent = offset.block_only().block_indent(context.config);
665 visitor.block_indent = item_indent;
666 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
668 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
669 if context.config.reorder_impl_items() {
670 // Create visitor for each items, then reorder them.
671 let mut buffer = vec![];
673 visitor.visit_impl_item(item);
674 buffer.push((visitor.buffer.clone(), item.clone()));
675 visitor.buffer.clear();
677 // type -> const -> macro -> method
678 use ast::ImplItemKind::*;
679 fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
681 (Type(..), Type(..)) | (Const(..), Const(..)) => false,
686 buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
687 (Type(..), _) => Ordering::Less,
688 (_, Type(..)) => Ordering::Greater,
689 (Const(..), _) => Ordering::Less,
690 (_, Const(..)) => Ordering::Greater,
691 (Macro(..), _) => Ordering::Less,
692 (_, Macro(..)) => Ordering::Greater,
695 let mut prev_kind = None;
696 for (buf, item) in buffer {
697 // Make sure that there are at least a single empty line between
698 // different impl items.
701 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
703 visitor.push_str("\n");
705 visitor.push_str(&item_indent.to_string_with_newline(context.config));
706 visitor.push_str(buf.trim());
707 prev_kind = Some(item.node.clone());
711 visitor.visit_impl_item(item);
715 visitor.format_missing(item.span.hi() - BytePos(1));
717 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
718 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
720 result.push_str(&inner_indent_str);
721 result.push_str(visitor.buffer.to_string().trim());
722 result.push_str(&outer_indent_str);
725 if result.ends_with('{') {
726 result.push_str(&sep);
736 fn is_impl_single_line(
737 context: &RewriteContext,
738 items: &[ast::ImplItem],
740 where_clause_str: &str,
743 let snippet = context.snippet(item.span);
744 let open_pos = snippet.find_uncommented("{")? + 1;
747 context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
748 && result.len() + where_clause_str.len() <= context.config.max_width()
749 && !contains_comment(&snippet[open_pos..]),
753 fn format_impl_ref_and_type(
754 context: &RewriteContext,
757 ) -> Option<String> {
758 if let ast::ItemKind::Impl(
768 let mut result = String::with_capacity(128);
770 result.push_str(&format_visibility(&item.vis));
771 result.push_str(format_defaultness(defaultness));
772 result.push_str(format_unsafety(unsafety));
774 let lo = context.snippet_provider.span_after(item.span, "impl");
775 let hi = match *trait_ref {
776 Some(ref tr) => tr.path.span.lo(),
777 None => self_ty.span.lo(),
779 let shape = generics_shape_from_config(
781 Shape::indented(offset + last_line_width(&result), context.config),
784 let generics_str = rewrite_generics(context, "impl", generics, shape, mk_sp(lo, hi))?;
785 result.push_str(&generics_str);
787 let polarity_str = if polarity == ast::ImplPolarity::Negative {
793 if let Some(ref trait_ref) = *trait_ref {
794 let result_len = last_line_width(&result);
795 result.push_str(&rewrite_trait_ref(
804 // Try to put the self type in a single line.
806 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
807 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
808 // If there is no where clause adapt budget for type formatting to take space and curly
809 // brace into account.
810 match context.config.brace_style() {
811 BraceStyle::AlwaysNextLine => 0,
817 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
818 // 1 = space before the type.
819 let budget = context.budget(used_space + 1);
820 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
821 if !self_ty_str.contains('\n') {
822 if trait_ref.is_some() {
823 result.push_str(" for ");
827 result.push_str(&self_ty_str);
832 // Couldn't fit the self type on a single line, put it on a new line.
834 // Add indentation of one additional tab.
835 let new_line_offset = offset.block_indent(context.config);
836 result.push_str(&new_line_offset.to_string(context.config));
837 if trait_ref.is_some() {
838 result.push_str("for ");
840 let budget = context.budget(last_line_width(&result));
841 let type_offset = match context.config.indent_style() {
842 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
843 IndentStyle::Block => new_line_offset,
845 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
852 fn rewrite_trait_ref(
853 context: &RewriteContext,
854 trait_ref: &ast::TraitRef,
858 ) -> Option<String> {
859 // 1 = space between generics and trait_ref
860 let used_space = 1 + polarity_str.len() + result_len;
861 let shape = Shape::indented(offset + used_space, context.config);
862 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
863 if !trait_ref_str.contains('\n') {
864 return Some(format!(" {}{}", polarity_str, &trait_ref_str));
867 // We could not make enough space for trait_ref, so put it on new line.
868 let offset = offset.block_indent(context.config);
869 let shape = Shape::indented(offset, context.config);
870 let trait_ref_str = trait_ref.rewrite(context, shape)?;
873 &offset.to_string_with_newline(context.config),
879 pub struct StructParts<'a> {
882 vis: &'a ast::Visibility,
883 def: &'a ast::VariantData,
884 generics: Option<&'a ast::Generics>,
888 impl<'a> StructParts<'a> {
889 fn format_header(&self) -> String {
890 format_header(self.prefix, self.ident, self.vis)
893 fn from_variant(variant: &'a ast::Variant) -> Self {
896 ident: variant.node.ident,
897 vis: &DEFAULT_VISIBILITY,
898 def: &variant.node.data,
904 pub fn from_item(item: &'a ast::Item) -> Self {
905 let (prefix, def, generics) = match item.node {
906 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
907 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
915 generics: Some(generics),
922 context: &RewriteContext,
923 struct_parts: &StructParts,
925 one_line_width: Option<usize>,
926 ) -> Option<String> {
927 match *struct_parts.def {
928 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
929 ast::VariantData::Tuple(ref fields, _) => {
930 format_tuple_struct(context, struct_parts, fields, offset)
932 ast::VariantData::Struct(ref fields, _) => {
933 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
938 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
939 if let ast::ItemKind::Trait(
943 ref type_param_bounds,
947 let mut result = String::with_capacity(128);
948 let header = format!(
950 format_auto(is_auto),
951 format_visibility(&item.vis),
952 format_unsafety(unsafety),
954 result.push_str(&header);
956 let body_lo = context.snippet_provider.span_after(item.span, "{");
958 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
959 let generics_str = rewrite_generics(
961 &item.ident.to_string(),
964 mk_sp(item.span.lo(), body_lo),
966 result.push_str(&generics_str);
968 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
969 if !type_param_bounds.is_empty() {
970 let ident_hi = context
972 .span_after(item.span, &format!("{}", item.ident));
973 let bound_hi = type_param_bounds.last().unwrap().span().hi();
974 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
975 if contains_comment(snippet) {
979 if !type_param_bounds.is_empty() {
980 result = rewrite_assign_rhs_with(
983 &TraitTyParamBounds::new(type_param_bounds),
985 RhsTactics::ForceNextLine,
989 // Rewrite where clause.
990 if !generics.where_clause.predicates.is_empty() {
991 let where_density = if context.config.indent_style() == IndentStyle::Block {
997 let where_budget = context.budget(last_line_width(&result));
998 let pos_before_where = if type_param_bounds.is_empty() {
999 generics.where_clause.span.lo()
1001 type_param_bounds[type_param_bounds.len() - 1].span().hi()
1003 let option = WhereClauseOption::snuggled(&generics_str);
1004 let where_clause_str = rewrite_where_clause(
1006 &generics.where_clause,
1007 context.config.brace_style(),
1008 Shape::legacy(where_budget, offset.block_only()),
1016 // If the where clause cannot fit on the same line,
1017 // put the where clause on a new line
1018 if !where_clause_str.contains('\n')
1019 && last_line_width(&result) + where_clause_str.len() + offset.width()
1020 > context.config.comment_width()
1022 let width = offset.block_indent + context.config.tab_spaces() - 1;
1023 let where_indent = Indent::new(0, width);
1024 result.push_str(&where_indent.to_string_with_newline(context.config));
1026 result.push_str(&where_clause_str);
1028 let item_snippet = context.snippet(item.span);
1029 if let Some(lo) = item_snippet.find('/') {
1031 let comment_hi = body_lo - BytePos(1);
1032 let comment_lo = item.span.lo() + BytePos(lo as u32);
1033 if comment_lo < comment_hi {
1034 match recover_missing_comment_in_span(
1035 mk_sp(comment_lo, comment_hi),
1036 Shape::indented(offset, context.config),
1038 last_line_width(&result),
1040 Some(ref missing_comment) if !missing_comment.is_empty() => {
1041 result.push_str(missing_comment);
1049 match context.config.brace_style() {
1050 _ if last_line_contains_single_line_comment(&result)
1051 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1053 result.push_str(&offset.to_string_with_newline(context.config));
1055 BraceStyle::AlwaysNextLine => {
1056 result.push_str(&offset.to_string_with_newline(context.config));
1058 BraceStyle::PreferSameLine => result.push(' '),
1059 BraceStyle::SameLineWhere => {
1060 if result.contains('\n')
1061 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1063 result.push_str(&offset.to_string_with_newline(context.config));
1071 let snippet = context.snippet(item.span);
1072 let open_pos = snippet.find_uncommented("{")? + 1;
1074 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1075 let mut visitor = FmtVisitor::from_context(context);
1076 visitor.block_indent = offset.block_only().block_indent(context.config);
1077 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1079 for item in trait_items {
1080 visitor.visit_trait_item(item);
1083 visitor.format_missing(item.span.hi() - BytePos(1));
1085 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1086 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1088 result.push_str(&inner_indent_str);
1089 result.push_str(visitor.buffer.to_string().trim());
1090 result.push_str(&outer_indent_str);
1091 } else if result.contains('\n') {
1102 pub fn format_trait_alias(
1103 context: &RewriteContext,
1105 generics: &ast::Generics,
1106 ty_param_bounds: &ast::TyParamBounds,
1108 ) -> Option<String> {
1109 let alias = ident.name.as_str();
1110 // 6 = "trait ", 2 = " ="
1111 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1112 let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
1113 let lhs = format!("trait {} =", generics_str);
1115 rewrite_assign_rhs(context, lhs, ty_param_bounds, shape.sub_width(1)?).map(|s| s + ";")
1118 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1119 let header_str = format_header(p.prefix, p.ident, p.vis);
1120 let generics_str = if let Some(generics) = p.generics {
1121 let hi = if generics.where_clause.predicates.is_empty() {
1124 generics.where_clause.span.hi()
1129 context.config.brace_style(),
1132 mk_sp(generics.span.lo(), hi),
1133 last_line_width(&header_str),
1138 Some(format!("{}{};", header_str, generics_str))
1141 pub fn format_struct_struct(
1142 context: &RewriteContext,
1143 struct_parts: &StructParts,
1144 fields: &[ast::StructField],
1146 one_line_width: Option<usize>,
1147 ) -> Option<String> {
1148 let mut result = String::with_capacity(1024);
1149 let span = struct_parts.span;
1151 let header_str = struct_parts.format_header();
1152 result.push_str(&header_str);
1154 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1155 let body_lo = context.snippet_provider.span_after(span, "{");
1157 let generics_str = match struct_parts.generics {
1158 Some(g) => format_generics(
1161 context.config.brace_style(),
1162 if fields.is_empty() {
1163 BracePos::ForceSameLine
1168 mk_sp(header_hi, body_lo),
1169 last_line_width(&result),
1172 // 3 = ` {}`, 2 = ` {`.
1173 let overhead = if fields.is_empty() { 3 } else { 2 };
1174 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1175 || context.config.max_width() < overhead + result.len()
1177 format!("\n{}{{", offset.block_only().to_string(context.config))
1184 let overhead = if fields.is_empty() { 1 } else { 0 };
1185 let total_width = result.len() + generics_str.len() + overhead;
1186 if !generics_str.is_empty() && !generics_str.contains('\n')
1187 && total_width > context.config.max_width()
1190 result.push_str(&offset.to_string(context.config));
1191 result.push_str(generics_str.trim_left());
1193 result.push_str(&generics_str);
1196 if fields.is_empty() {
1197 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1198 if snippet.trim().is_empty() {
1200 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1202 result.push_str(snippet.trim_right());
1204 result.push_str(&offset.to_string(context.config));
1206 result.push_str(snippet);
1209 return Some(result);
1213 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1214 let one_line_budget =
1215 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1217 let items_str = rewrite_with_alignment(
1220 Shape::indented(offset, context.config).sub_width(1)?,
1221 mk_sp(body_lo, span.hi()),
1225 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget
1226 && !last_line_contains_single_line_comment(&items_str)
1228 Some(format!("{} {} }}", result, items_str))
1234 .block_indent(context.config)
1235 .to_string(context.config),
1237 offset.to_string(context.config)
1242 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1244 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1245 _ => default_span.lo(),
1249 fn format_tuple_struct(
1250 context: &RewriteContext,
1251 struct_parts: &StructParts,
1252 fields: &[ast::StructField],
1254 ) -> Option<String> {
1255 let mut result = String::with_capacity(1024);
1256 let span = struct_parts.span;
1258 let header_str = struct_parts.format_header();
1259 result.push_str(&header_str);
1261 let body_lo = if fields.is_empty() {
1262 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1265 .span_after(mk_sp(lo, span.hi()), "(")
1269 let body_hi = if fields.is_empty() {
1272 .span_after(mk_sp(body_lo, span.hi()), ")")
1274 // This is a dirty hack to work around a missing `)` from the span of the last field.
1275 let last_arg_span = fields[fields.len() - 1].span;
1276 if context.snippet(last_arg_span).ends_with(')') {
1281 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1285 let where_clause_str = match struct_parts.generics {
1287 let budget = context.budget(last_line_width(&header_str));
1288 let shape = Shape::legacy(budget, offset);
1289 let g_span = mk_sp(span.lo(), body_lo);
1290 let generics_str = rewrite_generics(context, "", generics, shape, g_span)?;
1291 result.push_str(&generics_str);
1293 let where_budget = context.budget(last_line_width(&result));
1294 let option = WhereClauseOption::new(true, false);
1295 rewrite_where_clause(
1297 &generics.where_clause,
1298 context.config.brace_style(),
1299 Shape::legacy(where_budget, offset.block_only()),
1300 Density::Compressed,
1308 None => "".to_owned(),
1311 if fields.is_empty() {
1313 let used_width = last_line_used_width(&result, offset.width()) + 3;
1314 if used_width > context.config.max_width() {
1316 result.push_str(&offset
1317 .block_indent(context.config)
1318 .to_string(context.config))
1321 let snippet = context.snippet(mk_sp(
1325 .span_before(mk_sp(body_lo, span.hi()), ")"),
1327 if snippet.is_empty() {
1329 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1330 result.push_str(snippet.trim_right());
1332 result.push_str(&offset.to_string(context.config));
1334 result.push_str(snippet);
1338 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1339 let fields = &fields.iter().collect::<Vec<_>>();
1340 result = overflow::rewrite_with_parens(
1346 context.config.width_heuristics().fn_call_width,
1351 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1352 && (result.contains('\n')
1353 || offset.block_indent + result.len() + where_clause_str.len() + 1
1354 > context.config.max_width())
1356 // We need to put the where clause on a new line, but we didn't
1357 // know that earlier, so the where clause will not be indented properly.
1360 .push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1361 .to_string(context.config));
1363 result.push_str(&where_clause_str);
1368 pub fn rewrite_type_alias(
1369 context: &RewriteContext,
1373 generics: &ast::Generics,
1374 vis: &ast::Visibility,
1376 ) -> Option<String> {
1377 let mut result = String::with_capacity(128);
1379 result.push_str(&format_visibility(vis));
1380 result.push_str("type ");
1383 let g_shape = Shape::indented(indent, context.config)
1384 .offset_left(result.len())?
1387 context.snippet_provider.span_after(span, "type"),
1390 let generics_str = rewrite_generics(context, &ident.to_string(), generics, g_shape, g_span)?;
1391 result.push_str(&generics_str);
1393 let where_budget = context.budget(last_line_width(&result));
1394 let option = WhereClauseOption::snuggled(&result);
1395 let where_clause_str = rewrite_where_clause(
1397 &generics.where_clause,
1398 context.config.brace_style(),
1399 Shape::legacy(where_budget, indent),
1407 result.push_str(&where_clause_str);
1408 if where_clause_str.is_empty() {
1409 result.push_str(" =");
1411 result.push_str(&format!(
1413 indent.to_string_with_newline(context.config)
1418 let ty_shape = Shape::indented(indent, context.config).sub_width(1)?;
1419 rewrite_assign_rhs(context, result, ty, ty_shape).map(|s| s + ";")
1422 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1424 if config.space_before_colon() { " " } else { "" },
1425 if config.space_after_colon() { " " } else { "" },
1429 pub fn rewrite_struct_field_prefix(
1430 context: &RewriteContext,
1431 field: &ast::StructField,
1432 ) -> Option<String> {
1433 let vis = format_visibility(&field.vis);
1434 let type_annotation_spacing = type_annotation_spacing(context.config);
1435 Some(match field.ident {
1436 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1437 None => format!("{}", vis),
1441 impl Rewrite for ast::StructField {
1442 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1443 rewrite_struct_field(context, self, shape, 0)
1447 pub fn rewrite_struct_field(
1448 context: &RewriteContext,
1449 field: &ast::StructField,
1451 lhs_max_width: usize,
1452 ) -> Option<String> {
1453 if contains_skip(&field.attrs) {
1454 return Some(context.snippet(field.span()).to_owned());
1457 let type_annotation_spacing = type_annotation_spacing(context.config);
1458 let prefix = rewrite_struct_field_prefix(context, field)?;
1460 let attrs_str = field.attrs.rewrite(context, shape)?;
1461 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1462 let missing_span = if field.attrs.is_empty() {
1463 mk_sp(field.span.lo(), field.span.lo())
1465 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1467 let mut spacing = String::from(if field.ident.is_some() {
1468 type_annotation_spacing.1
1472 // Try to put everything on a single line.
1473 let attr_prefix = combine_strs_with_missing_comments(
1481 let overhead = last_line_width(&attr_prefix);
1482 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1483 for _ in 0..lhs_offset {
1486 // In this extreme case we will be missing a space betweeen an attribute and a field.
1487 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1491 .offset_left(overhead + spacing.len())
1492 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1493 if let Some(ref ty) = orig_ty {
1494 if !ty.contains('\n') {
1495 return Some(attr_prefix + &spacing + ty);
1499 let is_prefix_empty = prefix.is_empty();
1500 // We must use multiline. We are going to put attributes and a field on different lines.
1501 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1502 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1503 let field_str = if is_prefix_empty {
1504 field_str.trim_left()
1508 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1511 pub struct StaticParts<'a> {
1513 vis: &'a ast::Visibility,
1516 mutability: ast::Mutability,
1517 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1518 defaultness: Option<ast::Defaultness>,
1522 impl<'a> StaticParts<'a> {
1523 pub fn from_item(item: &'a ast::Item) -> Self {
1524 let (prefix, ty, mutability, expr) = match item.node {
1525 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1526 ast::ItemKind::Const(ref ty, ref expr) => {
1527 ("const", ty, ast::Mutability::Immutable, expr)
1529 _ => unreachable!(),
1537 expr_opt: Some(expr),
1543 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1544 let (ty, expr_opt) = match ti.node {
1545 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1546 _ => unreachable!(),
1550 vis: &DEFAULT_VISIBILITY,
1553 mutability: ast::Mutability::Immutable,
1554 expr_opt: expr_opt.as_ref(),
1560 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1561 let (ty, expr) = match ii.node {
1562 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1563 _ => unreachable!(),
1570 mutability: ast::Mutability::Immutable,
1571 expr_opt: Some(expr),
1572 defaultness: Some(ii.defaultness),
1579 context: &RewriteContext,
1580 static_parts: &StaticParts,
1582 ) -> Option<String> {
1583 let colon = colon_spaces(
1584 context.config.space_before_colon(),
1585 context.config.space_after_colon(),
1587 let mut prefix = format!(
1589 format_visibility(static_parts.vis),
1590 static_parts.defaultness.map_or("", format_defaultness),
1591 static_parts.prefix,
1592 format_mutability(static_parts.mutability),
1598 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1599 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1600 Some(ty_str) => ty_str,
1602 if prefix.ends_with(' ') {
1605 let nested_indent = offset.block_indent(context.config);
1606 let nested_shape = Shape::indented(nested_indent, context.config);
1607 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1610 nested_indent.to_string_with_newline(context.config),
1616 if let Some(expr) = static_parts.expr_opt {
1617 let lhs = format!("{}{} =", prefix, ty_str);
1619 let remaining_width = context.budget(offset.block_indent + 1);
1624 Shape::legacy(remaining_width, offset.block_only()),
1625 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1626 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1628 Some(format!("{}{};", prefix, ty_str))
1632 pub fn rewrite_associated_type(
1634 ty_opt: Option<&ptr::P<ast::Ty>>,
1635 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1636 context: &RewriteContext,
1638 ) -> Option<String> {
1639 let prefix = format!("type {}", ident);
1641 let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1642 if bounds.is_empty() {
1646 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1647 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1653 if let Some(ty) = ty_opt {
1655 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1656 let lhs = format!("{}{} =", prefix, type_bounds_str);
1657 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1659 Some(format!("{}{};", prefix, type_bounds_str))
1663 pub fn rewrite_associated_impl_type(
1665 defaultness: ast::Defaultness,
1666 ty_opt: Option<&ptr::P<ast::Ty>>,
1667 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1668 context: &RewriteContext,
1670 ) -> Option<String> {
1671 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1674 ast::Defaultness::Default => Some(format!("default {}", result)),
1679 impl Rewrite for ast::FunctionRetTy {
1680 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1682 ast::FunctionRetTy::Default(_) => Some(String::new()),
1683 ast::FunctionRetTy::Ty(ref ty) => {
1684 let inner_width = shape.width.checked_sub(3)?;
1685 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1686 .map(|r| format!("-> {}", r))
1692 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1694 ast::TyKind::Infer => {
1695 let original = context.snippet(ty.span);
1702 impl Rewrite for ast::Arg {
1703 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1704 if is_named_arg(self) {
1705 let mut result = self.pat
1706 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1708 if !is_empty_infer(context, &*self.ty) {
1709 if context.config.space_before_colon() {
1710 result.push_str(" ");
1712 result.push_str(":");
1713 if context.config.space_after_colon() {
1714 result.push_str(" ");
1716 let overhead = last_line_width(&result);
1717 let max_width = shape.width.checked_sub(overhead)?;
1718 let ty_str = self.ty
1719 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1720 result.push_str(&ty_str);
1725 self.ty.rewrite(context, shape)
1730 fn rewrite_explicit_self(
1731 explicit_self: &ast::ExplicitSelf,
1733 context: &RewriteContext,
1734 ) -> Option<String> {
1735 match explicit_self.node {
1736 ast::SelfKind::Region(lt, m) => {
1737 let mut_str = format_mutability(m);
1740 let lifetime_str = l.rewrite(
1742 Shape::legacy(context.config.max_width(), Indent::empty()),
1744 Some(format!("&{} {}self", lifetime_str, mut_str))
1746 None => Some(format!("&{}self", mut_str)),
1749 ast::SelfKind::Explicit(ref ty, _) => {
1750 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1752 let mutability = explicit_self_mutability(&args[0]);
1753 let type_str = ty.rewrite(
1755 Shape::legacy(context.config.max_width(), Indent::empty()),
1760 format_mutability(mutability),
1764 ast::SelfKind::Value(_) => {
1765 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1767 let mutability = explicit_self_mutability(&args[0]);
1769 Some(format!("{}self", format_mutability(mutability)))
1774 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1775 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1776 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1777 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1784 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1785 if is_named_arg(arg) {
1792 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1794 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1795 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1796 _ => arg.ty.span.hi(),
1800 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1801 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1802 ident != symbol::keywords::Invalid.ident()
1808 // Return type is (result, force_new_line_for_brace)
1810 context: &RewriteContext,
1815 newline_brace: bool,
1817 ) -> Option<(String, bool)> {
1818 let mut force_new_line_for_brace = false;
1820 let where_clause = &fn_sig.generics.where_clause;
1822 let mut result = String::with_capacity(1024);
1823 result.push_str(&fn_sig.to_str(context));
1826 result.push_str("fn ");
1829 let overhead = if has_body && !newline_brace {
1836 let used_width = last_line_used_width(&result, indent.width());
1837 let one_line_budget = context.budget(used_width + overhead);
1839 width: one_line_budget,
1843 let fd = fn_sig.decl;
1844 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1846 rewrite_generics(context, &ident.to_string(), fn_sig.generics, shape, g_span)?;
1847 result.push_str(&generics_str);
1849 let snuggle_angle_bracket = generics_str
1852 .map_or(false, |l| l.trim_left().len() == 1);
1854 // Note that the width and indent don't really matter, we'll re-layout the
1855 // return type later anyway.
1856 let ret_str = fd.output
1857 .rewrite(context, Shape::indented(indent, context.config))?;
1859 let multi_line_ret_str = ret_str.contains('\n');
1860 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1863 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1874 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1875 one_line_budget, multi_line_budget, arg_indent
1878 // Check if vertical layout was forced.
1879 if one_line_budget == 0 {
1880 if snuggle_angle_bracket {
1883 result.push_str("(");
1884 if context.config.indent_style() == IndentStyle::Visual {
1885 result.push_str(&arg_indent.to_string_with_newline(context.config));
1891 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1892 && result.ends_with('(')
1897 // Skip `pub(crate)`.
1898 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
1899 // A conservative estimation, to goal is to be over all parens in generics
1900 let args_start = fn_sig
1905 .map_or(lo_after_visibility, |param| param.span().hi());
1906 let args_end = if fd.inputs.is_empty() {
1909 .span_after(mk_sp(args_start, span.hi()), ")")
1911 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1912 context.snippet_provider.span_after(last_span, ")")
1914 let args_span = mk_sp(
1917 .span_after(mk_sp(args_start, span.hi()), "("),
1920 let arg_str = rewrite_args(
1923 fd.get_self().as_ref(),
1930 generics_str.contains('\n'),
1933 let put_args_in_block = match context.config.indent_style() {
1934 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1936 } && !fd.inputs.is_empty();
1938 let mut args_last_line_contains_comment = false;
1939 if put_args_in_block {
1940 arg_indent = indent.block_indent(context.config);
1941 result.push_str(&arg_indent.to_string_with_newline(context.config));
1942 result.push_str(&arg_str);
1943 result.push_str(&indent.to_string_with_newline(context.config));
1946 result.push_str(&arg_str);
1947 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1948 // Put the closing brace on the next line if it overflows the max width.
1950 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1953 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1956 // If the last line of args contains comment, we cannot put the closing paren
1957 // on the same line.
1961 .map_or(false, |last_line| last_line.contains("//"))
1963 args_last_line_contains_comment = true;
1964 result.push_str(&arg_indent.to_string_with_newline(context.config));
1970 if let ast::FunctionRetTy::Ty(..) = fd.output {
1971 let ret_should_indent = match context.config.indent_style() {
1972 // If our args are block layout then we surely must have space.
1973 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1974 _ if args_last_line_contains_comment => false,
1975 _ if result.contains('\n') || multi_line_ret_str => true,
1977 // If the return type would push over the max width, then put the return type on
1978 // a new line. With the +1 for the signature length an additional space between
1979 // the closing parenthesis of the argument and the arrow '->' is considered.
1980 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1982 // If there is no where clause, take into account the space after the return type
1984 if where_clause.predicates.is_empty() {
1988 sig_length > context.config.max_width()
1991 let ret_indent = if ret_should_indent {
1992 let indent = if arg_str.is_empty() {
1993 // Aligning with non-existent args looks silly.
1994 force_new_line_for_brace = true;
1997 // FIXME: we might want to check that using the arg indent
1998 // doesn't blow our budget, and if it does, then fallback to
1999 // the where clause indent.
2003 result.push_str(&indent.to_string_with_newline(context.config));
2007 Indent::new(indent.block_indent, last_line_width(&result))
2010 if multi_line_ret_str || ret_should_indent {
2011 // Now that we know the proper indent and width, we need to
2012 // re-layout the return type.
2013 let ret_str = fd.output
2014 .rewrite(context, Shape::indented(ret_indent, context.config))?;
2015 result.push_str(&ret_str);
2017 result.push_str(&ret_str);
2020 // Comment between return type and the end of the decl.
2021 let snippet_lo = fd.output.span().hi();
2022 if where_clause.predicates.is_empty() {
2023 let snippet_hi = span.hi();
2024 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2025 // Try to preserve the layout of the original snippet.
2026 let original_starts_with_newline = snippet
2028 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2029 let original_ends_with_newline = snippet
2030 .rfind(|c| c != ' ')
2031 .map_or(false, |i| snippet[i..].ends_with('\n'));
2032 let snippet = snippet.trim();
2033 if !snippet.is_empty() {
2034 result.push(if original_starts_with_newline {
2039 result.push_str(snippet);
2040 if original_ends_with_newline {
2041 force_new_line_for_brace = true;
2047 let pos_before_where = match fd.output {
2048 ast::FunctionRetTy::Default(..) => args_span.hi(),
2049 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2052 let is_args_multi_lined = arg_str.contains('\n');
2054 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2055 let where_clause_str = rewrite_where_clause(
2058 context.config.brace_style(),
2059 Shape::indented(indent, context.config),
2065 is_args_multi_lined,
2067 // If there are neither where clause nor return type, we may be missing comments between
2069 if where_clause_str.is_empty() {
2070 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2071 match recover_missing_comment_in_span(
2072 mk_sp(args_span.hi(), ret_span.hi()),
2075 last_line_width(&result),
2077 Some(ref missing_comment) if !missing_comment.is_empty() => {
2078 result.push_str(missing_comment);
2079 force_new_line_for_brace = true;
2086 result.push_str(&where_clause_str);
2088 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2089 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2090 Some((result, force_new_line_for_brace))
2093 #[derive(Copy, Clone)]
2094 struct WhereClauseOption {
2095 suppress_comma: bool, // Force no trailing comma
2096 snuggle: bool, // Do not insert newline before `where`
2097 compress_where: bool, // Try single line where clause instead of vertical layout
2100 impl WhereClauseOption {
2101 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2105 compress_where: false,
2109 pub fn snuggled(current: &str) -> WhereClauseOption {
2111 suppress_comma: false,
2112 snuggle: trimmed_last_line_width(current) == 1,
2113 compress_where: false,
2119 context: &RewriteContext,
2121 explicit_self: Option<&ast::ExplicitSelf>,
2122 one_line_budget: usize,
2123 multi_line_budget: usize,
2128 generics_str_contains_newline: bool,
2129 ) -> Option<String> {
2130 let mut arg_item_strs = args.iter()
2131 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2132 .collect::<Option<Vec<_>>>()?;
2134 // Account for sugary self.
2135 // FIXME: the comment for the self argument is dropped. This is blocked
2136 // on rust issue #27522.
2137 let min_args = explicit_self
2138 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2139 .map_or(1, |self_str| {
2140 arg_item_strs[0] = self_str;
2144 // Comments between args.
2145 let mut arg_items = Vec::new();
2147 arg_items.push(ListItem::from_str(""));
2150 // FIXME(#21): if there are no args, there might still be a comment, but
2151 // without spans for the comment or parens, there is no chance of
2152 // getting it right. You also don't get to put a comment on self, unless
2154 if args.len() >= min_args || variadic {
2155 let comment_span_start = if min_args == 2 {
2156 let second_arg_start = if arg_has_pattern(&args[1]) {
2157 args[1].pat.span.lo()
2159 args[1].ty.span.lo()
2161 let reduced_span = mk_sp(span.lo(), second_arg_start);
2163 context.snippet_provider.span_after_last(reduced_span, ",")
2168 enum ArgumentKind<'a> {
2169 Regular(&'a ast::Arg),
2173 let variadic_arg = if variadic {
2174 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2175 let variadic_start =
2176 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2177 Some(ArgumentKind::Variadic(variadic_start))
2182 let more_items = itemize_list(
2183 context.snippet_provider,
2184 args[min_args - 1..]
2186 .map(ArgumentKind::Regular)
2187 .chain(variadic_arg),
2191 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2192 ArgumentKind::Variadic(start) => start,
2195 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2196 ArgumentKind::Variadic(start) => start + BytePos(3),
2199 ArgumentKind::Regular(..) => None,
2200 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2207 arg_items.extend(more_items);
2210 let fits_in_one_line = !generics_str_contains_newline
2211 && (arg_items.is_empty()
2212 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2214 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2215 item.item = Some(arg);
2218 let last_line_ends_with_comment = arg_items
2221 .and_then(|item| item.post_comment.as_ref())
2222 .map_or(false, |s| s.trim().starts_with("//"));
2224 let (indent, trailing_comma) = match context.config.indent_style() {
2225 IndentStyle::Block if fits_in_one_line => {
2226 (indent.block_indent(context.config), SeparatorTactic::Never)
2228 IndentStyle::Block => (
2229 indent.block_indent(context.config),
2230 context.config.trailing_comma(),
2232 IndentStyle::Visual if last_line_ends_with_comment => {
2233 (arg_indent, context.config.trailing_comma())
2235 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2238 let tactic = definitive_tactic(
2240 context.config.fn_args_density().to_list_tactic(),
2244 let budget = match tactic {
2245 DefinitiveListTactic::Horizontal => one_line_budget,
2246 _ => multi_line_budget,
2249 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2251 let fmt = ListFormatting {
2254 trailing_separator: if variadic {
2255 SeparatorTactic::Never
2259 separator_place: SeparatorPlace::Back,
2260 shape: Shape::legacy(budget, indent),
2261 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2262 preserve_newline: true,
2263 config: context.config,
2266 write_list(&arg_items, &fmt)
2269 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2270 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2271 ident != symbol::keywords::Invalid.ident()
2277 fn compute_budgets_for_args(
2278 context: &RewriteContext,
2282 newline_brace: bool,
2284 force_vertical_layout: bool,
2285 ) -> Option<((usize, usize, Indent))> {
2287 "compute_budgets_for_args {} {:?}, {}, {}",
2293 // Try keeping everything on the same line.
2294 if !result.contains('\n') && !force_vertical_layout {
2295 // 2 = `()`, 3 = `() `, space is before ret_string.
2296 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2297 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2307 let one_line_budget = context.budget(used_space);
2309 if one_line_budget > 0 {
2311 let (indent, multi_line_budget) = match context.config.indent_style() {
2312 IndentStyle::Block => {
2313 let indent = indent.block_indent(context.config);
2314 (indent, context.budget(indent.width() + 1))
2316 IndentStyle::Visual => {
2317 let indent = indent + result.len() + 1;
2318 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2319 (indent, context.budget(multi_line_overhead))
2323 return Some((one_line_budget, multi_line_budget, indent));
2327 // Didn't work. we must force vertical layout and put args on a newline.
2328 let new_indent = indent.block_indent(context.config);
2329 let used_space = match context.config.indent_style() {
2331 IndentStyle::Block => new_indent.width() + 1,
2332 // Account for `)` and possibly ` {`.
2333 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2335 Some((0, context.budget(used_space), new_indent))
2338 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2339 let predicate_count = where_clause.predicates.len();
2341 if config.where_single_line() && predicate_count == 1 {
2344 let brace_style = config.brace_style();
2346 brace_style == BraceStyle::AlwaysNextLine
2347 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2350 fn rewrite_generics(
2351 context: &RewriteContext,
2353 generics: &ast::Generics,
2356 ) -> Option<String> {
2357 // FIXME: convert bounds to where clauses where they get too big or if
2358 // there is a where clause at all.
2360 if generics.params.is_empty() {
2361 return Some(ident.to_owned());
2364 let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>();
2365 overflow::rewrite_with_angle_brackets(context, ident, params, shape, span)
2368 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2369 match config.indent_style() {
2370 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2371 IndentStyle::Block => {
2375 .block_indent(config.tab_spaces())
2376 .with_max_width(config)
2382 fn rewrite_where_clause_rfc_style(
2383 context: &RewriteContext,
2384 where_clause: &ast::WhereClause,
2387 span_end: Option<BytePos>,
2388 span_end_before_where: BytePos,
2389 where_clause_option: WhereClauseOption,
2390 is_args_multi_line: bool,
2391 ) -> Option<String> {
2392 let block_shape = shape.block().with_max_width(context.config);
2394 let (span_before, span_after) =
2395 missing_span_before_after_where(span_end_before_where, where_clause);
2396 let (comment_before, comment_after) =
2397 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2399 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2402 block_shape.indent.to_string_with_newline(context.config)
2405 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2407 let clause_shape = clause_shape.sub_width(1)?;
2408 // each clause on one line, trailing comma (except if suppress_comma)
2409 let span_start = where_clause.predicates[0].span().lo();
2410 // If we don't have the start of the next span, then use the end of the
2411 // predicates, but that means we miss comments.
2412 let len = where_clause.predicates.len();
2413 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2414 let span_end = span_end.unwrap_or(end_of_preds);
2415 let items = itemize_list(
2416 context.snippet_provider,
2417 where_clause.predicates.iter(),
2420 |pred| pred.span().lo(),
2421 |pred| pred.span().hi(),
2422 |pred| pred.rewrite(context, clause_shape),
2427 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2428 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2429 SeparatorTactic::Never
2431 context.config.trailing_comma()
2434 // shape should be vertical only and only if we have `where_single_line` option enabled
2435 // and the number of items of the where clause is equal to 1
2436 let shape_tactic = if where_single_line {
2437 DefinitiveListTactic::Horizontal
2439 DefinitiveListTactic::Vertical
2442 let fmt = ListFormatting {
2443 tactic: shape_tactic,
2445 trailing_separator: comma_tactic,
2446 separator_place: SeparatorPlace::Back,
2447 shape: clause_shape,
2448 ends_with_newline: true,
2449 preserve_newline: true,
2450 config: context.config,
2452 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2454 let comment_separator = |comment: &str, shape: Shape| {
2455 if comment.is_empty() {
2458 shape.indent.to_string_with_newline(context.config)
2461 let newline_before_where = comment_separator(&comment_before, shape);
2462 let newline_after_where = comment_separator(&comment_after, clause_shape);
2465 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2466 && comment_after.is_empty() && !preds_str.contains('\n')
2467 && 6 + preds_str.len() <= shape.width || where_single_line
2471 clause_shape.indent.to_string_with_newline(context.config)
2474 "{}{}{}where{}{}{}{}",
2477 newline_before_where,
2478 newline_after_where,
2485 fn rewrite_where_clause(
2486 context: &RewriteContext,
2487 where_clause: &ast::WhereClause,
2488 brace_style: BraceStyle,
2492 span_end: Option<BytePos>,
2493 span_end_before_where: BytePos,
2494 where_clause_option: WhereClauseOption,
2495 is_args_multi_line: bool,
2496 ) -> Option<String> {
2497 if where_clause.predicates.is_empty() {
2498 return Some(String::new());
2501 if context.config.indent_style() == IndentStyle::Block {
2502 return rewrite_where_clause_rfc_style(
2508 span_end_before_where,
2509 where_clause_option,
2514 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2516 let offset = match context.config.indent_style() {
2517 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2518 // 6 = "where ".len()
2519 IndentStyle::Visual => shape.indent + extra_indent + 6,
2521 // FIXME: if indent_style != Visual, then the budgets below might
2522 // be out by a char or two.
2524 let budget = context.config.max_width() - offset.width();
2525 let span_start = where_clause.predicates[0].span().lo();
2526 // If we don't have the start of the next span, then use the end of the
2527 // predicates, but that means we miss comments.
2528 let len = where_clause.predicates.len();
2529 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2530 let span_end = span_end.unwrap_or(end_of_preds);
2531 let items = itemize_list(
2532 context.snippet_provider,
2533 where_clause.predicates.iter(),
2536 |pred| pred.span().lo(),
2537 |pred| pred.span().hi(),
2538 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2543 let item_vec = items.collect::<Vec<_>>();
2544 // FIXME: we don't need to collect here
2545 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2547 let mut comma_tactic = context.config.trailing_comma();
2548 // Kind of a hack because we don't usually have trailing commas in where clauses.
2549 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2550 comma_tactic = SeparatorTactic::Never;
2553 let fmt = ListFormatting {
2556 trailing_separator: comma_tactic,
2557 separator_place: SeparatorPlace::Back,
2558 shape: Shape::legacy(budget, offset),
2559 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2560 preserve_newline: true,
2561 config: context.config,
2563 let preds_str = write_list(&item_vec, &fmt)?;
2565 let end_length = if terminator == "{" {
2566 // If the brace is on the next line we don't need to count it otherwise it needs two
2569 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2570 BraceStyle::PreferSameLine => 2,
2572 } else if terminator == "=" {
2577 if density == Density::Tall || preds_str.contains('\n')
2578 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2582 (shape.indent + extra_indent).to_string(context.config),
2586 Some(format!(" where {}", preds_str))
2590 fn missing_span_before_after_where(
2591 before_item_span_end: BytePos,
2592 where_clause: &ast::WhereClause,
2594 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2596 let pos_after_where = where_clause.span.lo() + BytePos(5);
2597 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2598 (missing_span_before, missing_span_after)
2601 fn rewrite_comments_before_after_where(
2602 context: &RewriteContext,
2603 span_before_where: Span,
2604 span_after_where: Span,
2606 ) -> Option<(String, String)> {
2607 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2608 let after_comment = rewrite_missing_comment(
2610 shape.block_indent(context.config.tab_spaces()),
2613 Some((before_comment, after_comment))
2616 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2617 format!("{}{}{}", format_visibility(vis), item_name, ident)
2620 #[derive(PartialEq, Eq, Clone, Copy)]
2628 context: &RewriteContext,
2629 generics: &ast::Generics,
2630 brace_style: BraceStyle,
2631 brace_pos: BracePos,
2635 ) -> Option<String> {
2636 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2637 let mut result = rewrite_generics(context, "", generics, shape, span)?;
2639 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2640 let budget = context.budget(last_line_used_width(&result, offset.width()));
2641 let mut option = WhereClauseOption::snuggled(&result);
2642 if brace_pos == BracePos::None {
2643 option.suppress_comma = true;
2645 // If the generics are not parameterized then generics.span.hi() == 0,
2646 // so we use span.lo(), which is the position after `struct Foo`.
2647 let span_end_before_where = if generics.is_parameterized() {
2652 let where_clause_str = rewrite_where_clause(
2654 &generics.where_clause,
2656 Shape::legacy(budget, offset.block_only()),
2660 span_end_before_where,
2664 result.push_str(&where_clause_str);
2665 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2666 || (generics.where_clause.predicates.is_empty()
2667 && trimmed_last_line_width(&result) == 1)
2669 brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2670 || brace_style != BraceStyle::AlwaysNextLine
2672 if brace_pos == BracePos::None {
2673 return Some(result);
2675 let total_used_width = last_line_used_width(&result, used_width);
2676 let remaining_budget = context.budget(total_used_width);
2677 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2678 // and hence we take the closer into account as well for one line budget.
2679 // We assume that the closer has the same length as the opener.
2680 let overhead = if brace_pos == BracePos::ForceSameLine {
2687 let forbid_same_line_brace = overhead > remaining_budget;
2688 if !forbid_same_line_brace && same_line_brace {
2692 result.push_str(&offset.block_only().to_string(context.config));
2699 impl Rewrite for ast::ForeignItem {
2700 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2701 let attrs_str = self.attrs.rewrite(context, shape)?;
2702 // Drop semicolon or it will be interpreted as comment.
2703 // FIXME: this may be a faulty span from libsyntax.
2704 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2706 let item_str = match self.node {
2707 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2712 &FnSig::new(fn_decl, generics, self.vis.clone()),
2716 ).map(|(s, _)| format!("{};", s))
2718 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2719 // FIXME(#21): we're dropping potential comments in between the
2720 // function keywords here.
2721 let vis = format_visibility(&self.vis);
2722 let mut_str = if is_mutable { "mut " } else { "" };
2723 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2725 let shape = shape.sub_width(1)?;
2726 ty.rewrite(context, shape).map(|ty_str| {
2727 // 1 = space between prefix and type.
2728 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2731 let nested_indent = shape.indent.block_indent(context.config);
2732 nested_indent.to_string_with_newline(context.config)
2734 format!("{}{}{};", prefix, sep, ty_str)
2737 ast::ForeignItemKind::Ty => {
2738 let vis = format_visibility(&self.vis);
2739 Some(format!("{}type {};", vis, self.ident))
2741 ast::ForeignItemKind::Macro(ref mac) => {
2742 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
2746 let missing_span = if self.attrs.is_empty() {
2747 mk_sp(self.span.lo(), self.span.lo())
2749 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2751 combine_strs_with_missing_comments(
2762 impl Rewrite for ast::GenericParam {
2763 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2765 ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.rewrite(context, shape),
2766 ast::GenericParam::Type(ref ty) => ty.rewrite(context, shape),
2771 /// Rewrite an inline mod.
2772 pub fn rewrite_mod(item: &ast::Item) -> String {
2773 let mut result = String::with_capacity(32);
2774 result.push_str(&*format_visibility(&item.vis));
2775 result.push_str("mod ");
2776 result.push_str(&item.ident.to_string());
2781 /// Rewrite `extern crate foo;` WITHOUT attributes.
2782 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2783 assert!(is_extern_crate(item));
2784 let new_str = context.snippet(item.span);
2785 Some(if contains_comment(new_str) {
2788 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2789 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2793 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2794 pub fn is_mod_decl(item: &ast::Item) -> bool {
2796 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2801 pub fn is_use_item(item: &ast::Item) -> bool {
2803 ast::ItemKind::Use(_) => true,
2808 pub fn is_extern_crate(item: &ast::Item) -> bool {
2810 ast::ItemKind::ExternCrate(..) => true,