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.
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};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
33 use types::TraitTyParamBounds;
34 use utils::{colon_spaces, contains_skip, first_line_width, format_abi, format_constness,
35 format_defaultness, format_mutability, format_unsafety, format_visibility,
36 is_attributes_extendable, last_line_contains_single_line_comment,
37 last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
38 stmt_expr, trimmed_last_line_width};
39 use vertical::rewrite_with_alignment;
40 use visitor::FmtVisitor;
42 const DEFAULT_VISIBILITY: ast::Visibility = codemap::Spanned {
43 node: ast::VisibilityKind::Inherited,
44 span: codemap::DUMMY_SP,
47 fn type_annotation_separator(config: &Config) -> &str {
48 colon_spaces(config.space_before_colon(), config.space_after_colon())
51 // Statements of the form
52 // let pat: ty = init;
53 impl Rewrite for ast::Local {
54 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
56 "Local::rewrite {:?} {} {:?}",
57 self, shape.width, shape.indent
60 skip_out_of_file_lines_range!(context, self.span);
62 if contains_skip(&self.attrs) {
66 let attrs_str = self.attrs.rewrite(context, shape)?;
67 let mut result = if attrs_str.is_empty() {
70 combine_strs_with_missing_comments(
75 self.attrs.last().map(|a| a.span.hi()).unwrap(),
84 let pat_shape = shape.offset_left(4)?;
86 let pat_shape = pat_shape.sub_width(1)?;
87 let pat_str = self.pat.rewrite(context, pat_shape)?;
88 result.push_str(&pat_str);
90 // String that is placed within the assignment pattern and expression.
92 let mut infix = String::with_capacity(32);
94 if let Some(ref ty) = self.ty {
95 let separator = type_annotation_separator(context.config);
96 let indent = shape.indent + last_line_width(&result) + separator.len();
98 let budget = shape.width.checked_sub(indent.width() + 1)?;
99 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
101 infix.push_str(separator);
102 infix.push_str(&rewrite);
105 if self.init.is_some() {
106 infix.push_str(" =");
112 result.push_str(&infix);
114 if let Some(ref ex) = self.init {
115 // 1 = trailing semicolon;
116 let nested_shape = shape.sub_width(1)?;
118 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
126 // TODO convert to using rewrite style rather than visitor
127 // TODO format modules in this style
130 keyword: &'static str,
131 abi: Cow<'static, str>,
132 vis: Option<&'a ast::Visibility>,
133 body: Vec<BodyElement<'a>>,
138 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
141 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
145 .map(|i| BodyElement::ForeignItem(i))
152 enum BodyElement<'a> {
153 // Stmt(&'a ast::Stmt),
154 // Field(&'a ast::Field),
155 // Variant(&'a ast::Variant),
156 // Item(&'a ast::Item),
157 ForeignItem(&'a ast::ForeignItem),
160 /// Represents a fn's signature.
161 pub struct FnSig<'a> {
162 decl: &'a ast::FnDecl,
163 generics: &'a ast::Generics,
165 constness: ast::Constness,
166 defaultness: ast::Defaultness,
167 unsafety: ast::Unsafety,
168 visibility: ast::Visibility,
173 decl: &'a ast::FnDecl,
174 generics: &'a ast::Generics,
175 vis: ast::Visibility,
181 constness: ast::Constness::NotConst,
182 defaultness: ast::Defaultness::Final,
183 unsafety: ast::Unsafety::Normal,
188 pub fn from_method_sig(
189 method_sig: &'a ast::MethodSig,
190 generics: &'a ast::Generics,
193 unsafety: method_sig.unsafety,
194 constness: method_sig.constness.node,
195 defaultness: ast::Defaultness::Final,
197 decl: &*method_sig.decl,
199 visibility: DEFAULT_VISIBILITY,
204 fn_kind: &'a visit::FnKind,
205 generics: &'a ast::Generics,
206 decl: &'a ast::FnDecl,
207 defaultness: ast::Defaultness,
210 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
214 constness: constness.node,
217 visibility: visibility.clone(),
219 visit::FnKind::Method(_, method_sig, vis, _) => {
220 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
221 fn_sig.defaultness = defaultness;
222 if let Some(vis) = vis {
223 fn_sig.visibility = vis.clone();
231 fn to_str(&self, context: &RewriteContext) -> String {
232 let mut result = String::with_capacity(128);
233 // Vis defaultness constness unsafety abi.
234 result.push_str(&*format_visibility(&self.visibility));
235 result.push_str(format_defaultness(self.defaultness));
236 result.push_str(format_constness(self.constness));
237 result.push_str(format_unsafety(self.unsafety));
238 result.push_str(&format_abi(
240 context.config.force_explicit_abi(),
247 impl<'a> FmtVisitor<'a> {
248 fn format_item(&mut self, item: &Item) {
249 self.buffer.push_str(&item.abi);
251 let snippet = self.snippet(item.span);
252 let brace_pos = snippet.find_uncommented("{").unwrap();
255 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
256 // FIXME: this skips comments between the extern keyword and the opening
258 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
259 self.block_indent = self.block_indent.block_indent(self.config);
261 if item.body.is_empty() {
262 self.format_missing_no_indent(item.span.hi() - BytePos(1));
263 self.block_indent = self.block_indent.block_unindent(self.config);
264 let indent_str = self.block_indent.to_string(self.config);
265 self.push_str(&indent_str);
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));
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);
291 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
292 let rewrite = item.rewrite(&self.get_context(), self.shape());
293 self.push_rewrite(item.span(), rewrite);
294 self.last_pos = item.span.hi();
304 inner_attrs: Option<&[ast::Attribute]>,
305 ) -> Option<String> {
306 let context = self.get_context();
308 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
310 let (mut result, force_newline_brace) =
311 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
314 if self.config.brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
315 || last_line_width(&result) + 2 > self.shape().width
317 newline_brace = true;
318 } else if !result.contains('\n') {
319 newline_brace = false;
322 // Prepare for the function body by possibly adding a newline and
324 // FIXME we'll miss anything between the end of the signature and the
325 // start of the body, but we need more spans from the compiler to solve
328 result.push_str(&indent.to_string_with_newline(self.config));
333 self.single_line_fn(&result, block, inner_attrs)
334 .or_else(|| Some(result))
337 pub fn rewrite_required_fn(
341 sig: &ast::MethodSig,
342 generics: &ast::Generics,
344 ) -> Option<String> {
345 // Drop semicolon or it will be interpreted as comment.
346 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
347 let context = self.get_context();
349 let (mut result, _) = rewrite_fn_base(
353 &FnSig::from_method_sig(sig, generics),
359 // Re-attach semicolon
369 inner_attrs: Option<&[ast::Attribute]>,
370 ) -> Option<String> {
371 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
375 let codemap = self.get_context().codemap;
377 if self.config.empty_item_single_line() && is_empty_block(block, None, codemap)
378 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
380 return Some(format!("{}{{}}", fn_str));
383 if self.config.fn_single_line() && is_simple_block_stmt(block, None, codemap) {
385 if let Some(stmt) = block.stmts.first() {
386 match stmt_expr(stmt) {
388 let suffix = if semicolon_for_expr(&self.get_context(), e) {
394 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
396 .or_else(|| Some(self.snippet(e.span).to_owned()))
398 None => stmt.rewrite(&self.get_context(), self.shape()),
405 if let Some(res) = rewrite {
406 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
407 if !res.contains('\n') && width <= self.config.max_width() {
408 return Some(format!("{}{{ {} }}", fn_str, res));
416 pub fn visit_static(&mut self, static_parts: &StaticParts) {
417 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
418 self.push_rewrite(static_parts.span, rewrite);
421 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
422 let is_tuple = struct_parts.def.is_tuple();
423 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
424 .map(|s| if is_tuple { s + ";" } else { s });
425 self.push_rewrite(struct_parts.span, rewrite);
431 vis: &ast::Visibility,
432 enum_def: &ast::EnumDef,
433 generics: &ast::Generics,
436 let enum_header = format_header("enum ", ident, vis);
437 self.push_str(&enum_header);
439 let enum_snippet = self.snippet(span);
440 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
441 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
442 let generics_str = format_generics(
445 self.config.brace_style(),
446 if enum_def.variants.is_empty() {
447 BracePos::ForceSameLine
452 mk_sp(span.lo(), body_start),
453 last_line_width(&enum_header),
455 self.push_str(&generics_str);
457 self.last_pos = body_start;
459 self.block_indent = self.block_indent.block_indent(self.config);
460 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
462 Some(ref body_str) => self.push_str(body_str),
463 None => self.format_missing_no_indent(span.hi() - BytePos(1)),
465 self.block_indent = self.block_indent.block_unindent(self.config);
467 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
468 let indent_str = self.block_indent.to_string(self.config);
469 self.push_str(&indent_str);
472 self.last_pos = span.hi();
475 // Format the body of an enum definition
476 fn format_variant_list(
478 enum_def: &ast::EnumDef,
481 ) -> Option<String> {
482 if enum_def.variants.is_empty() {
485 let mut result = String::with_capacity(1024);
486 let indentation = self.block_indent.to_string_with_newline(self.config);
487 result.push_str(&indentation);
489 let itemize_list_with = |one_line_width: usize| {
491 self.snippet_provider,
492 enum_def.variants.iter(),
496 if !f.node.attrs.is_empty() {
497 f.node.attrs[0].span.lo()
503 |f| self.format_variant(f, one_line_width),
509 let mut items: Vec<_> =
510 itemize_list_with(self.config.width_heuristics().struct_variant_width);
511 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
512 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
513 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
514 if has_multiline_variant && has_single_line_variant {
515 items = itemize_list_with(0);
518 let shape = self.shape().sub_width(2)?;
519 let fmt = ListFormatting {
520 tactic: DefinitiveListTactic::Vertical,
522 trailing_separator: self.config.trailing_comma(),
523 separator_place: SeparatorPlace::Back,
525 ends_with_newline: true,
526 preserve_newline: true,
530 let list = write_list(&items, &fmt)?;
531 result.push_str(&list);
536 // Variant of an enum.
537 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
538 if contains_skip(&field.node.attrs) {
539 let lo = field.node.attrs[0].span.lo();
540 let span = mk_sp(lo, field.span.hi());
541 return Some(self.snippet(span).to_owned());
544 let context = self.get_context();
546 let shape = self.shape().sub_width(1)?;
547 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
552 .map_or(field.span.lo(), |attr| attr.span.hi());
553 let span = mk_sp(lo, field.span.lo());
555 let variant_body = match field.node.data {
556 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
558 &StructParts::from_variant(field),
560 Some(one_line_width),
562 ast::VariantData::Unit(..) => {
563 if let Some(ref expr) = field.node.disr_expr {
564 let lhs = format!("{} =", field.node.name);
565 rewrite_assign_rhs(&context, lhs, &**expr, shape)?
567 field.node.name.to_string()
572 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
577 context: &RewriteContext,
580 where_span_end: Option<BytePos>,
581 ) -> Option<String> {
582 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
583 let mut result = String::with_capacity(128);
584 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
585 let sep = offset.to_string_with_newline(context.config);
586 result.push_str(&ref_and_type);
588 let where_budget = if result.contains('\n') {
589 context.config.max_width()
591 context.budget(last_line_width(&result))
593 let option = WhereClauseOption::snuggled(&ref_and_type);
594 let where_clause_str = rewrite_where_clause(
596 &generics.where_clause,
597 context.config.brace_style(),
598 Shape::legacy(where_budget, offset.block_only()),
607 // If there is no where clause, we may have missing comments between the trait name and
608 // the opening brace.
609 if generics.where_clause.predicates.is_empty() {
610 if let Some(hi) = where_span_end {
611 match recover_missing_comment_in_span(
612 mk_sp(self_ty.span.hi(), hi),
613 Shape::indented(offset, context.config),
615 last_line_width(&result),
617 Some(ref missing_comment) if !missing_comment.is_empty() => {
618 result.push_str(missing_comment);
625 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
626 result.push_str(&where_clause_str);
627 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
628 result.push_str(&format!("{}{{{}}}", &sep, &sep));
630 result.push_str(" {}");
635 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
636 let width = offset.block_indent + context.config.tab_spaces() - 1;
637 let where_indent = Indent::new(0, width);
638 result.push_str(&where_indent.to_string_with_newline(context.config));
640 result.push_str(&where_clause_str);
642 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
643 match context.config.brace_style() {
644 _ if need_newline => result.push_str(&sep),
645 BraceStyle::AlwaysNextLine => result.push_str(&sep),
646 BraceStyle::PreferSameLine => result.push(' '),
647 BraceStyle::SameLineWhere => {
648 if !where_clause_str.is_empty() {
649 result.push_str(&sep);
658 let snippet = context.snippet(item.span);
659 let open_pos = snippet.find_uncommented("{")? + 1;
661 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
662 let mut visitor = FmtVisitor::from_context(context);
663 visitor.block_indent = offset.block_only().block_indent(context.config);
664 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
666 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
668 visitor.visit_impl_item(item);
671 visitor.format_missing(item.span.hi() - BytePos(1));
673 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
674 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
676 result.push_str(&inner_indent_str);
677 result.push_str(visitor.buffer.to_string().trim());
678 result.push_str(&outer_indent_str);
681 if result.ends_with('{') {
682 result.push_str(&sep);
692 fn is_impl_single_line(
693 context: &RewriteContext,
694 items: &[ast::ImplItem],
696 where_clause_str: &str,
699 let snippet = context.snippet(item.span);
700 let open_pos = snippet.find_uncommented("{")? + 1;
703 context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
704 && result.len() + where_clause_str.len() <= context.config.max_width()
705 && !contains_comment(&snippet[open_pos..]),
709 fn format_impl_ref_and_type(
710 context: &RewriteContext,
713 ) -> Option<String> {
714 if let ast::ItemKind::Impl(
724 let mut result = String::with_capacity(128);
726 result.push_str(&format_visibility(&item.vis));
727 result.push_str(format_defaultness(defaultness));
728 result.push_str(format_unsafety(unsafety));
730 let lo = context.snippet_provider.span_after(item.span, "impl");
731 let hi = match *trait_ref {
732 Some(ref tr) => tr.path.span.lo(),
733 None => self_ty.span.lo(),
735 let shape = generics_shape_from_config(
737 Shape::indented(offset + last_line_width(&result), context.config),
740 let generics_str = rewrite_generics(context, "impl", generics, shape, mk_sp(lo, hi))?;
741 result.push_str(&generics_str);
743 let polarity_str = if polarity == ast::ImplPolarity::Negative {
749 if let Some(ref trait_ref) = *trait_ref {
750 let result_len = last_line_width(&result);
751 result.push_str(&rewrite_trait_ref(
760 // Try to put the self type in a single line.
762 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
763 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
764 // If there is no where clause adapt budget for type formatting to take space and curly
765 // brace into account.
766 match context.config.brace_style() {
767 BraceStyle::AlwaysNextLine => 0,
773 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
774 // 1 = space before the type.
775 let budget = context.budget(used_space + 1);
776 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
777 if !self_ty_str.contains('\n') {
778 if trait_ref.is_some() {
779 result.push_str(" for ");
783 result.push_str(&self_ty_str);
788 // Couldn't fit the self type on a single line, put it on a new line.
790 // Add indentation of one additional tab.
791 let new_line_offset = offset.block_indent(context.config);
792 result.push_str(&new_line_offset.to_string(context.config));
793 if trait_ref.is_some() {
794 result.push_str("for ");
796 let budget = context.budget(last_line_width(&result));
797 let type_offset = match context.config.indent_style() {
798 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
799 IndentStyle::Block => new_line_offset,
801 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
808 fn rewrite_trait_ref(
809 context: &RewriteContext,
810 trait_ref: &ast::TraitRef,
814 ) -> Option<String> {
815 // 1 = space between generics and trait_ref
816 let used_space = 1 + polarity_str.len() + result_len;
817 let shape = Shape::indented(offset + used_space, context.config);
818 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
819 if !trait_ref_str.contains('\n') {
820 return Some(format!(" {}{}", polarity_str, &trait_ref_str));
823 // We could not make enough space for trait_ref, so put it on new line.
824 let offset = offset.block_indent(context.config);
825 let shape = Shape::indented(offset, context.config);
826 let trait_ref_str = trait_ref.rewrite(context, shape)?;
829 &offset.to_string_with_newline(context.config),
835 pub struct StructParts<'a> {
838 vis: &'a ast::Visibility,
839 def: &'a ast::VariantData,
840 generics: Option<&'a ast::Generics>,
844 impl<'a> StructParts<'a> {
845 fn format_header(&self) -> String {
846 format_header(self.prefix, self.ident, self.vis)
849 fn from_variant(variant: &'a ast::Variant) -> Self {
852 ident: variant.node.name,
853 vis: &DEFAULT_VISIBILITY,
854 def: &variant.node.data,
860 pub fn from_item(item: &'a ast::Item) -> Self {
861 let (prefix, def, generics) = match item.node {
862 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
863 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
871 generics: Some(generics),
878 context: &RewriteContext,
879 struct_parts: &StructParts,
881 one_line_width: Option<usize>,
882 ) -> Option<String> {
883 match *struct_parts.def {
884 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
885 ast::VariantData::Tuple(ref fields, _) => {
886 format_tuple_struct(context, struct_parts, fields, offset)
888 ast::VariantData::Struct(ref fields, _) => {
889 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
894 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
895 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
898 let mut result = String::with_capacity(128);
899 let header = format!(
901 format_visibility(&item.vis),
902 format_unsafety(unsafety),
905 result.push_str(&header);
907 let body_lo = context.snippet_provider.span_after(item.span, "{");
909 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
910 let generics_str = rewrite_generics(
912 &item.ident.to_string(),
915 mk_sp(item.span.lo(), body_lo),
917 result.push_str(&generics_str);
919 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
920 if !type_param_bounds.is_empty() {
921 let ident_hi = context
923 .span_after(item.span, &format!("{}", item.ident));
924 let bound_hi = type_param_bounds.last().unwrap().span().hi();
925 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
926 if contains_comment(snippet) {
930 if !type_param_bounds.is_empty() {
931 result = rewrite_assign_rhs_with(
934 &TraitTyParamBounds::new(type_param_bounds),
936 RhsTactics::ForceNextLine,
940 // Rewrite where clause.
941 if !generics.where_clause.predicates.is_empty() {
942 let where_density = if context.config.indent_style() == IndentStyle::Block {
948 let where_budget = context.budget(last_line_width(&result));
949 let pos_before_where = if type_param_bounds.is_empty() {
950 generics.where_clause.span.lo()
952 type_param_bounds[type_param_bounds.len() - 1].span().hi()
954 let option = WhereClauseOption::snuggled(&generics_str);
955 let where_clause_str = rewrite_where_clause(
957 &generics.where_clause,
958 context.config.brace_style(),
959 Shape::legacy(where_budget, offset.block_only()),
967 // If the where clause cannot fit on the same line,
968 // put the where clause on a new line
969 if !where_clause_str.contains('\n')
970 && last_line_width(&result) + where_clause_str.len() + offset.width()
971 > context.config.comment_width()
973 let width = offset.block_indent + context.config.tab_spaces() - 1;
974 let where_indent = Indent::new(0, width);
975 result.push_str(&where_indent.to_string_with_newline(context.config));
977 result.push_str(&where_clause_str);
979 let item_snippet = context.snippet(item.span);
980 if let Some(lo) = item_snippet.find('/') {
982 let comment_hi = body_lo - BytePos(1);
983 let comment_lo = item.span.lo() + BytePos(lo as u32);
984 if comment_lo < comment_hi {
985 match recover_missing_comment_in_span(
986 mk_sp(comment_lo, comment_hi),
987 Shape::indented(offset, context.config),
989 last_line_width(&result),
991 Some(ref missing_comment) if !missing_comment.is_empty() => {
992 result.push_str(missing_comment);
1000 match context.config.brace_style() {
1001 _ if last_line_contains_single_line_comment(&result)
1002 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1004 result.push_str(&offset.to_string_with_newline(context.config));
1006 BraceStyle::AlwaysNextLine => {
1007 result.push_str(&offset.to_string_with_newline(context.config));
1009 BraceStyle::PreferSameLine => result.push(' '),
1010 BraceStyle::SameLineWhere => {
1011 if result.contains('\n')
1012 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1014 result.push_str(&offset.to_string_with_newline(context.config));
1022 let snippet = context.snippet(item.span);
1023 let open_pos = snippet.find_uncommented("{")? + 1;
1025 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1026 let mut visitor = FmtVisitor::from_context(context);
1027 visitor.block_indent = offset.block_only().block_indent(context.config);
1028 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1030 for item in trait_items {
1031 visitor.visit_trait_item(item);
1034 visitor.format_missing(item.span.hi() - BytePos(1));
1036 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1037 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1039 result.push_str(&inner_indent_str);
1040 result.push_str(visitor.buffer.to_string().trim());
1041 result.push_str(&outer_indent_str);
1042 } else if result.contains('\n') {
1053 pub fn format_trait_alias(
1054 context: &RewriteContext,
1056 generics: &ast::Generics,
1057 ty_param_bounds: &ast::TyParamBounds,
1059 ) -> Option<String> {
1060 let alias = ident.name.as_str();
1061 // 6 = "trait ", 2 = " ="
1062 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1063 let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
1064 let lhs = format!("trait {} =", generics_str);
1066 rewrite_assign_rhs(context, lhs, ty_param_bounds, shape.sub_width(1)?).map(|s| s + ";")
1069 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1070 let header_str = format_header(p.prefix, p.ident, p.vis);
1071 let generics_str = if let Some(generics) = p.generics {
1072 let hi = if generics.where_clause.predicates.is_empty() {
1075 generics.where_clause.span.hi()
1080 context.config.brace_style(),
1083 mk_sp(generics.span.lo(), hi),
1084 last_line_width(&header_str),
1089 Some(format!("{}{};", header_str, generics_str))
1092 pub fn format_struct_struct(
1093 context: &RewriteContext,
1094 struct_parts: &StructParts,
1095 fields: &[ast::StructField],
1097 one_line_width: Option<usize>,
1098 ) -> Option<String> {
1099 let mut result = String::with_capacity(1024);
1100 let span = struct_parts.span;
1102 let header_str = struct_parts.format_header();
1103 result.push_str(&header_str);
1105 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1106 let body_lo = context.snippet_provider.span_after(span, "{");
1108 let generics_str = match struct_parts.generics {
1109 Some(g) => format_generics(
1112 context.config.brace_style(),
1113 if fields.is_empty() {
1114 BracePos::ForceSameLine
1119 mk_sp(header_hi, body_lo),
1120 last_line_width(&result),
1123 // 3 = ` {}`, 2 = ` {`.
1124 let overhead = if fields.is_empty() { 3 } else { 2 };
1125 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1126 || context.config.max_width() < overhead + result.len()
1128 format!("\n{}{{", offset.block_only().to_string(context.config))
1135 let overhead = if fields.is_empty() { 1 } else { 0 };
1136 let total_width = result.len() + generics_str.len() + overhead;
1137 if !generics_str.is_empty() && !generics_str.contains('\n')
1138 && total_width > context.config.max_width()
1141 result.push_str(&offset.to_string(context.config));
1142 result.push_str(generics_str.trim_left());
1144 result.push_str(&generics_str);
1147 if fields.is_empty() {
1148 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1149 if snippet.trim().is_empty() {
1151 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1153 result.push_str(snippet.trim_right());
1155 result.push_str(&offset.to_string(context.config));
1157 result.push_str(snippet);
1160 return Some(result);
1164 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1165 let one_line_budget =
1166 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1168 let items_str = rewrite_with_alignment(
1171 Shape::indented(offset, context.config).sub_width(1)?,
1172 mk_sp(body_lo, span.hi()),
1176 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget
1177 && !last_line_contains_single_line_comment(&items_str)
1179 Some(format!("{} {} }}", result, items_str))
1185 .block_indent(context.config)
1186 .to_string(context.config),
1188 offset.to_string(context.config)
1193 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1195 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1196 _ => default_span.lo(),
1200 fn format_tuple_struct(
1201 context: &RewriteContext,
1202 struct_parts: &StructParts,
1203 fields: &[ast::StructField],
1205 ) -> Option<String> {
1206 let mut result = String::with_capacity(1024);
1207 let span = struct_parts.span;
1209 let header_str = struct_parts.format_header();
1210 result.push_str(&header_str);
1212 let body_lo = if fields.is_empty() {
1213 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1216 .span_after(mk_sp(lo, span.hi()), "(")
1220 let body_hi = if fields.is_empty() {
1223 .span_after(mk_sp(body_lo, span.hi()), ")")
1225 // This is a dirty hack to work around a missing `)` from the span of the last field.
1226 let last_arg_span = fields[fields.len() - 1].span;
1227 if context.snippet(last_arg_span).ends_with(')') {
1232 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1236 let where_clause_str = match struct_parts.generics {
1238 let budget = context.budget(last_line_width(&header_str));
1239 let shape = Shape::legacy(budget, offset);
1240 let g_span = mk_sp(span.lo(), body_lo);
1241 let generics_str = rewrite_generics(context, "", generics, shape, g_span)?;
1242 result.push_str(&generics_str);
1244 let where_budget = context.budget(last_line_width(&result));
1245 let option = WhereClauseOption::new(true, false);
1246 rewrite_where_clause(
1248 &generics.where_clause,
1249 context.config.brace_style(),
1250 Shape::legacy(where_budget, offset.block_only()),
1251 Density::Compressed,
1259 None => "".to_owned(),
1262 if fields.is_empty() {
1264 let used_width = last_line_used_width(&result, offset.width()) + 3;
1265 if used_width > context.config.max_width() {
1267 result.push_str(&offset
1268 .block_indent(context.config)
1269 .to_string(context.config))
1272 let snippet = context.snippet(mk_sp(
1276 .span_before(mk_sp(body_lo, span.hi()), ")"),
1278 if snippet.is_empty() {
1280 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1281 result.push_str(snippet.trim_right());
1283 result.push_str(&offset.to_string(context.config));
1285 result.push_str(snippet);
1289 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1290 let fields = &fields.iter().collect::<Vec<_>>();
1291 result = overflow::rewrite_with_parens(
1297 context.config.width_heuristics().fn_call_width,
1302 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1303 && (result.contains('\n')
1304 || offset.block_indent + result.len() + where_clause_str.len() + 1
1305 > context.config.max_width())
1307 // We need to put the where clause on a new line, but we didn't
1308 // know that earlier, so the where clause will not be indented properly.
1311 .push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1312 .to_string(context.config));
1314 result.push_str(&where_clause_str);
1319 pub fn rewrite_type_alias(
1320 context: &RewriteContext,
1324 generics: &ast::Generics,
1325 vis: &ast::Visibility,
1327 ) -> Option<String> {
1328 let mut result = String::with_capacity(128);
1330 result.push_str(&format_visibility(vis));
1331 result.push_str("type ");
1334 let g_shape = Shape::indented(indent, context.config)
1335 .offset_left(result.len())?
1338 context.snippet_provider.span_after(span, "type"),
1341 let generics_str = rewrite_generics(context, &ident.to_string(), generics, g_shape, g_span)?;
1342 result.push_str(&generics_str);
1344 let where_budget = context.budget(last_line_width(&result));
1345 let option = WhereClauseOption::snuggled(&result);
1346 let where_clause_str = rewrite_where_clause(
1348 &generics.where_clause,
1349 context.config.brace_style(),
1350 Shape::legacy(where_budget, indent),
1358 result.push_str(&where_clause_str);
1359 if where_clause_str.is_empty() {
1360 result.push_str(" =");
1362 result.push_str(&format!(
1364 indent.to_string_with_newline(context.config)
1369 let ty_shape = Shape::indented(indent, context.config).sub_width(1)?;
1370 rewrite_assign_rhs(context, result, ty, ty_shape).map(|s| s + ";")
1373 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1375 if config.space_before_colon() { " " } else { "" },
1376 if config.space_after_colon() { " " } else { "" },
1380 pub fn rewrite_struct_field_prefix(
1381 context: &RewriteContext,
1382 field: &ast::StructField,
1383 ) -> Option<String> {
1384 let vis = format_visibility(&field.vis);
1385 let type_annotation_spacing = type_annotation_spacing(context.config);
1386 Some(match field.ident {
1387 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1388 None => format!("{}", vis),
1392 impl Rewrite for ast::StructField {
1393 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1394 rewrite_struct_field(context, self, shape, 0)
1398 pub fn rewrite_struct_field(
1399 context: &RewriteContext,
1400 field: &ast::StructField,
1402 lhs_max_width: usize,
1403 ) -> Option<String> {
1404 if contains_skip(&field.attrs) {
1405 return Some(context.snippet(field.span()).to_owned());
1408 let type_annotation_spacing = type_annotation_spacing(context.config);
1409 let prefix = rewrite_struct_field_prefix(context, field)?;
1411 let attrs_str = field.attrs.rewrite(context, shape)?;
1412 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1413 let missing_span = if field.attrs.is_empty() {
1414 mk_sp(field.span.lo(), field.span.lo())
1416 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1418 let mut spacing = String::from(if field.ident.is_some() {
1419 type_annotation_spacing.1
1423 // Try to put everything on a single line.
1424 let attr_prefix = combine_strs_with_missing_comments(
1432 let overhead = last_line_width(&attr_prefix);
1433 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1434 for _ in 0..lhs_offset {
1437 // In this extreme case we will be missing a space betweeen an attribute and a field.
1438 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1442 .offset_left(overhead + spacing.len())
1443 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1444 if let Some(ref ty) = orig_ty {
1445 if !ty.contains('\n') {
1446 return Some(attr_prefix + &spacing + ty);
1450 let is_prefix_empty = prefix.is_empty();
1451 // We must use multiline. We are going to put attributes and a field on different lines.
1452 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1453 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1454 let field_str = if is_prefix_empty {
1455 field_str.trim_left()
1459 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1462 pub struct StaticParts<'a> {
1464 vis: &'a ast::Visibility,
1467 mutability: ast::Mutability,
1468 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1469 defaultness: Option<ast::Defaultness>,
1473 impl<'a> StaticParts<'a> {
1474 pub fn from_item(item: &'a ast::Item) -> Self {
1475 let (prefix, ty, mutability, expr) = match item.node {
1476 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1477 ast::ItemKind::Const(ref ty, ref expr) => {
1478 ("const", ty, ast::Mutability::Immutable, expr)
1480 _ => unreachable!(),
1488 expr_opt: Some(expr),
1494 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1495 let (ty, expr_opt) = match ti.node {
1496 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1497 _ => unreachable!(),
1501 vis: &DEFAULT_VISIBILITY,
1504 mutability: ast::Mutability::Immutable,
1505 expr_opt: expr_opt.as_ref(),
1511 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1512 let (ty, expr) = match ii.node {
1513 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1514 _ => unreachable!(),
1521 mutability: ast::Mutability::Immutable,
1522 expr_opt: Some(expr),
1523 defaultness: Some(ii.defaultness),
1530 context: &RewriteContext,
1531 static_parts: &StaticParts,
1533 ) -> Option<String> {
1534 let colon = colon_spaces(
1535 context.config.space_before_colon(),
1536 context.config.space_after_colon(),
1538 let mut prefix = format!(
1540 format_visibility(static_parts.vis),
1541 static_parts.defaultness.map_or("", format_defaultness),
1542 static_parts.prefix,
1543 format_mutability(static_parts.mutability),
1549 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1550 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1551 Some(ty_str) => ty_str,
1553 if prefix.ends_with(' ') {
1556 let nested_indent = offset.block_indent(context.config);
1557 let nested_shape = Shape::indented(nested_indent, context.config);
1558 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1561 nested_indent.to_string_with_newline(context.config),
1567 if let Some(expr) = static_parts.expr_opt {
1568 let lhs = format!("{}{} =", prefix, ty_str);
1570 let remaining_width = context.budget(offset.block_indent + 1);
1575 Shape::legacy(remaining_width, offset.block_only()),
1576 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1577 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1579 Some(format!("{}{};", prefix, ty_str))
1583 pub fn rewrite_associated_type(
1585 ty_opt: Option<&ptr::P<ast::Ty>>,
1586 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1587 context: &RewriteContext,
1589 ) -> Option<String> {
1590 let prefix = format!("type {}", ident);
1592 let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1593 if bounds.is_empty() {
1597 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1598 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1604 if let Some(ty) = ty_opt {
1606 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1607 let lhs = format!("{}{} =", prefix, type_bounds_str);
1608 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1610 Some(format!("{}{};", prefix, type_bounds_str))
1614 pub fn rewrite_associated_impl_type(
1616 defaultness: ast::Defaultness,
1617 ty_opt: Option<&ptr::P<ast::Ty>>,
1618 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1619 context: &RewriteContext,
1621 ) -> Option<String> {
1622 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1625 ast::Defaultness::Default => Some(format!("default {}", result)),
1630 impl Rewrite for ast::FunctionRetTy {
1631 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1633 ast::FunctionRetTy::Default(_) => Some(String::new()),
1634 ast::FunctionRetTy::Ty(ref ty) => {
1635 let inner_width = shape.width.checked_sub(3)?;
1636 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1637 .map(|r| format!("-> {}", r))
1643 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1645 ast::TyKind::Infer => {
1646 let original = context.snippet(ty.span);
1653 impl Rewrite for ast::Arg {
1654 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1655 if is_named_arg(self) {
1656 let mut result = self.pat
1657 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1659 if !is_empty_infer(context, &*self.ty) {
1660 if context.config.space_before_colon() {
1661 result.push_str(" ");
1663 result.push_str(":");
1664 if context.config.space_after_colon() {
1665 result.push_str(" ");
1667 let overhead = last_line_width(&result);
1668 let max_width = shape.width.checked_sub(overhead)?;
1669 let ty_str = self.ty
1670 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1671 result.push_str(&ty_str);
1676 self.ty.rewrite(context, shape)
1681 fn rewrite_explicit_self(
1682 explicit_self: &ast::ExplicitSelf,
1684 context: &RewriteContext,
1685 ) -> Option<String> {
1686 match explicit_self.node {
1687 ast::SelfKind::Region(lt, m) => {
1688 let mut_str = format_mutability(m);
1691 let lifetime_str = l.rewrite(
1693 Shape::legacy(context.config.max_width(), Indent::empty()),
1695 Some(format!("&{} {}self", lifetime_str, mut_str))
1697 None => Some(format!("&{}self", mut_str)),
1700 ast::SelfKind::Explicit(ref ty, _) => {
1701 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1703 let mutability = explicit_self_mutability(&args[0]);
1704 let type_str = ty.rewrite(
1706 Shape::legacy(context.config.max_width(), Indent::empty()),
1711 format_mutability(mutability),
1715 ast::SelfKind::Value(_) => {
1716 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1718 let mutability = explicit_self_mutability(&args[0]);
1720 Some(format!("{}self", format_mutability(mutability)))
1725 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1726 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1727 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1728 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1735 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1736 if is_named_arg(arg) {
1743 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1745 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1746 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1747 _ => arg.ty.span.hi(),
1751 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1752 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1753 ident.node != symbol::keywords::Invalid.ident()
1759 // Return type is (result, force_new_line_for_brace)
1761 context: &RewriteContext,
1766 newline_brace: bool,
1768 ) -> Option<(String, bool)> {
1769 let mut force_new_line_for_brace = false;
1771 let where_clause = &fn_sig.generics.where_clause;
1773 let mut result = String::with_capacity(1024);
1774 result.push_str(&fn_sig.to_str(context));
1777 result.push_str("fn ");
1780 let overhead = if has_body && !newline_brace {
1787 let used_width = last_line_used_width(&result, indent.width());
1788 let one_line_budget = context.budget(used_width + overhead);
1790 width: one_line_budget,
1794 let fd = fn_sig.decl;
1795 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1797 rewrite_generics(context, &ident.to_string(), fn_sig.generics, shape, g_span)?;
1798 result.push_str(&generics_str);
1800 let snuggle_angle_bracket = generics_str
1803 .map_or(false, |l| l.trim_left().len() == 1);
1805 // Note that the width and indent don't really matter, we'll re-layout the
1806 // return type later anyway.
1807 let ret_str = fd.output
1808 .rewrite(context, Shape::indented(indent, context.config))?;
1810 let multi_line_ret_str = ret_str.contains('\n');
1811 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1814 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1825 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1826 one_line_budget, multi_line_budget, arg_indent
1829 // Check if vertical layout was forced.
1830 if one_line_budget == 0 {
1831 if snuggle_angle_bracket {
1834 result.push_str("(");
1835 if context.config.indent_style() == IndentStyle::Visual {
1836 result.push_str(&arg_indent.to_string_with_newline(context.config));
1842 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1843 && result.ends_with('(')
1848 // Skip `pub(crate)`.
1849 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
1850 // A conservative estimation, to goal is to be over all parens in generics
1851 let args_start = fn_sig
1856 .map_or(lo_after_visibility, |param| param.span().hi());
1857 let args_end = if fd.inputs.is_empty() {
1860 .span_after(mk_sp(args_start, span.hi()), ")")
1862 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1863 context.snippet_provider.span_after(last_span, ")")
1865 let args_span = mk_sp(
1868 .span_after(mk_sp(args_start, span.hi()), "("),
1871 let arg_str = rewrite_args(
1874 fd.get_self().as_ref(),
1881 generics_str.contains('\n'),
1884 let put_args_in_block = match context.config.indent_style() {
1885 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1887 } && !fd.inputs.is_empty();
1889 let mut args_last_line_contains_comment = false;
1890 if put_args_in_block {
1891 arg_indent = indent.block_indent(context.config);
1892 result.push_str(&arg_indent.to_string_with_newline(context.config));
1893 result.push_str(&arg_str);
1894 result.push_str(&indent.to_string_with_newline(context.config));
1897 result.push_str(&arg_str);
1898 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1899 // Put the closing brace on the next line if it overflows the max width.
1901 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1904 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1907 // If the last line of args contains comment, we cannot put the closing paren
1908 // on the same line.
1912 .map_or(false, |last_line| last_line.contains("//"))
1914 args_last_line_contains_comment = true;
1915 result.push_str(&arg_indent.to_string_with_newline(context.config));
1921 if let ast::FunctionRetTy::Ty(..) = fd.output {
1922 let ret_should_indent = match context.config.indent_style() {
1923 // If our args are block layout then we surely must have space.
1924 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1925 _ if args_last_line_contains_comment => false,
1926 _ if result.contains('\n') || multi_line_ret_str => true,
1928 // If the return type would push over the max width, then put the return type on
1929 // a new line. With the +1 for the signature length an additional space between
1930 // the closing parenthesis of the argument and the arrow '->' is considered.
1931 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1933 // If there is no where clause, take into account the space after the return type
1935 if where_clause.predicates.is_empty() {
1939 sig_length > context.config.max_width()
1942 let ret_indent = if ret_should_indent {
1943 let indent = if arg_str.is_empty() {
1944 // Aligning with non-existent args looks silly.
1945 force_new_line_for_brace = true;
1948 // FIXME: we might want to check that using the arg indent
1949 // doesn't blow our budget, and if it does, then fallback to
1950 // the where clause indent.
1954 result.push_str(&indent.to_string_with_newline(context.config));
1958 Indent::new(indent.block_indent, last_line_width(&result))
1961 if multi_line_ret_str || ret_should_indent {
1962 // Now that we know the proper indent and width, we need to
1963 // re-layout the return type.
1964 let ret_str = fd.output
1965 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1966 result.push_str(&ret_str);
1968 result.push_str(&ret_str);
1971 // Comment between return type and the end of the decl.
1972 let snippet_lo = fd.output.span().hi();
1973 if where_clause.predicates.is_empty() {
1974 let snippet_hi = span.hi();
1975 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1976 // Try to preserve the layout of the original snippet.
1977 let original_starts_with_newline = snippet
1979 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1980 let original_ends_with_newline = snippet
1981 .rfind(|c| c != ' ')
1982 .map_or(false, |i| snippet[i..].ends_with('\n'));
1983 let snippet = snippet.trim();
1984 if !snippet.is_empty() {
1985 result.push(if original_starts_with_newline {
1990 result.push_str(snippet);
1991 if original_ends_with_newline {
1992 force_new_line_for_brace = true;
1998 let pos_before_where = match fd.output {
1999 ast::FunctionRetTy::Default(..) => args_span.hi(),
2000 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2003 let is_args_multi_lined = arg_str.contains('\n');
2005 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2006 let where_clause_str = rewrite_where_clause(
2009 context.config.brace_style(),
2010 Shape::indented(indent, context.config),
2016 is_args_multi_lined,
2018 // If there are neither where clause nor return type, we may be missing comments between
2020 if where_clause_str.is_empty() {
2021 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2022 match recover_missing_comment_in_span(
2023 mk_sp(args_span.hi(), ret_span.hi()),
2026 last_line_width(&result),
2028 Some(ref missing_comment) if !missing_comment.is_empty() => {
2029 result.push_str(missing_comment);
2030 force_new_line_for_brace = true;
2037 result.push_str(&where_clause_str);
2039 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2040 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2041 Some((result, force_new_line_for_brace))
2044 #[derive(Copy, Clone)]
2045 struct WhereClauseOption {
2046 suppress_comma: bool, // Force no trailing comma
2047 snuggle: bool, // Do not insert newline before `where`
2048 compress_where: bool, // Try single line where clause instead of vertical layout
2051 impl WhereClauseOption {
2052 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2056 compress_where: false,
2060 pub fn snuggled(current: &str) -> WhereClauseOption {
2062 suppress_comma: false,
2063 snuggle: trimmed_last_line_width(current) == 1,
2064 compress_where: false,
2070 context: &RewriteContext,
2072 explicit_self: Option<&ast::ExplicitSelf>,
2073 one_line_budget: usize,
2074 multi_line_budget: usize,
2079 generics_str_contains_newline: bool,
2080 ) -> Option<String> {
2081 let mut arg_item_strs = args.iter()
2082 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2083 .collect::<Option<Vec<_>>>()?;
2085 // Account for sugary self.
2086 // FIXME: the comment for the self argument is dropped. This is blocked
2087 // on rust issue #27522.
2088 let min_args = explicit_self
2089 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2090 .map_or(1, |self_str| {
2091 arg_item_strs[0] = self_str;
2095 // Comments between args.
2096 let mut arg_items = Vec::new();
2098 arg_items.push(ListItem::from_str(""));
2101 // FIXME(#21): if there are no args, there might still be a comment, but
2102 // without spans for the comment or parens, there is no chance of
2103 // getting it right. You also don't get to put a comment on self, unless
2105 if args.len() >= min_args || variadic {
2106 let comment_span_start = if min_args == 2 {
2107 let second_arg_start = if arg_has_pattern(&args[1]) {
2108 args[1].pat.span.lo()
2110 args[1].ty.span.lo()
2112 let reduced_span = mk_sp(span.lo(), second_arg_start);
2114 context.snippet_provider.span_after_last(reduced_span, ",")
2119 enum ArgumentKind<'a> {
2120 Regular(&'a ast::Arg),
2124 let variadic_arg = if variadic {
2125 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2126 let variadic_start =
2127 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2128 Some(ArgumentKind::Variadic(variadic_start))
2133 let more_items = itemize_list(
2134 context.snippet_provider,
2135 args[min_args - 1..]
2137 .map(ArgumentKind::Regular)
2138 .chain(variadic_arg),
2142 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2143 ArgumentKind::Variadic(start) => start,
2146 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2147 ArgumentKind::Variadic(start) => start + BytePos(3),
2150 ArgumentKind::Regular(..) => None,
2151 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2158 arg_items.extend(more_items);
2161 let fits_in_one_line = !generics_str_contains_newline
2162 && (arg_items.is_empty()
2163 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2165 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2166 item.item = Some(arg);
2169 let last_line_ends_with_comment = arg_items
2172 .and_then(|item| item.post_comment.as_ref())
2173 .map_or(false, |s| s.trim().starts_with("//"));
2175 let (indent, trailing_comma) = match context.config.indent_style() {
2176 IndentStyle::Block if fits_in_one_line => {
2177 (indent.block_indent(context.config), SeparatorTactic::Never)
2179 IndentStyle::Block => (
2180 indent.block_indent(context.config),
2181 context.config.trailing_comma(),
2183 IndentStyle::Visual if last_line_ends_with_comment => {
2184 (arg_indent, context.config.trailing_comma())
2186 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2189 let tactic = definitive_tactic(
2191 context.config.fn_args_density().to_list_tactic(),
2195 let budget = match tactic {
2196 DefinitiveListTactic::Horizontal => one_line_budget,
2197 _ => multi_line_budget,
2200 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2202 let fmt = ListFormatting {
2205 trailing_separator: if variadic {
2206 SeparatorTactic::Never
2210 separator_place: SeparatorPlace::Back,
2211 shape: Shape::legacy(budget, indent),
2212 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2213 preserve_newline: true,
2214 config: context.config,
2217 write_list(&arg_items, &fmt)
2220 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2221 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2222 ident.node != symbol::keywords::Invalid.ident()
2228 fn compute_budgets_for_args(
2229 context: &RewriteContext,
2233 newline_brace: bool,
2235 force_vertical_layout: bool,
2236 ) -> Option<((usize, usize, Indent))> {
2238 "compute_budgets_for_args {} {:?}, {}, {}",
2244 // Try keeping everything on the same line.
2245 if !result.contains('\n') && !force_vertical_layout {
2246 // 2 = `()`, 3 = `() `, space is before ret_string.
2247 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2248 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2258 let one_line_budget = context.budget(used_space);
2260 if one_line_budget > 0 {
2262 let (indent, multi_line_budget) = match context.config.indent_style() {
2263 IndentStyle::Block => {
2264 let indent = indent.block_indent(context.config);
2265 (indent, context.budget(indent.width() + 1))
2267 IndentStyle::Visual => {
2268 let indent = indent + result.len() + 1;
2269 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2270 (indent, context.budget(multi_line_overhead))
2274 return Some((one_line_budget, multi_line_budget, indent));
2278 // Didn't work. we must force vertical layout and put args on a newline.
2279 let new_indent = indent.block_indent(context.config);
2280 let used_space = match context.config.indent_style() {
2282 IndentStyle::Block => new_indent.width() + 1,
2283 // Account for `)` and possibly ` {`.
2284 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2286 Some((0, context.budget(used_space), new_indent))
2289 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2290 let predicate_count = where_clause.predicates.len();
2292 if config.where_single_line() && predicate_count == 1 {
2295 let brace_style = config.brace_style();
2297 brace_style == BraceStyle::AlwaysNextLine
2298 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2301 fn rewrite_generics(
2302 context: &RewriteContext,
2304 generics: &ast::Generics,
2307 ) -> Option<String> {
2308 // FIXME: convert bounds to where clauses where they get too big or if
2309 // there is a where clause at all.
2311 if generics.params.is_empty() {
2312 return Some(ident.to_owned());
2315 let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>();
2316 overflow::rewrite_with_angle_brackets(context, ident, params, shape, span)
2319 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2320 match config.indent_style() {
2321 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2322 IndentStyle::Block => {
2326 .block_indent(config.tab_spaces())
2327 .with_max_width(config)
2333 fn rewrite_where_clause_rfc_style(
2334 context: &RewriteContext,
2335 where_clause: &ast::WhereClause,
2338 span_end: Option<BytePos>,
2339 span_end_before_where: BytePos,
2340 where_clause_option: WhereClauseOption,
2341 is_args_multi_line: bool,
2342 ) -> Option<String> {
2343 let block_shape = shape.block().with_max_width(context.config);
2345 let (span_before, span_after) =
2346 missing_span_before_after_where(span_end_before_where, where_clause);
2347 let (comment_before, comment_after) =
2348 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2350 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2353 block_shape.indent.to_string_with_newline(context.config)
2356 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2358 let clause_shape = clause_shape.sub_width(1)?;
2359 // each clause on one line, trailing comma (except if suppress_comma)
2360 let span_start = where_clause.predicates[0].span().lo();
2361 // If we don't have the start of the next span, then use the end of the
2362 // predicates, but that means we miss comments.
2363 let len = where_clause.predicates.len();
2364 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2365 let span_end = span_end.unwrap_or(end_of_preds);
2366 let items = itemize_list(
2367 context.snippet_provider,
2368 where_clause.predicates.iter(),
2371 |pred| pred.span().lo(),
2372 |pred| pred.span().hi(),
2373 |pred| pred.rewrite(context, clause_shape),
2378 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2379 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2380 SeparatorTactic::Never
2382 context.config.trailing_comma()
2385 // shape should be vertical only and only if we have `where_single_line` option enabled
2386 // and the number of items of the where clause is equal to 1
2387 let shape_tactic = if where_single_line {
2388 DefinitiveListTactic::Horizontal
2390 DefinitiveListTactic::Vertical
2393 let fmt = ListFormatting {
2394 tactic: shape_tactic,
2396 trailing_separator: comma_tactic,
2397 separator_place: SeparatorPlace::Back,
2398 shape: clause_shape,
2399 ends_with_newline: true,
2400 preserve_newline: true,
2401 config: context.config,
2403 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2405 let comment_separator = |comment: &str, shape: Shape| {
2406 if comment.is_empty() {
2409 shape.indent.to_string_with_newline(context.config)
2412 let newline_before_where = comment_separator(&comment_before, shape);
2413 let newline_after_where = comment_separator(&comment_after, clause_shape);
2416 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2417 && comment_after.is_empty() && !preds_str.contains('\n')
2418 && 6 + preds_str.len() <= shape.width || where_single_line
2422 clause_shape.indent.to_string_with_newline(context.config)
2425 "{}{}{}where{}{}{}{}",
2428 newline_before_where,
2429 newline_after_where,
2436 fn rewrite_where_clause(
2437 context: &RewriteContext,
2438 where_clause: &ast::WhereClause,
2439 brace_style: BraceStyle,
2443 span_end: Option<BytePos>,
2444 span_end_before_where: BytePos,
2445 where_clause_option: WhereClauseOption,
2446 is_args_multi_line: bool,
2447 ) -> Option<String> {
2448 if where_clause.predicates.is_empty() {
2449 return Some(String::new());
2452 if context.config.indent_style() == IndentStyle::Block {
2453 return rewrite_where_clause_rfc_style(
2459 span_end_before_where,
2460 where_clause_option,
2465 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2467 let offset = match context.config.indent_style() {
2468 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2469 // 6 = "where ".len()
2470 IndentStyle::Visual => shape.indent + extra_indent + 6,
2472 // FIXME: if indent_style != Visual, then the budgets below might
2473 // be out by a char or two.
2475 let budget = context.config.max_width() - offset.width();
2476 let span_start = where_clause.predicates[0].span().lo();
2477 // If we don't have the start of the next span, then use the end of the
2478 // predicates, but that means we miss comments.
2479 let len = where_clause.predicates.len();
2480 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2481 let span_end = span_end.unwrap_or(end_of_preds);
2482 let items = itemize_list(
2483 context.snippet_provider,
2484 where_clause.predicates.iter(),
2487 |pred| pred.span().lo(),
2488 |pred| pred.span().hi(),
2489 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2494 let item_vec = items.collect::<Vec<_>>();
2495 // FIXME: we don't need to collect here
2496 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2498 let mut comma_tactic = context.config.trailing_comma();
2499 // Kind of a hack because we don't usually have trailing commas in where clauses.
2500 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2501 comma_tactic = SeparatorTactic::Never;
2504 let fmt = ListFormatting {
2507 trailing_separator: comma_tactic,
2508 separator_place: SeparatorPlace::Back,
2509 shape: Shape::legacy(budget, offset),
2510 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2511 preserve_newline: true,
2512 config: context.config,
2514 let preds_str = write_list(&item_vec, &fmt)?;
2516 let end_length = if terminator == "{" {
2517 // If the brace is on the next line we don't need to count it otherwise it needs two
2520 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2521 BraceStyle::PreferSameLine => 2,
2523 } else if terminator == "=" {
2528 if density == Density::Tall || preds_str.contains('\n')
2529 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2533 (shape.indent + extra_indent).to_string(context.config),
2537 Some(format!(" where {}", preds_str))
2541 fn missing_span_before_after_where(
2542 before_item_span_end: BytePos,
2543 where_clause: &ast::WhereClause,
2545 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2547 let pos_after_where = where_clause.span.lo() + BytePos(5);
2548 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2549 (missing_span_before, missing_span_after)
2552 fn rewrite_comments_before_after_where(
2553 context: &RewriteContext,
2554 span_before_where: Span,
2555 span_after_where: Span,
2557 ) -> Option<(String, String)> {
2558 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2559 let after_comment = rewrite_missing_comment(
2561 shape.block_indent(context.config.tab_spaces()),
2564 Some((before_comment, after_comment))
2567 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2568 format!("{}{}{}", format_visibility(vis), item_name, ident)
2571 #[derive(PartialEq, Eq, Clone, Copy)]
2579 context: &RewriteContext,
2580 generics: &ast::Generics,
2581 brace_style: BraceStyle,
2582 brace_pos: BracePos,
2586 ) -> Option<String> {
2587 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2588 let mut result = rewrite_generics(context, "", generics, shape, span)?;
2590 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2591 let budget = context.budget(last_line_used_width(&result, offset.width()));
2592 let mut option = WhereClauseOption::snuggled(&result);
2593 if brace_pos == BracePos::None {
2594 option.suppress_comma = true;
2596 // If the generics are not parameterized then generics.span.hi() == 0,
2597 // so we use span.lo(), which is the position after `struct Foo`.
2598 let span_end_before_where = if generics.is_parameterized() {
2603 let where_clause_str = rewrite_where_clause(
2605 &generics.where_clause,
2607 Shape::legacy(budget, offset.block_only()),
2611 span_end_before_where,
2615 result.push_str(&where_clause_str);
2616 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2617 || (generics.where_clause.predicates.is_empty()
2618 && trimmed_last_line_width(&result) == 1)
2620 brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2621 || brace_style != BraceStyle::AlwaysNextLine
2623 if brace_pos == BracePos::None {
2624 return Some(result);
2626 let total_used_width = last_line_used_width(&result, used_width);
2627 let remaining_budget = context.budget(total_used_width);
2628 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2629 // and hence we take the closer into account as well for one line budget.
2630 // We assume that the closer has the same length as the opener.
2631 let overhead = if brace_pos == BracePos::ForceSameLine {
2638 let forbid_same_line_brace = overhead > remaining_budget;
2639 if !forbid_same_line_brace && same_line_brace {
2643 result.push_str(&offset.block_only().to_string(context.config));
2650 impl Rewrite for ast::ForeignItem {
2651 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2652 let attrs_str = self.attrs.rewrite(context, shape)?;
2653 // Drop semicolon or it will be interpreted as comment.
2654 // FIXME: this may be a faulty span from libsyntax.
2655 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2657 let item_str = match self.node {
2658 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2663 &FnSig::new(fn_decl, generics, self.vis.clone()),
2667 ).map(|(s, _)| format!("{};", s))
2669 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2670 // FIXME(#21): we're dropping potential comments in between the
2671 // function keywords here.
2672 let vis = format_visibility(&self.vis);
2673 let mut_str = if is_mutable { "mut " } else { "" };
2674 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2676 let shape = shape.sub_width(1)?;
2677 ty.rewrite(context, shape).map(|ty_str| {
2678 // 1 = space between prefix and type.
2679 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2682 let nested_indent = shape.indent.block_indent(context.config);
2683 nested_indent.to_string_with_newline(context.config)
2685 format!("{}{}{};", prefix, sep, ty_str)
2688 ast::ForeignItemKind::Ty => {
2689 let vis = format_visibility(&self.vis);
2690 Some(format!("{}type {};", vis, self.ident))
2694 let missing_span = if self.attrs.is_empty() {
2695 mk_sp(self.span.lo(), self.span.lo())
2697 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2699 combine_strs_with_missing_comments(
2710 impl Rewrite for ast::GenericParam {
2711 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2713 ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.rewrite(context, shape),
2714 ast::GenericParam::Type(ref ty) => ty.rewrite(context, shape),
2719 /// Rewrite an inline mod.
2720 pub fn rewrite_mod(item: &ast::Item) -> String {
2721 let mut result = String::with_capacity(32);
2722 result.push_str(&*format_visibility(&item.vis));
2723 result.push_str("mod ");
2724 result.push_str(&item.ident.to_string());
2729 /// Rewrite `extern crate foo;` WITHOUT attributes.
2730 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2731 assert!(is_extern_crate(item));
2732 let new_str = context.snippet(item.span);
2733 Some(if contains_comment(new_str) {
2736 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2737 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2741 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2742 pub fn is_mod_decl(item: &ast::Item) -> bool {
2744 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2749 pub fn is_use_item(item: &ast::Item) -> bool {
2751 ast::ItemKind::Use(_) => true,
2756 pub fn is_extern_crate(item: &ast::Item) -> bool {
2758 ast::ItemKind::ExternCrate(..) => true,