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::{abi, ast, ptr, symbol};
19 use syntax::codemap::{self, BytePos, Span};
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle};
26 use expr::{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 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 defualtness: ast::Defaultness,
210 visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
214 constness: constness.node,
215 defaultness: defualtness,
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 = defualtness;
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 ) -> Option<String> {
305 let context = self.get_context();
307 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
309 let (mut result, force_newline_brace) =
310 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
313 if self.config.brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace
314 || last_line_width(&result) + 2 > self.shape().width
316 newline_brace = true;
317 } else if !result.contains('\n') {
318 newline_brace = false;
321 // Prepare for the function body by possibly adding a newline and
323 // FIXME we'll miss anything between the end of the signature and the
324 // start of the body, but we need more spans from the compiler to solve
327 result.push_str(&indent.to_string_with_newline(self.config));
332 self.single_line_fn(&result, block).or_else(|| Some(result))
335 pub fn rewrite_required_fn(
339 sig: &ast::MethodSig,
340 generics: &ast::Generics,
342 ) -> Option<String> {
343 // Drop semicolon or it will be interpreted as comment.
344 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
345 let context = self.get_context();
347 let (mut result, _) = rewrite_fn_base(
351 &FnSig::from_method_sig(sig, generics),
357 // Re-attach semicolon
363 fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
364 if fn_str.contains('\n') {
368 let codemap = self.get_context().codemap;
370 if self.config.empty_item_single_line() && is_empty_block(block, codemap)
371 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
373 return Some(format!("{}{{}}", fn_str));
376 if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
378 if let Some(stmt) = block.stmts.first() {
379 match stmt_expr(stmt) {
381 let suffix = if semicolon_for_expr(&self.get_context(), e) {
387 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
389 .or_else(|| Some(self.snippet(e.span).to_owned()))
391 None => stmt.rewrite(&self.get_context(), self.shape()),
398 if let Some(res) = rewrite {
399 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
400 if !res.contains('\n') && width <= self.config.max_width() {
401 return Some(format!("{}{{ {} }}", fn_str, res));
409 pub fn visit_static(&mut self, static_parts: &StaticParts) {
410 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
411 self.push_rewrite(static_parts.span, rewrite);
414 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
415 let is_tuple = struct_parts.def.is_tuple();
416 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
417 .map(|s| if is_tuple { s + ";" } else { s });
418 self.push_rewrite(struct_parts.span, rewrite);
424 vis: &ast::Visibility,
425 enum_def: &ast::EnumDef,
426 generics: &ast::Generics,
429 let enum_header = format_header("enum ", ident, vis);
430 self.push_str(&enum_header);
432 let enum_snippet = self.snippet(span);
433 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
434 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
435 let generics_str = format_generics(
438 self.config.brace_style(),
439 if enum_def.variants.is_empty() {
440 BracePos::ForceSameLine
445 mk_sp(span.lo(), body_start),
446 last_line_width(&enum_header),
448 self.push_str(&generics_str);
450 self.last_pos = body_start;
452 self.block_indent = self.block_indent.block_indent(self.config);
453 let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
455 Some(ref body_str) => self.push_str(body_str),
456 None => self.format_missing_no_indent(span.hi() - BytePos(1)),
458 self.block_indent = self.block_indent.block_unindent(self.config);
460 if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
461 let indent_str = self.block_indent.to_string(self.config);
462 self.push_str(&indent_str);
465 self.last_pos = span.hi();
468 // Format the body of an enum definition
469 fn format_variant_list(
471 enum_def: &ast::EnumDef,
474 ) -> Option<String> {
475 if enum_def.variants.is_empty() {
478 let mut result = String::with_capacity(1024);
479 let indentation = self.block_indent.to_string_with_newline(self.config);
480 result.push_str(&indentation);
482 let itemize_list_with = |one_line_width: usize| {
484 self.snippet_provider,
485 enum_def.variants.iter(),
489 if !f.node.attrs.is_empty() {
490 f.node.attrs[0].span.lo()
496 |f| self.format_variant(f, one_line_width),
502 let mut items: Vec<_> =
503 itemize_list_with(self.config.width_heuristics().struct_variant_width);
504 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
505 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
506 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
507 if has_multiline_variant && has_single_line_variant {
508 items = itemize_list_with(0);
511 let shape = self.shape().sub_width(2)?;
512 let fmt = ListFormatting {
513 tactic: DefinitiveListTactic::Vertical,
515 trailing_separator: self.config.trailing_comma(),
516 separator_place: SeparatorPlace::Back,
518 ends_with_newline: true,
519 preserve_newline: true,
523 let list = write_list(&items, &fmt)?;
524 result.push_str(&list);
529 // Variant of an enum.
530 fn format_variant(&self, field: &ast::Variant, one_line_width: usize) -> Option<String> {
531 if contains_skip(&field.node.attrs) {
532 let lo = field.node.attrs[0].span.lo();
533 let span = mk_sp(lo, field.span.hi());
534 return Some(self.snippet(span).to_owned());
537 let context = self.get_context();
539 let shape = self.shape().sub_width(1)?;
540 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
545 .map_or(field.span.lo(), |attr| attr.span.hi());
546 let span = mk_sp(lo, field.span.lo());
548 let variant_body = match field.node.data {
549 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
551 &StructParts::from_variant(field),
553 Some(one_line_width),
555 ast::VariantData::Unit(..) => {
556 if let Some(ref expr) = field.node.disr_expr {
557 let lhs = format!("{} =", field.node.name);
558 rewrite_assign_rhs(&context, lhs, &**expr, shape)?
560 field.node.name.to_string()
565 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
570 context: &RewriteContext,
573 where_span_end: Option<BytePos>,
574 ) -> Option<String> {
575 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
576 let mut result = String::with_capacity(128);
577 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
578 let sep = offset.to_string_with_newline(context.config);
579 result.push_str(&ref_and_type);
581 let where_budget = if result.contains('\n') {
582 context.config.max_width()
584 context.budget(last_line_width(&result))
586 let option = WhereClauseOption::snuggled(&ref_and_type);
587 let where_clause_str = rewrite_where_clause(
589 &generics.where_clause,
590 context.config.brace_style(),
591 Shape::legacy(where_budget, offset.block_only()),
600 // If there is no where clause, we may have missing comments between the trait name and
601 // the opening brace.
602 if generics.where_clause.predicates.is_empty() {
603 if let Some(hi) = where_span_end {
604 match recover_missing_comment_in_span(
605 mk_sp(self_ty.span.hi(), hi),
606 Shape::indented(offset, context.config),
608 last_line_width(&result),
610 Some(ref missing_comment) if !missing_comment.is_empty() => {
611 result.push_str(missing_comment);
618 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
619 result.push_str(&where_clause_str);
620 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
621 result.push_str(&format!("{}{{{}}}", &sep, &sep));
623 result.push_str(" {}");
628 if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
629 let width = offset.block_indent + context.config.tab_spaces() - 1;
630 let where_indent = Indent::new(0, width);
631 result.push_str(&where_indent.to_string_with_newline(context.config));
633 result.push_str(&where_clause_str);
635 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
636 match context.config.brace_style() {
637 _ if need_newline => result.push_str(&sep),
638 BraceStyle::AlwaysNextLine => result.push_str(&sep),
639 BraceStyle::PreferSameLine => result.push(' '),
640 BraceStyle::SameLineWhere => {
641 if !where_clause_str.is_empty() {
642 result.push_str(&sep);
651 let snippet = context.snippet(item.span);
652 let open_pos = snippet.find_uncommented("{")? + 1;
654 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
655 let mut visitor = FmtVisitor::from_context(context);
656 visitor.block_indent = offset.block_only().block_indent(context.config);
657 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
659 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
661 visitor.visit_impl_item(item);
664 visitor.format_missing(item.span.hi() - BytePos(1));
666 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
667 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
669 result.push_str(&inner_indent_str);
670 result.push_str(visitor.buffer.to_string().trim());
671 result.push_str(&outer_indent_str);
674 if result.ends_with('{') {
675 result.push_str(&sep);
685 fn is_impl_single_line(
686 context: &RewriteContext,
687 items: &[ast::ImplItem],
689 where_clause_str: &str,
692 let snippet = context.snippet(item.span);
693 let open_pos = snippet.find_uncommented("{")? + 1;
696 context.config.empty_item_single_line() && items.is_empty() && !result.contains('\n')
697 && result.len() + where_clause_str.len() <= context.config.max_width()
698 && !contains_comment(&snippet[open_pos..]),
702 fn format_impl_ref_and_type(
703 context: &RewriteContext,
706 ) -> Option<String> {
707 if let ast::ItemKind::Impl(
717 let mut result = String::with_capacity(128);
719 result.push_str(&format_visibility(&item.vis));
720 result.push_str(format_defaultness(defaultness));
721 result.push_str(format_unsafety(unsafety));
723 let lo = context.snippet_provider.span_after(item.span, "impl");
724 let hi = match *trait_ref {
725 Some(ref tr) => tr.path.span.lo(),
726 None => self_ty.span.lo(),
728 let shape = generics_shape_from_config(
730 Shape::indented(offset + last_line_width(&result), context.config),
733 let generics_str = rewrite_generics(context, "impl", generics, shape, mk_sp(lo, hi))?;
734 result.push_str(&generics_str);
736 let polarity_str = if polarity == ast::ImplPolarity::Negative {
742 if let Some(ref trait_ref) = *trait_ref {
743 let result_len = last_line_width(&result);
744 result.push_str(&rewrite_trait_ref(
753 // Try to put the self type in a single line.
755 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
756 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
757 // If there is no where clause adapt budget for type formatting to take space and curly
758 // brace into account.
759 match context.config.brace_style() {
760 BraceStyle::AlwaysNextLine => 0,
766 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
767 // 1 = space before the type.
768 let budget = context.budget(used_space + 1);
769 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
770 if !self_ty_str.contains('\n') {
771 if trait_ref.is_some() {
772 result.push_str(" for ");
776 result.push_str(&self_ty_str);
781 // Couldn't fit the self type on a single line, put it on a new line.
783 // Add indentation of one additional tab.
784 let new_line_offset = offset.block_indent(context.config);
785 result.push_str(&new_line_offset.to_string(context.config));
786 if trait_ref.is_some() {
787 result.push_str("for ");
789 let budget = context.budget(last_line_width(&result));
790 let type_offset = match context.config.indent_style() {
791 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
792 IndentStyle::Block => new_line_offset,
794 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
801 fn rewrite_trait_ref(
802 context: &RewriteContext,
803 trait_ref: &ast::TraitRef,
807 ) -> Option<String> {
808 // 1 = space between generics and trait_ref
809 let used_space = 1 + polarity_str.len() + result_len;
810 let shape = Shape::indented(offset + used_space, context.config);
811 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
812 if !trait_ref_str.contains('\n') {
813 return Some(format!(" {}{}", polarity_str, &trait_ref_str));
816 // We could not make enough space for trait_ref, so put it on new line.
817 let offset = offset.block_indent(context.config);
818 let shape = Shape::indented(offset, context.config);
819 let trait_ref_str = trait_ref.rewrite(context, shape)?;
822 &offset.to_string_with_newline(context.config),
828 pub struct StructParts<'a> {
831 vis: &'a ast::Visibility,
832 def: &'a ast::VariantData,
833 generics: Option<&'a ast::Generics>,
837 impl<'a> StructParts<'a> {
838 fn format_header(&self) -> String {
839 format_header(self.prefix, self.ident, self.vis)
842 fn from_variant(variant: &'a ast::Variant) -> Self {
845 ident: variant.node.name,
846 vis: &DEFAULT_VISIBILITY,
847 def: &variant.node.data,
853 pub fn from_item(item: &'a ast::Item) -> Self {
854 let (prefix, def, generics) = match item.node {
855 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
856 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
864 generics: Some(generics),
871 context: &RewriteContext,
872 struct_parts: &StructParts,
874 one_line_width: Option<usize>,
875 ) -> Option<String> {
876 match *struct_parts.def {
877 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
878 ast::VariantData::Tuple(ref fields, _) => {
879 format_tuple_struct(context, struct_parts, fields, offset)
881 ast::VariantData::Struct(ref fields, _) => {
882 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
887 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
888 if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
891 let mut result = String::with_capacity(128);
892 let header = format!(
894 format_visibility(&item.vis),
895 format_unsafety(unsafety),
898 result.push_str(&header);
900 let body_lo = context.snippet_provider.span_after(item.span, "{");
902 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
903 let generics_str = rewrite_generics(
905 &item.ident.to_string(),
908 mk_sp(item.span.lo(), body_lo),
910 result.push_str(&generics_str);
912 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
913 if !type_param_bounds.is_empty() {
914 let ident_hi = context
916 .span_after(item.span, &format!("{}", item.ident));
917 let bound_hi = type_param_bounds.last().unwrap().span().hi();
918 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
919 if contains_comment(snippet) {
923 if !type_param_bounds.is_empty() {
924 result = rewrite_assign_rhs_with(
927 &TraitTyParamBounds::new(type_param_bounds),
929 RhsTactics::ForceNextLine,
933 // Rewrite where clause.
934 if !generics.where_clause.predicates.is_empty() {
935 let where_density = if context.config.indent_style() == IndentStyle::Block {
941 let where_budget = context.budget(last_line_width(&result));
942 let pos_before_where = if type_param_bounds.is_empty() {
943 generics.where_clause.span.lo()
945 type_param_bounds[type_param_bounds.len() - 1].span().hi()
947 let option = WhereClauseOption::snuggled(&generics_str);
948 let where_clause_str = rewrite_where_clause(
950 &generics.where_clause,
951 context.config.brace_style(),
952 Shape::legacy(where_budget, offset.block_only()),
960 // If the where clause cannot fit on the same line,
961 // put the where clause on a new line
962 if !where_clause_str.contains('\n')
963 && last_line_width(&result) + where_clause_str.len() + offset.width()
964 > context.config.comment_width()
966 let width = offset.block_indent + context.config.tab_spaces() - 1;
967 let where_indent = Indent::new(0, width);
968 result.push_str(&where_indent.to_string_with_newline(context.config));
970 result.push_str(&where_clause_str);
972 let item_snippet = context.snippet(item.span);
973 if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
975 let comment_hi = body_lo - BytePos(1);
976 let comment_lo = item.span.lo() + BytePos(lo as u32);
977 if comment_lo < comment_hi {
978 match recover_missing_comment_in_span(
979 mk_sp(comment_lo, comment_hi),
980 Shape::indented(offset, context.config),
982 last_line_width(&result),
984 Some(ref missing_comment) if !missing_comment.is_empty() => {
985 result.push_str(missing_comment);
993 match context.config.brace_style() {
994 _ if last_line_contains_single_line_comment(&result)
995 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
997 result.push_str(&offset.to_string_with_newline(context.config));
999 BraceStyle::AlwaysNextLine => {
1000 result.push_str(&offset.to_string_with_newline(context.config));
1002 BraceStyle::PreferSameLine => result.push(' '),
1003 BraceStyle::SameLineWhere => {
1004 if result.contains('\n')
1005 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1007 result.push_str(&offset.to_string_with_newline(context.config));
1015 let snippet = context.snippet(item.span);
1016 let open_pos = snippet.find_uncommented("{")? + 1;
1018 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1019 let mut visitor = FmtVisitor::from_context(context);
1020 visitor.block_indent = offset.block_only().block_indent(context.config);
1021 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1023 for item in trait_items {
1024 visitor.visit_trait_item(item);
1027 visitor.format_missing(item.span.hi() - BytePos(1));
1029 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1030 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1032 result.push_str(&inner_indent_str);
1033 result.push_str(visitor.buffer.to_string().trim());
1034 result.push_str(&outer_indent_str);
1035 } else if result.contains('\n') {
1046 pub fn format_trait_alias(
1047 context: &RewriteContext,
1049 generics: &ast::Generics,
1050 ty_param_bounds: &ast::TyParamBounds,
1052 ) -> Option<String> {
1053 let alias = ident.name.as_str();
1054 // 6 = "trait ", 2 = " ="
1055 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1056 let generics_str = rewrite_generics(context, &alias, generics, g_shape, generics.span)?;
1057 let lhs = format!("trait {} =", generics_str);
1059 rewrite_assign_rhs(context, lhs, ty_param_bounds, shape.sub_width(1)?).map(|s| s + ";")
1062 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1063 let header_str = format_header(p.prefix, p.ident, p.vis);
1064 let generics_str = if let Some(generics) = p.generics {
1065 let hi = if generics.where_clause.predicates.is_empty() {
1068 generics.where_clause.span.hi()
1073 context.config.brace_style(),
1076 mk_sp(generics.span.lo(), hi),
1077 last_line_width(&header_str),
1082 Some(format!("{}{};", header_str, generics_str))
1085 pub fn format_struct_struct(
1086 context: &RewriteContext,
1087 struct_parts: &StructParts,
1088 fields: &[ast::StructField],
1090 one_line_width: Option<usize>,
1091 ) -> Option<String> {
1092 let mut result = String::with_capacity(1024);
1093 let span = struct_parts.span;
1095 let header_str = struct_parts.format_header();
1096 result.push_str(&header_str);
1098 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1099 let body_lo = context.snippet_provider.span_after(span, "{");
1101 let generics_str = match struct_parts.generics {
1102 Some(g) => format_generics(
1105 context.config.brace_style(),
1106 if fields.is_empty() {
1107 BracePos::ForceSameLine
1112 mk_sp(header_hi, body_lo),
1113 last_line_width(&result),
1116 // 3 = ` {}`, 2 = ` {`.
1117 let overhead = if fields.is_empty() { 3 } else { 2 };
1118 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1119 || context.config.max_width() < overhead + result.len()
1121 format!("\n{}{{", offset.block_only().to_string(context.config))
1128 let overhead = if fields.is_empty() { 1 } else { 0 };
1129 let total_width = result.len() + generics_str.len() + overhead;
1130 if !generics_str.is_empty() && !generics_str.contains('\n')
1131 && total_width > context.config.max_width()
1134 result.push_str(&offset.to_string(context.config));
1135 result.push_str(generics_str.trim_left());
1137 result.push_str(&generics_str);
1140 if fields.is_empty() {
1141 let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1142 if snippet.trim().is_empty() {
1144 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1146 result.push_str(snippet.trim_right());
1148 result.push_str(&offset.to_string(context.config));
1150 result.push_str(snippet);
1153 return Some(result);
1157 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1158 let one_line_budget =
1159 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1161 let items_str = rewrite_with_alignment(
1164 Shape::indented(offset, context.config).sub_width(1)?,
1165 mk_sp(body_lo, span.hi()),
1169 if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget
1170 && !last_line_contains_single_line_comment(&items_str)
1172 Some(format!("{} {} }}", result, items_str))
1178 .block_indent(context.config)
1179 .to_string(context.config),
1181 offset.to_string(context.config)
1186 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1188 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1189 _ => default_span.lo(),
1193 fn format_tuple_struct(
1194 context: &RewriteContext,
1195 struct_parts: &StructParts,
1196 fields: &[ast::StructField],
1198 ) -> Option<String> {
1199 let mut result = String::with_capacity(1024);
1200 let span = struct_parts.span;
1202 let header_str = struct_parts.format_header();
1203 result.push_str(&header_str);
1205 let body_lo = if fields.is_empty() {
1206 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1209 .span_after(mk_sp(lo, span.hi()), "(")
1213 let body_hi = if fields.is_empty() {
1216 .span_after(mk_sp(body_lo, span.hi()), ")")
1218 // This is a dirty hack to work around a missing `)` from the span of the last field.
1219 let last_arg_span = fields[fields.len() - 1].span;
1220 if context.snippet(last_arg_span).ends_with(')') {
1225 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1229 let where_clause_str = match struct_parts.generics {
1231 let budget = context.budget(last_line_width(&header_str));
1232 let shape = Shape::legacy(budget, offset);
1233 let g_span = mk_sp(span.lo(), body_lo);
1234 let generics_str = rewrite_generics(context, "", generics, shape, g_span)?;
1235 result.push_str(&generics_str);
1237 let where_budget = context.budget(last_line_width(&result));
1238 let option = WhereClauseOption::new(true, false);
1239 rewrite_where_clause(
1241 &generics.where_clause,
1242 context.config.brace_style(),
1243 Shape::legacy(where_budget, offset.block_only()),
1244 Density::Compressed,
1252 None => "".to_owned(),
1255 if fields.is_empty() {
1257 let used_width = last_line_used_width(&result, offset.width()) + 3;
1258 if used_width > context.config.max_width() {
1260 result.push_str(&offset
1261 .block_indent(context.config)
1262 .to_string(context.config))
1265 let snippet = context.snippet(mk_sp(
1269 .span_before(mk_sp(body_lo, span.hi()), ")"),
1271 if snippet.is_empty() {
1273 } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1274 result.push_str(snippet.trim_right());
1276 result.push_str(&offset.to_string(context.config));
1278 result.push_str(snippet);
1282 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1283 let fields = &fields.iter().collect::<Vec<_>>()[..];
1284 result = overflow::rewrite_with_parens(
1290 context.config.width_heuristics().fn_call_width,
1295 if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1296 && (result.contains('\n')
1297 || offset.block_indent + result.len() + where_clause_str.len() + 1
1298 > context.config.max_width())
1300 // We need to put the where clause on a new line, but we didn't
1301 // know that earlier, so the where clause will not be indented properly.
1304 .push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1305 .to_string(context.config));
1307 result.push_str(&where_clause_str);
1312 pub fn rewrite_type_alias(
1313 context: &RewriteContext,
1317 generics: &ast::Generics,
1318 vis: &ast::Visibility,
1320 ) -> Option<String> {
1321 let mut result = String::with_capacity(128);
1323 result.push_str(&format_visibility(vis));
1324 result.push_str("type ");
1327 let g_shape = Shape::indented(indent, context.config)
1328 .offset_left(result.len())?
1331 context.snippet_provider.span_after(span, "type"),
1334 let generics_str = rewrite_generics(context, &ident.to_string(), generics, g_shape, g_span)?;
1335 result.push_str(&generics_str);
1337 let where_budget = context.budget(last_line_width(&result));
1338 let option = WhereClauseOption::snuggled(&result);
1339 let where_clause_str = rewrite_where_clause(
1341 &generics.where_clause,
1342 context.config.brace_style(),
1343 Shape::legacy(where_budget, indent),
1351 result.push_str(&where_clause_str);
1352 if where_clause_str.is_empty() {
1353 result.push_str(" =");
1355 result.push_str(&format!(
1357 indent.to_string_with_newline(context.config)
1362 let ty_shape = Shape::indented(indent, context.config).sub_width(1)?;
1363 rewrite_assign_rhs(context, result, ty, ty_shape).map(|s| s + ";")
1366 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1368 if config.space_before_colon() { " " } else { "" },
1369 if config.space_after_colon() { " " } else { "" },
1373 pub fn rewrite_struct_field_prefix(
1374 context: &RewriteContext,
1375 field: &ast::StructField,
1376 ) -> Option<String> {
1377 let vis = format_visibility(&field.vis);
1378 let type_annotation_spacing = type_annotation_spacing(context.config);
1379 Some(match field.ident {
1380 Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1381 None => format!("{}", vis),
1385 impl Rewrite for ast::StructField {
1386 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1387 rewrite_struct_field(context, self, shape, 0)
1391 pub fn rewrite_struct_field(
1392 context: &RewriteContext,
1393 field: &ast::StructField,
1395 lhs_max_width: usize,
1396 ) -> Option<String> {
1397 if contains_skip(&field.attrs) {
1398 return Some(context.snippet(field.span()).to_owned());
1401 let type_annotation_spacing = type_annotation_spacing(context.config);
1402 let prefix = rewrite_struct_field_prefix(context, field)?;
1404 let attrs_str = field.attrs.rewrite(context, shape)?;
1405 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1406 let missing_span = if field.attrs.is_empty() {
1407 mk_sp(field.span.lo(), field.span.lo())
1409 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1411 let mut spacing = String::from(if field.ident.is_some() {
1412 type_annotation_spacing.1
1416 // Try to put everything on a single line.
1417 let attr_prefix = combine_strs_with_missing_comments(
1425 let overhead = last_line_width(&attr_prefix);
1426 let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1427 for _ in 0..lhs_offset {
1430 // In this extreme case we will be missing a space betweeen an attribute and a field.
1431 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1435 .offset_left(overhead + spacing.len())
1436 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1437 if let Some(ref ty) = orig_ty {
1438 if !ty.contains('\n') {
1439 return Some(attr_prefix + &spacing + ty);
1443 let is_prefix_empty = prefix.is_empty();
1444 // We must use multiline. We are going to put attributes and a field on different lines.
1445 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1446 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1447 let field_str = if is_prefix_empty {
1448 field_str.trim_left()
1452 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1455 pub struct StaticParts<'a> {
1457 vis: &'a ast::Visibility,
1460 mutability: ast::Mutability,
1461 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1462 defaultness: Option<ast::Defaultness>,
1466 impl<'a> StaticParts<'a> {
1467 pub fn from_item(item: &'a ast::Item) -> Self {
1468 let (prefix, ty, mutability, expr) = match item.node {
1469 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1470 ast::ItemKind::Const(ref ty, ref expr) => {
1471 ("const", ty, ast::Mutability::Immutable, expr)
1473 _ => unreachable!(),
1481 expr_opt: Some(expr),
1487 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1488 let (ty, expr_opt) = match ti.node {
1489 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1490 _ => unreachable!(),
1494 vis: &DEFAULT_VISIBILITY,
1497 mutability: ast::Mutability::Immutable,
1498 expr_opt: expr_opt.as_ref(),
1504 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1505 let (ty, expr) = match ii.node {
1506 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1507 _ => unreachable!(),
1514 mutability: ast::Mutability::Immutable,
1515 expr_opt: Some(expr),
1516 defaultness: Some(ii.defaultness),
1523 context: &RewriteContext,
1524 static_parts: &StaticParts,
1526 ) -> Option<String> {
1527 let colon = colon_spaces(
1528 context.config.space_before_colon(),
1529 context.config.space_after_colon(),
1531 let mut prefix = format!(
1533 format_visibility(static_parts.vis),
1534 static_parts.defaultness.map_or("", format_defaultness),
1535 static_parts.prefix,
1536 format_mutability(static_parts.mutability),
1542 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1543 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1544 Some(ty_str) => ty_str,
1546 if prefix.ends_with(' ') {
1549 let nested_indent = offset.block_indent(context.config);
1550 let nested_shape = Shape::indented(nested_indent, context.config);
1551 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1554 nested_indent.to_string_with_newline(context.config),
1560 if let Some(expr) = static_parts.expr_opt {
1561 let lhs = format!("{}{} =", prefix, ty_str);
1563 let remaining_width = context.budget(offset.block_indent + 1);
1568 Shape::legacy(remaining_width, offset.block_only()),
1569 ).and_then(|res| recover_comment_removed(res, static_parts.span, context))
1570 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1572 Some(format!("{}{};", prefix, ty_str))
1576 pub fn rewrite_associated_type(
1578 ty_opt: Option<&ptr::P<ast::Ty>>,
1579 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1580 context: &RewriteContext,
1582 ) -> Option<String> {
1583 let prefix = format!("type {}", ident);
1585 let type_bounds_str = if let Some(bounds) = ty_param_bounds_opt {
1586 if bounds.is_empty() {
1590 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1591 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1597 if let Some(ty) = ty_opt {
1599 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1600 let lhs = format!("{}{} =", prefix, type_bounds_str);
1601 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1603 Some(format!("{}{};", prefix, type_bounds_str))
1607 pub fn rewrite_associated_impl_type(
1609 defaultness: ast::Defaultness,
1610 ty_opt: Option<&ptr::P<ast::Ty>>,
1611 ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1612 context: &RewriteContext,
1614 ) -> Option<String> {
1615 let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1618 ast::Defaultness::Default => Some(format!("default {}", result)),
1623 impl Rewrite for ast::FunctionRetTy {
1624 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1626 ast::FunctionRetTy::Default(_) => Some(String::new()),
1627 ast::FunctionRetTy::Ty(ref ty) => {
1628 let inner_width = shape.width.checked_sub(3)?;
1629 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1630 .map(|r| format!("-> {}", r))
1636 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1638 ast::TyKind::Infer => {
1639 let original = context.snippet(ty.span);
1646 impl Rewrite for ast::Arg {
1647 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1648 if is_named_arg(self) {
1649 let mut result = self.pat
1650 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1652 if !is_empty_infer(context, &*self.ty) {
1653 if context.config.space_before_colon() {
1654 result.push_str(" ");
1656 result.push_str(":");
1657 if context.config.space_after_colon() {
1658 result.push_str(" ");
1660 let overhead = last_line_width(&result);
1661 let max_width = shape.width.checked_sub(overhead)?;
1662 let ty_str = self.ty
1663 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1664 result.push_str(&ty_str);
1669 self.ty.rewrite(context, shape)
1674 fn rewrite_explicit_self(
1675 explicit_self: &ast::ExplicitSelf,
1677 context: &RewriteContext,
1678 ) -> Option<String> {
1679 match explicit_self.node {
1680 ast::SelfKind::Region(lt, m) => {
1681 let mut_str = format_mutability(m);
1684 let lifetime_str = l.rewrite(
1686 Shape::legacy(context.config.max_width(), Indent::empty()),
1688 Some(format!("&{} {}self", lifetime_str, mut_str))
1690 None => Some(format!("&{}self", mut_str)),
1693 ast::SelfKind::Explicit(ref ty, _) => {
1694 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1696 let mutability = explicit_self_mutability(&args[0]);
1697 let type_str = ty.rewrite(
1699 Shape::legacy(context.config.max_width(), Indent::empty()),
1704 format_mutability(mutability),
1708 ast::SelfKind::Value(_) => {
1709 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1711 let mutability = explicit_self_mutability(&args[0]);
1713 Some(format!("{}self", format_mutability(mutability)))
1718 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1719 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1720 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1721 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1728 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1729 if is_named_arg(arg) {
1736 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1738 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1739 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1740 _ => arg.ty.span.hi(),
1744 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1745 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1746 ident.node != symbol::keywords::Invalid.ident()
1752 // Return type is (result, force_new_line_for_brace)
1754 context: &RewriteContext,
1759 newline_brace: bool,
1761 ) -> Option<(String, bool)> {
1762 let mut force_new_line_for_brace = false;
1764 let where_clause = &fn_sig.generics.where_clause;
1766 let mut result = String::with_capacity(1024);
1767 result.push_str(&fn_sig.to_str(context));
1770 result.push_str("fn ");
1773 let overhead = if has_body && !newline_brace {
1780 let used_width = last_line_used_width(&result, indent.width());
1781 let one_line_budget = context.budget(used_width + overhead);
1783 width: one_line_budget,
1787 let fd = fn_sig.decl;
1788 let g_span = mk_sp(span.lo(), fd.output.span().lo());
1790 rewrite_generics(context, &ident.to_string(), fn_sig.generics, shape, g_span)?;
1791 result.push_str(&generics_str);
1793 let snuggle_angle_bracket = generics_str
1796 .map_or(false, |l| l.trim_left().len() == 1);
1798 // Note that the width and indent don't really matter, we'll re-layout the
1799 // return type later anyway.
1800 let ret_str = fd.output
1801 .rewrite(context, Shape::indented(indent, context.config))?;
1803 let multi_line_ret_str = ret_str.contains('\n');
1804 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1807 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1818 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1819 one_line_budget, multi_line_budget, arg_indent
1822 // Check if vertical layout was forced.
1823 if one_line_budget == 0 {
1824 if snuggle_angle_bracket {
1827 result.push_str("(");
1828 if context.config.indent_style() == IndentStyle::Visual {
1829 result.push_str(&arg_indent.to_string_with_newline(context.config));
1835 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty()
1836 && result.ends_with('(')
1841 // Skip `pub(crate)`.
1842 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
1843 // A conservative estimation, to goal is to be over all parens in generics
1844 let args_start = fn_sig
1849 .map_or(lo_after_visibility, |param| param.span().hi());
1850 let args_end = if fd.inputs.is_empty() {
1853 .span_after(mk_sp(args_start, span.hi()), ")")
1855 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1856 context.snippet_provider.span_after(last_span, ")")
1858 let args_span = mk_sp(
1861 .span_after(mk_sp(args_start, span.hi()), "("),
1864 let arg_str = rewrite_args(
1867 fd.get_self().as_ref(),
1874 generics_str.contains('\n'),
1877 let put_args_in_block = match context.config.indent_style() {
1878 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1880 } && !fd.inputs.is_empty();
1882 let mut args_last_line_contains_comment = false;
1883 if put_args_in_block {
1884 arg_indent = indent.block_indent(context.config);
1885 result.push_str(&arg_indent.to_string_with_newline(context.config));
1886 result.push_str(&arg_str);
1887 result.push_str(&indent.to_string_with_newline(context.config));
1890 result.push_str(&arg_str);
1891 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1892 // Put the closing brace on the next line if it overflows the max width.
1894 if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1897 if context.config.spaces_within_parens_and_brackets() && !fd.inputs.is_empty() {
1900 // If the last line of args contains comment, we cannot put the closing paren
1901 // on the same line.
1905 .map_or(false, |last_line| last_line.contains("//"))
1907 args_last_line_contains_comment = true;
1908 result.push_str(&arg_indent.to_string_with_newline(context.config));
1914 if let ast::FunctionRetTy::Ty(..) = fd.output {
1915 let ret_should_indent = match context.config.indent_style() {
1916 // If our args are block layout then we surely must have space.
1917 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1918 _ if args_last_line_contains_comment => false,
1919 _ if result.contains('\n') || multi_line_ret_str => true,
1921 // If the return type would push over the max width, then put the return type on
1922 // a new line. With the +1 for the signature length an additional space between
1923 // the closing parenthesis of the argument and the arrow '->' is considered.
1924 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1926 // If there is no where clause, take into account the space after the return type
1928 if where_clause.predicates.is_empty() {
1932 sig_length > context.config.max_width()
1935 let ret_indent = if ret_should_indent {
1936 let indent = if arg_str.is_empty() {
1937 // Aligning with non-existent args looks silly.
1938 force_new_line_for_brace = true;
1941 // FIXME: we might want to check that using the arg indent
1942 // doesn't blow our budget, and if it does, then fallback to
1943 // the where clause indent.
1947 result.push_str(&indent.to_string_with_newline(context.config));
1951 Indent::new(indent.block_indent, last_line_width(&result))
1954 if multi_line_ret_str || ret_should_indent {
1955 // Now that we know the proper indent and width, we need to
1956 // re-layout the return type.
1957 let ret_str = fd.output
1958 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1959 result.push_str(&ret_str);
1961 result.push_str(&ret_str);
1964 // Comment between return type and the end of the decl.
1965 let snippet_lo = fd.output.span().hi();
1966 if where_clause.predicates.is_empty() {
1967 let snippet_hi = span.hi();
1968 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1969 // Try to preserve the layout of the original snippet.
1970 let original_starts_with_newline = snippet
1972 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1973 let original_ends_with_newline = snippet
1974 .rfind(|c| c != ' ')
1975 .map_or(false, |i| snippet[i..].ends_with('\n'));
1976 let snippet = snippet.trim();
1977 if !snippet.is_empty() {
1978 result.push(if original_starts_with_newline {
1983 result.push_str(snippet);
1984 if original_ends_with_newline {
1985 force_new_line_for_brace = true;
1991 let pos_before_where = match fd.output {
1992 ast::FunctionRetTy::Default(..) => args_span.hi(),
1993 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1996 let is_args_multi_lined = arg_str.contains('\n');
1998 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1999 let where_clause_str = rewrite_where_clause(
2002 context.config.brace_style(),
2003 Shape::indented(indent, context.config),
2009 is_args_multi_lined,
2011 // If there are neither where clause nor return type, we may be missing comments between
2013 if where_clause_str.is_empty() {
2014 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2015 match recover_missing_comment_in_span(
2016 mk_sp(args_span.hi(), ret_span.hi()),
2019 last_line_width(&result),
2021 Some(ref missing_comment) if !missing_comment.is_empty() => {
2022 result.push_str(missing_comment);
2023 force_new_line_for_brace = true;
2030 result.push_str(&where_clause_str);
2032 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2033 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2034 Some((result, force_new_line_for_brace))
2037 #[derive(Copy, Clone)]
2038 struct WhereClauseOption {
2039 suppress_comma: bool, // Force no trailing comma
2040 snuggle: bool, // Do not insert newline before `where`
2041 compress_where: bool, // Try single line where clause instead of vertical layout
2044 impl WhereClauseOption {
2045 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2049 compress_where: false,
2053 pub fn snuggled(current: &str) -> WhereClauseOption {
2055 suppress_comma: false,
2056 snuggle: trimmed_last_line_width(current) == 1,
2057 compress_where: false,
2063 context: &RewriteContext,
2065 explicit_self: Option<&ast::ExplicitSelf>,
2066 one_line_budget: usize,
2067 multi_line_budget: usize,
2072 generics_str_contains_newline: bool,
2073 ) -> Option<String> {
2074 let mut arg_item_strs = args.iter()
2075 .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2076 .collect::<Option<Vec<_>>>()?;
2078 // Account for sugary self.
2079 // FIXME: the comment for the self argument is dropped. This is blocked
2080 // on rust issue #27522.
2081 let min_args = explicit_self
2082 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2083 .map_or(1, |self_str| {
2084 arg_item_strs[0] = self_str;
2088 // Comments between args.
2089 let mut arg_items = Vec::new();
2091 arg_items.push(ListItem::from_str(""));
2094 // FIXME(#21): if there are no args, there might still be a comment, but
2095 // without spans for the comment or parens, there is no chance of
2096 // getting it right. You also don't get to put a comment on self, unless
2098 if args.len() >= min_args || variadic {
2099 let comment_span_start = if min_args == 2 {
2100 let second_arg_start = if arg_has_pattern(&args[1]) {
2101 args[1].pat.span.lo()
2103 args[1].ty.span.lo()
2105 let reduced_span = mk_sp(span.lo(), second_arg_start);
2107 context.snippet_provider.span_after_last(reduced_span, ",")
2112 enum ArgumentKind<'a> {
2113 Regular(&'a ast::Arg),
2117 let variadic_arg = if variadic {
2118 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2119 let variadic_start =
2120 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2121 Some(ArgumentKind::Variadic(variadic_start))
2126 let more_items = itemize_list(
2127 context.snippet_provider,
2128 args[min_args - 1..]
2130 .map(ArgumentKind::Regular)
2131 .chain(variadic_arg),
2135 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2136 ArgumentKind::Variadic(start) => start,
2139 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2140 ArgumentKind::Variadic(start) => start + BytePos(3),
2143 ArgumentKind::Regular(..) => None,
2144 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2151 arg_items.extend(more_items);
2154 let fits_in_one_line = !generics_str_contains_newline
2155 && (arg_items.is_empty()
2156 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2158 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2159 item.item = Some(arg);
2162 let last_line_ends_with_comment = arg_items
2165 .and_then(|item| item.post_comment.as_ref())
2166 .map_or(false, |s| s.trim().starts_with("//"));
2168 let (indent, trailing_comma) = match context.config.indent_style() {
2169 IndentStyle::Block if fits_in_one_line => {
2170 (indent.block_indent(context.config), SeparatorTactic::Never)
2172 IndentStyle::Block => (
2173 indent.block_indent(context.config),
2174 context.config.trailing_comma(),
2176 IndentStyle::Visual if last_line_ends_with_comment => {
2177 (arg_indent, context.config.trailing_comma())
2179 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2182 let tactic = definitive_tactic(
2184 context.config.fn_args_density().to_list_tactic(),
2188 let budget = match tactic {
2189 DefinitiveListTactic::Horizontal => one_line_budget,
2190 _ => multi_line_budget,
2193 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2195 let fmt = ListFormatting {
2198 trailing_separator: if variadic {
2199 SeparatorTactic::Never
2203 separator_place: SeparatorPlace::Back,
2204 shape: Shape::legacy(budget, indent),
2205 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2206 preserve_newline: true,
2207 config: context.config,
2210 write_list(&arg_items, &fmt)
2213 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2214 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2215 ident.node != symbol::keywords::Invalid.ident()
2221 fn compute_budgets_for_args(
2222 context: &RewriteContext,
2226 newline_brace: bool,
2228 force_vertical_layout: bool,
2229 ) -> Option<((usize, usize, Indent))> {
2231 "compute_budgets_for_args {} {:?}, {}, {}",
2237 // Try keeping everything on the same line.
2238 if !result.contains('\n') && !force_vertical_layout {
2239 // 2 = `()`, 3 = `() `, space is before ret_string.
2240 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2241 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2251 let one_line_budget = context.budget(used_space);
2253 if one_line_budget > 0 {
2255 let (indent, multi_line_budget) = match context.config.indent_style() {
2256 IndentStyle::Block => {
2257 let indent = indent.block_indent(context.config);
2258 (indent, context.budget(indent.width() + 1))
2260 IndentStyle::Visual => {
2261 let indent = indent + result.len() + 1;
2262 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2263 (indent, context.budget(multi_line_overhead))
2267 return Some((one_line_budget, multi_line_budget, indent));
2271 // Didn't work. we must force vertical layout and put args on a newline.
2272 let new_indent = indent.block_indent(context.config);
2273 let used_space = match context.config.indent_style() {
2275 IndentStyle::Block => new_indent.width() + 1,
2276 // Account for `)` and possibly ` {`.
2277 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2279 Some((0, context.budget(used_space), new_indent))
2282 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2283 let predicate_count = where_clause.predicates.len();
2285 if config.where_single_line() && predicate_count == 1 {
2288 let brace_style = config.brace_style();
2290 brace_style == BraceStyle::AlwaysNextLine
2291 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2294 fn rewrite_generics(
2295 context: &RewriteContext,
2297 generics: &ast::Generics,
2300 ) -> Option<String> {
2301 // FIXME: convert bounds to where clauses where they get too big or if
2302 // there is a where clause at all.
2304 if generics.params.is_empty() {
2305 return Some(ident.to_owned());
2308 let params = &generics.params.iter().map(|e| &*e).collect::<Vec<_>>()[..];
2309 overflow::rewrite_with_angle_brackets(context, ident, params, shape, span)
2312 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2313 match config.indent_style() {
2314 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2315 IndentStyle::Block => {
2319 .block_indent(config.tab_spaces())
2320 .with_max_width(config)
2326 fn rewrite_where_clause_rfc_style(
2327 context: &RewriteContext,
2328 where_clause: &ast::WhereClause,
2331 span_end: Option<BytePos>,
2332 span_end_before_where: BytePos,
2333 where_clause_option: WhereClauseOption,
2334 is_args_multi_line: bool,
2335 ) -> Option<String> {
2336 let block_shape = shape.block().with_max_width(context.config);
2338 let (span_before, span_after) =
2339 missing_span_before_after_where(span_end_before_where, where_clause);
2340 let (comment_before, comment_after) =
2341 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2343 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2346 block_shape.indent.to_string_with_newline(context.config)
2349 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2351 let clause_shape = clause_shape.sub_width(1)?;
2352 // each clause on one line, trailing comma (except if suppress_comma)
2353 let span_start = where_clause.predicates[0].span().lo();
2354 // If we don't have the start of the next span, then use the end of the
2355 // predicates, but that means we miss comments.
2356 let len = where_clause.predicates.len();
2357 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2358 let span_end = span_end.unwrap_or(end_of_preds);
2359 let items = itemize_list(
2360 context.snippet_provider,
2361 where_clause.predicates.iter(),
2364 |pred| pred.span().lo(),
2365 |pred| pred.span().hi(),
2366 |pred| pred.rewrite(context, clause_shape),
2371 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2372 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2373 SeparatorTactic::Never
2375 context.config.trailing_comma()
2378 // shape should be vertical only and only if we have `where_single_line` option enabled
2379 // and the number of items of the where clause is equal to 1
2380 let shape_tactic = if where_single_line {
2381 DefinitiveListTactic::Horizontal
2383 DefinitiveListTactic::Vertical
2386 let fmt = ListFormatting {
2387 tactic: shape_tactic,
2389 trailing_separator: comma_tactic,
2390 separator_place: SeparatorPlace::Back,
2391 shape: clause_shape,
2392 ends_with_newline: true,
2393 preserve_newline: true,
2394 config: context.config,
2396 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2398 let comment_separator = |comment: &str, shape: Shape| {
2399 if comment.is_empty() {
2402 shape.indent.to_string_with_newline(context.config)
2405 let newline_before_where = comment_separator(&comment_before, shape);
2406 let newline_after_where = comment_separator(&comment_after, clause_shape);
2409 let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2410 && comment_after.is_empty() && !preds_str.contains('\n')
2411 && 6 + preds_str.len() <= shape.width || where_single_line
2415 clause_shape.indent.to_string_with_newline(context.config)
2418 "{}{}{}where{}{}{}{}",
2421 newline_before_where,
2422 newline_after_where,
2429 fn rewrite_where_clause(
2430 context: &RewriteContext,
2431 where_clause: &ast::WhereClause,
2432 brace_style: BraceStyle,
2436 span_end: Option<BytePos>,
2437 span_end_before_where: BytePos,
2438 where_clause_option: WhereClauseOption,
2439 is_args_multi_line: bool,
2440 ) -> Option<String> {
2441 if where_clause.predicates.is_empty() {
2442 return Some(String::new());
2445 if context.config.indent_style() == IndentStyle::Block {
2446 return rewrite_where_clause_rfc_style(
2452 span_end_before_where,
2453 where_clause_option,
2458 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2460 let offset = match context.config.indent_style() {
2461 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2462 // 6 = "where ".len()
2463 IndentStyle::Visual => shape.indent + extra_indent + 6,
2465 // FIXME: if indent_style != Visual, then the budgets below might
2466 // be out by a char or two.
2468 let budget = context.config.max_width() - offset.width();
2469 let span_start = where_clause.predicates[0].span().lo();
2470 // If we don't have the start of the next span, then use the end of the
2471 // predicates, but that means we miss comments.
2472 let len = where_clause.predicates.len();
2473 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2474 let span_end = span_end.unwrap_or(end_of_preds);
2475 let items = itemize_list(
2476 context.snippet_provider,
2477 where_clause.predicates.iter(),
2480 |pred| pred.span().lo(),
2481 |pred| pred.span().hi(),
2482 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2487 let item_vec = items.collect::<Vec<_>>();
2488 // FIXME: we don't need to collect here
2489 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2491 let mut comma_tactic = context.config.trailing_comma();
2492 // Kind of a hack because we don't usually have trailing commas in where clauses.
2493 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2494 comma_tactic = SeparatorTactic::Never;
2497 let fmt = ListFormatting {
2500 trailing_separator: comma_tactic,
2501 separator_place: SeparatorPlace::Back,
2502 shape: Shape::legacy(budget, offset),
2503 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
2504 preserve_newline: true,
2505 config: context.config,
2507 let preds_str = write_list(&item_vec, &fmt)?;
2509 let end_length = if terminator == "{" {
2510 // If the brace is on the next line we don't need to count it otherwise it needs two
2513 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2514 BraceStyle::PreferSameLine => 2,
2516 } else if terminator == "=" {
2521 if density == Density::Tall || preds_str.contains('\n')
2522 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2526 (shape.indent + extra_indent).to_string(context.config),
2530 Some(format!(" where {}", preds_str))
2534 fn missing_span_before_after_where(
2535 before_item_span_end: BytePos,
2536 where_clause: &ast::WhereClause,
2538 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2540 let pos_after_where = where_clause.span.lo() + BytePos(5);
2541 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2542 (missing_span_before, missing_span_after)
2545 fn rewrite_comments_before_after_where(
2546 context: &RewriteContext,
2547 span_before_where: Span,
2548 span_after_where: Span,
2550 ) -> Option<(String, String)> {
2551 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2552 let after_comment = rewrite_missing_comment(
2554 shape.block_indent(context.config.tab_spaces()),
2557 Some((before_comment, after_comment))
2560 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2561 format!("{}{}{}", format_visibility(vis), item_name, ident)
2564 #[derive(PartialEq, Eq, Clone, Copy)]
2572 context: &RewriteContext,
2573 generics: &ast::Generics,
2574 brace_style: BraceStyle,
2575 brace_pos: BracePos,
2579 ) -> Option<String> {
2580 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2581 let mut result = rewrite_generics(context, "", generics, shape, span)?;
2583 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2584 let budget = context.budget(last_line_used_width(&result, offset.width()));
2585 let mut option = WhereClauseOption::snuggled(&result);
2586 if brace_pos == BracePos::None {
2587 option.suppress_comma = true;
2589 // If the generics are not parameterized then generics.span.hi() == 0,
2590 // so we use span.lo(), which is the position after `struct Foo`.
2591 let span_end_before_where = if generics.is_parameterized() {
2596 let where_clause_str = rewrite_where_clause(
2598 &generics.where_clause,
2600 Shape::legacy(budget, offset.block_only()),
2604 span_end_before_where,
2608 result.push_str(&where_clause_str);
2609 brace_pos == BracePos::ForceSameLine || brace_style == BraceStyle::PreferSameLine
2610 || (generics.where_clause.predicates.is_empty()
2611 && trimmed_last_line_width(&result) == 1)
2613 brace_pos == BracePos::ForceSameLine || trimmed_last_line_width(&result) == 1
2614 || brace_style != BraceStyle::AlwaysNextLine
2616 if brace_pos == BracePos::None {
2617 return Some(result);
2619 let total_used_width = last_line_used_width(&result, used_width);
2620 let remaining_budget = context.budget(total_used_width);
2621 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2622 // and hence we take the closer into account as well for one line budget.
2623 // We assume that the closer has the same length as the opener.
2624 let overhead = if brace_pos == BracePos::ForceSameLine {
2631 let forbid_same_line_brace = overhead > remaining_budget;
2632 if !forbid_same_line_brace && same_line_brace {
2636 result.push_str(&offset.block_only().to_string(context.config));
2643 impl Rewrite for ast::ForeignItem {
2644 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2645 let attrs_str = self.attrs.rewrite(context, shape)?;
2646 // Drop semicolon or it will be interpreted as comment.
2647 // FIXME: this may be a faulty span from libsyntax.
2648 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2650 let item_str = match self.node {
2651 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => {
2656 &FnSig::new(fn_decl, generics, self.vis.clone()),
2660 ).map(|(s, _)| format!("{};", s))
2662 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2663 // FIXME(#21): we're dropping potential comments in between the
2664 // function keywords here.
2665 let vis = format_visibility(&self.vis);
2666 let mut_str = if is_mutable { "mut " } else { "" };
2667 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2669 let shape = shape.sub_width(1)?;
2670 ty.rewrite(context, shape).map(|ty_str| {
2671 // 1 = space between prefix and type.
2672 let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2675 let nested_indent = shape.indent.block_indent(context.config);
2676 nested_indent.to_string_with_newline(context.config)
2678 format!("{}{}{};", prefix, sep, ty_str)
2681 ast::ForeignItemKind::Ty => {
2682 let vis = format_visibility(&self.vis);
2683 Some(format!("{}type {};", vis, self.ident))
2687 let missing_span = if self.attrs.is_empty() {
2688 mk_sp(self.span.lo(), self.span.lo())
2690 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2692 combine_strs_with_missing_comments(
2703 impl Rewrite for ast::GenericParam {
2704 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2706 ast::GenericParam::Lifetime(ref lifetime_def) => lifetime_def.rewrite(context, shape),
2707 ast::GenericParam::Type(ref ty) => ty.rewrite(context, shape),
2712 /// Rewrite an inline mod.
2713 pub fn rewrite_mod(item: &ast::Item) -> String {
2714 let mut result = String::with_capacity(32);
2715 result.push_str(&*format_visibility(&item.vis));
2716 result.push_str("mod ");
2717 result.push_str(&item.ident.to_string());
2722 /// Rewrite `extern crate foo;` WITHOUT attributes.
2723 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2724 assert!(is_extern_crate(item));
2725 let new_str = context.snippet(item.span);
2726 Some(if contains_comment(new_str) {
2729 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2730 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2734 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2735 pub fn is_mod_decl(item: &ast::Item) -> bool {
2737 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2742 pub fn is_use_item(item: &ast::Item) -> bool {
2744 ast::ItemKind::Use(_) => true,
2749 pub fn is_extern_crate(item: &ast::Item) -> bool {
2751 ast::ItemKind::ExternCrate(..) => true,