1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
14 use std::cmp::{min, Ordering};
18 use rustc_target::spec::abi;
19 use syntax::source_map::{self, BytePos, Span};
21 use syntax::{ast, ptr, symbol};
24 combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
25 recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented,
27 use config::{BraceStyle, Config, Density, IndentStyle};
29 format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs, rewrite_assign_rhs_with,
32 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator};
33 use macros::{rewrite_macro, MacroPosition};
35 use rewrite::{Rewrite, RewriteContext};
36 use shape::{Indent, Shape};
37 use source_map::{LineRangeUtils, SpanUtils};
40 use vertical::rewrite_with_alignment;
41 use visitor::FmtVisitor;
43 const DEFAULT_VISIBILITY: ast::Visibility = source_map::Spanned {
44 node: ast::VisibilityKind::Inherited,
45 span: source_map::DUMMY_SP,
48 fn type_annotation_separator(config: &Config) -> &str {
49 colon_spaces(config.space_before_colon(), config.space_after_colon())
52 // Statements of the form
53 // let pat: ty = init;
54 impl Rewrite for ast::Local {
55 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
57 "Local::rewrite {:?} {} {:?}",
58 self, shape.width, shape.indent
61 skip_out_of_file_lines_range!(context, self.span);
63 if contains_skip(&self.attrs) {
67 let attrs_str = self.attrs.rewrite(context, shape)?;
68 let mut result = if attrs_str.is_empty() {
71 combine_strs_with_missing_comments(
76 self.attrs.last().map(|a| a.span.hi()).unwrap(),
85 let pat_shape = shape.offset_left(4)?;
87 let pat_shape = pat_shape.sub_width(1)?;
88 let pat_str = self.pat.rewrite(context, pat_shape)?;
89 result.push_str(&pat_str);
91 // String that is placed within the assignment pattern and expression.
93 let mut infix = String::with_capacity(32);
95 if let Some(ref ty) = self.ty {
96 let separator = type_annotation_separator(context.config);
97 let indent = shape.indent + last_line_width(&result) + separator.len();
99 let budget = shape.width.checked_sub(indent.width() + 1)?;
100 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
102 infix.push_str(separator);
103 infix.push_str(&rewrite);
106 if self.init.is_some() {
107 infix.push_str(" =");
113 result.push_str(&infix);
115 if let Some(ref ex) = self.init {
116 // 1 = trailing semicolon;
117 let nested_shape = shape.sub_width(1)?;
119 result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
127 // FIXME convert to using rewrite style rather than visitor
128 // FIXME format modules in this style
131 keyword: &'static str,
132 abi: Cow<'static, str>,
133 vis: Option<&'a ast::Visibility>,
134 body: Vec<BodyElement<'a>>,
139 fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
142 abi: format_abi(fm.abi, config.force_explicit_abi(), true),
147 .map(|i| BodyElement::ForeignItem(i))
154 enum BodyElement<'a> {
155 // Stmt(&'a ast::Stmt),
156 // Field(&'a ast::Field),
157 // Variant(&'a ast::Variant),
158 // Item(&'a ast::Item),
159 ForeignItem(&'a ast::ForeignItem),
162 /// Represents a fn's signature.
163 pub struct FnSig<'a> {
164 decl: &'a ast::FnDecl,
165 generics: &'a ast::Generics,
167 is_async: ast::IsAsync,
168 constness: ast::Constness,
169 defaultness: ast::Defaultness,
170 unsafety: ast::Unsafety,
171 visibility: ast::Visibility,
176 decl: &'a ast::FnDecl,
177 generics: &'a ast::Generics,
178 vis: ast::Visibility,
184 is_async: ast::IsAsync::NotAsync,
185 constness: ast::Constness::NotConst,
186 defaultness: ast::Defaultness::Final,
187 unsafety: ast::Unsafety::Normal,
192 pub fn from_method_sig(
193 method_sig: &'a ast::MethodSig,
194 generics: &'a ast::Generics,
197 unsafety: method_sig.header.unsafety,
198 is_async: method_sig.header.asyncness,
199 constness: method_sig.header.constness.node,
200 defaultness: ast::Defaultness::Final,
201 abi: method_sig.header.abi,
202 decl: &*method_sig.decl,
204 visibility: DEFAULT_VISIBILITY,
209 fn_kind: &'a visit::FnKind,
210 generics: &'a ast::Generics,
211 decl: &'a ast::FnDecl,
212 defaultness: ast::Defaultness,
215 visit::FnKind::ItemFn(_, fn_header, visibility, _) => FnSig {
219 constness: fn_header.constness.node,
220 is_async: fn_header.asyncness,
222 unsafety: fn_header.unsafety,
223 visibility: visibility.clone(),
225 visit::FnKind::Method(_, method_sig, vis, _) => {
226 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
227 fn_sig.defaultness = defaultness;
228 if let Some(vis) = vis {
229 fn_sig.visibility = vis.clone();
237 fn to_str(&self, context: &RewriteContext) -> String {
238 let mut result = String::with_capacity(128);
239 // Vis defaultness constness unsafety abi.
240 result.push_str(&*format_visibility(context, &self.visibility));
241 result.push_str(format_defaultness(self.defaultness));
242 result.push_str(format_constness(self.constness));
243 result.push_str(format_unsafety(self.unsafety));
244 result.push_str(format_async(self.is_async));
245 result.push_str(&format_abi(
247 context.config.force_explicit_abi(),
254 impl<'a> FmtVisitor<'a> {
255 fn format_item(&mut self, item: &Item) {
256 self.buffer.push_str(&item.abi);
258 let snippet = self.snippet(item.span);
259 let brace_pos = snippet.find_uncommented("{").unwrap();
262 if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
263 // FIXME: this skips comments between the extern keyword and the opening
265 self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
266 self.block_indent = self.block_indent.block_indent(self.config);
268 if item.body.is_empty() {
269 self.format_missing_no_indent(item.span.hi() - BytePos(1));
270 self.block_indent = self.block_indent.block_unindent(self.config);
271 let indent_str = self.block_indent.to_string(self.config);
272 self.push_str(&indent_str);
274 for item in &item.body {
275 self.format_body_element(item);
278 self.block_indent = self.block_indent.block_unindent(self.config);
279 self.format_missing_with_indent(item.span.hi() - BytePos(1));
284 self.last_pos = item.span.hi();
287 fn format_body_element(&mut self, element: &BodyElement) {
289 BodyElement::ForeignItem(item) => self.format_foreign_item(item),
293 pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
294 let item = Item::from_foreign_mod(fm, span, self.config);
295 self.format_item(&item);
298 fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
299 let rewrite = item.rewrite(&self.get_context(), self.shape());
300 self.push_rewrite(item.span(), rewrite);
301 self.last_pos = item.span.hi();
311 inner_attrs: Option<&[ast::Attribute]>,
312 ) -> Option<String> {
313 let context = self.get_context();
315 let mut newline_brace = newline_for_brace(self.config, &fn_sig.generics.where_clause);
317 let (mut result, force_newline_brace) =
318 rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
321 if self.config.brace_style() == BraceStyle::AlwaysNextLine
322 || force_newline_brace
323 || last_line_width(&result) + 2 > self.shape().width
325 newline_brace = true;
326 } else if !result.contains('\n') {
327 newline_brace = false;
330 // Prepare for the function body by possibly adding a newline and
332 // FIXME we'll miss anything between the end of the signature and the
333 // start of the body, but we need more spans from the compiler to solve
336 result.push_str(&indent.to_string_with_newline(self.config));
341 self.single_line_fn(&result, block, inner_attrs)
342 .or_else(|| Some(result))
345 pub fn rewrite_required_fn(
349 sig: &ast::MethodSig,
350 generics: &ast::Generics,
352 ) -> Option<String> {
353 // Drop semicolon or it will be interpreted as comment.
354 let span = mk_sp(span.lo(), span.hi() - BytePos(1));
355 let context = self.get_context();
357 let (mut result, _) = rewrite_fn_base(
361 &FnSig::from_method_sig(sig, generics),
367 // Re-attach semicolon
377 inner_attrs: Option<&[ast::Attribute]>,
378 ) -> Option<String> {
379 if fn_str.contains('\n') || inner_attrs.map_or(false, |a| !a.is_empty()) {
383 let source_map = self.get_context().source_map;
385 if self.config.empty_item_single_line()
386 && is_empty_block(block, None, source_map)
387 && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
389 return Some(format!("{}{{}}", fn_str));
392 if self.config.fn_single_line() && is_simple_block_stmt(block, None, source_map) {
394 if let Some(stmt) = block.stmts.first() {
395 match stmt_expr(stmt) {
397 let suffix = if semicolon_for_expr(&self.get_context(), e) {
403 format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
405 .or_else(|| Some(self.snippet(e.span).to_owned()))
407 None => stmt.rewrite(&self.get_context(), self.shape()),
414 if let Some(res) = rewrite {
415 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
416 if !res.contains('\n') && width <= self.config.max_width() {
417 return Some(format!("{}{{ {} }}", fn_str, res));
425 pub fn visit_static(&mut self, static_parts: &StaticParts) {
426 let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent);
427 self.push_rewrite(static_parts.span, rewrite);
430 pub fn visit_struct(&mut self, struct_parts: &StructParts) {
431 let is_tuple = struct_parts.def.is_tuple();
432 let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None)
433 .map(|s| if is_tuple { s + ";" } else { s });
434 self.push_rewrite(struct_parts.span, rewrite);
440 vis: &ast::Visibility,
441 enum_def: &ast::EnumDef,
442 generics: &ast::Generics,
445 let enum_header = format_header(&self.get_context(), "enum ", ident, vis);
446 self.push_str(&enum_header);
448 let enum_snippet = self.snippet(span);
449 let brace_pos = enum_snippet.find_uncommented("{").unwrap();
450 let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
451 let generics_str = format_generics(
454 self.config.brace_style(),
455 if enum_def.variants.is_empty() {
456 BracePos::ForceSameLine
461 mk_sp(span.lo(), body_start),
462 last_line_width(&enum_header),
465 self.push_str(&generics_str);
467 self.last_pos = body_start;
469 match self.format_variant_list(enum_def, body_start, span.hi()) {
470 Some(ref s) if enum_def.variants.is_empty() => self.push_str(s),
472 self.push_rewrite(mk_sp(body_start, span.hi()), rw);
473 self.block_indent = self.block_indent.block_unindent(self.config);
478 // Format the body of an enum definition
479 fn format_variant_list(
481 enum_def: &ast::EnumDef,
484 ) -> Option<String> {
485 if enum_def.variants.is_empty() {
486 let mut buffer = String::with_capacity(128);
488 let span = mk_sp(body_lo, body_hi - BytePos(1));
489 format_empty_struct_or_tuple(
499 let mut result = String::with_capacity(1024);
500 let original_offset = self.block_indent;
501 self.block_indent = self.block_indent.block_indent(self.config);
503 // If enum variants have discriminants, try to vertically align those,
504 // provided the discrims are not shifted too much to the right
505 let align_threshold: usize = self.config.enum_discrim_align_threshold();
506 let discr_ident_lens: Vec<usize> = enum_def
509 .filter(|var| var.node.disr_expr.is_some())
510 .map(|var| rewrite_ident(&self.get_context(), var.node.ident).len())
512 // cut the list at the point of longest discrim shorter than the threshold
513 // All of the discrims under the threshold will get padded, and all above - left as is.
514 let pad_discrim_ident_to = *discr_ident_lens
516 .filter(|&l| *l <= align_threshold)
520 let itemize_list_with = |one_line_width: usize| {
522 self.snippet_provider,
523 enum_def.variants.iter(),
527 if !f.node.attrs.is_empty() {
528 f.node.attrs[0].span.lo()
534 |f| self.format_variant(f, one_line_width, pad_discrim_ident_to),
541 let mut items: Vec<_> =
542 itemize_list_with(self.config.width_heuristics().struct_variant_width);
543 // If one of the variants use multiple lines, use multi-lined formatting for all variants.
544 let has_multiline_variant = items.iter().any(|item| item.inner_as_ref().contains('\n'));
545 let has_single_line_variant = items.iter().any(|item| !item.inner_as_ref().contains('\n'));
546 if has_multiline_variant && has_single_line_variant {
547 items = itemize_list_with(0);
550 let shape = self.shape().sub_width(2)?;
551 let fmt = ListFormatting::new(shape, self.config)
552 .trailing_separator(self.config.trailing_comma())
553 .preserve_newline(true);
555 let list = write_list(&items, &fmt)?;
556 result.push_str(&list);
557 result.push_str(&original_offset.to_string_with_newline(self.config));
562 // Variant of an enum.
565 field: &ast::Variant,
566 one_line_width: usize,
567 pad_discrim_ident_to: usize,
568 ) -> Option<String> {
569 if contains_skip(&field.node.attrs) {
570 let lo = field.node.attrs[0].span.lo();
571 let span = mk_sp(lo, field.span.hi());
572 return Some(self.snippet(span).to_owned());
575 let context = self.get_context();
577 let shape = self.shape().sub_width(1)?;
578 let attrs_str = field.node.attrs.rewrite(&context, shape)?;
583 .map_or(field.span.lo(), |attr| attr.span.hi());
584 let span = mk_sp(lo, field.span.lo());
586 let variant_body = match field.node.data {
587 ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => format_struct(
589 &StructParts::from_variant(field),
591 Some(one_line_width),
593 ast::VariantData::Unit(..) => {
594 if let Some(ref expr) = field.node.disr_expr {
597 rewrite_ident(&context, field.node.ident),
600 rewrite_assign_rhs(&context, lhs, &*expr.value, shape)?
602 rewrite_ident(&context, field.node.ident).to_owned()
607 combine_strs_with_missing_comments(&context, &attrs_str, &variant_body, span, shape, false)
610 fn visit_impl_items(&mut self, items: &[ast::ImplItem]) {
611 if self.get_context().config.reorder_impl_items() {
612 // Create visitor for each items, then reorder them.
613 let mut buffer = vec![];
615 self.visit_impl_item(item);
616 buffer.push((self.buffer.clone(), item.clone()));
619 // type -> existential -> const -> macro -> method
620 use ast::ImplItemKind::*;
621 fn need_empty_line(a: &ast::ImplItemKind, b: &ast::ImplItemKind) -> bool {
624 | (Const(..), Const(..))
625 | (Existential(..), Existential(..)) => false,
630 buffer.sort_by(|(_, a), (_, b)| match (&a.node, &b.node) {
632 | (Const(..), Const(..))
633 | (Macro(..), Macro(..))
634 | (Existential(..), Existential(..)) => a.ident.as_str().cmp(&b.ident.as_str()),
635 (Method(..), Method(..)) => a.span.lo().cmp(&b.span.lo()),
636 (Type(..), _) => Ordering::Less,
637 (_, Type(..)) => Ordering::Greater,
638 (Existential(..), _) => Ordering::Less,
639 (_, Existential(..)) => Ordering::Greater,
640 (Const(..), _) => Ordering::Less,
641 (_, Const(..)) => Ordering::Greater,
642 (Macro(..), _) => Ordering::Less,
643 (_, Macro(..)) => Ordering::Greater,
645 let mut prev_kind = None;
646 for (buf, item) in buffer {
647 // Make sure that there are at least a single empty line between
648 // different impl items.
651 .map_or(false, |prev_kind| need_empty_line(prev_kind, &item.node))
655 let indent_str = self.block_indent.to_string_with_newline(self.config);
656 self.push_str(&indent_str);
657 self.push_str(buf.trim());
658 prev_kind = Some(item.node.clone());
662 self.visit_impl_item(item);
669 context: &RewriteContext,
672 where_span_end: Option<BytePos>,
673 ) -> Option<String> {
674 if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
675 let mut result = String::with_capacity(128);
676 let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
677 let sep = offset.to_string_with_newline(context.config);
678 result.push_str(&ref_and_type);
680 let where_budget = if result.contains('\n') {
681 context.config.max_width()
683 context.budget(last_line_width(&result))
686 let mut option = WhereClauseOption::snuggled(&ref_and_type);
687 let snippet = context.snippet(item.span);
688 let open_pos = snippet.find_uncommented("{")? + 1;
689 if !contains_comment(&snippet[open_pos..])
691 && generics.where_clause.predicates.len() == 1
692 && !result.contains('\n')
694 option.suppress_comma();
696 option.compress_where();
699 let where_clause_str = rewrite_where_clause(
701 &generics.where_clause,
702 context.config.brace_style(),
703 Shape::legacy(where_budget, offset.block_only()),
712 // If there is no where clause, we may have missing comments between the trait name and
713 // the opening brace.
714 if generics.where_clause.predicates.is_empty() {
715 if let Some(hi) = where_span_end {
716 match recover_missing_comment_in_span(
717 mk_sp(self_ty.span.hi(), hi),
718 Shape::indented(offset, context.config),
720 last_line_width(&result),
722 Some(ref missing_comment) if !missing_comment.is_empty() => {
723 result.push_str(missing_comment);
730 if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
731 result.push_str(&where_clause_str);
732 if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
733 // if the where_clause contains extra comments AND
734 // there is only one where clause predicate
735 // recover the suppressed comma in single line where_clause formatting
736 if generics.where_clause.predicates.len() == 1 {
737 result.push_str(",");
739 result.push_str(&format!("{}{{{}}}", &sep, &sep));
741 result.push_str(" {}");
746 result.push_str(&where_clause_str);
748 let need_newline = last_line_contains_single_line_comment(&result) || result.contains('\n');
749 match context.config.brace_style() {
750 _ if need_newline => result.push_str(&sep),
751 BraceStyle::AlwaysNextLine => result.push_str(&sep),
752 BraceStyle::PreferSameLine => result.push(' '),
753 BraceStyle::SameLineWhere => {
754 if !where_clause_str.is_empty() {
755 result.push_str(&sep);
764 let snippet = context.snippet(item.span);
765 let open_pos = snippet.find_uncommented("{")? + 1;
767 if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
768 let mut visitor = FmtVisitor::from_context(context);
769 let item_indent = offset.block_only().block_indent(context.config);
770 visitor.block_indent = item_indent;
771 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
773 visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
774 visitor.visit_impl_items(items);
776 visitor.format_missing(item.span.hi() - BytePos(1));
778 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
779 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
781 result.push_str(&inner_indent_str);
782 result.push_str(visitor.buffer.to_string().trim());
783 result.push_str(&outer_indent_str);
784 } else if need_newline || !context.config.empty_item_single_line() {
785 result.push_str(&sep);
796 fn is_impl_single_line(
797 context: &RewriteContext,
798 items: &[ast::ImplItem],
800 where_clause_str: &str,
803 let snippet = context.snippet(item.span);
804 let open_pos = snippet.find_uncommented("{")? + 1;
807 context.config.empty_item_single_line()
809 && !result.contains('\n')
810 && result.len() + where_clause_str.len() <= context.config.max_width()
811 && !contains_comment(&snippet[open_pos..]),
815 fn format_impl_ref_and_type(
816 context: &RewriteContext,
819 ) -> Option<String> {
820 if let ast::ItemKind::Impl(
830 let mut result = String::with_capacity(128);
832 result.push_str(&format_visibility(context, &item.vis));
833 result.push_str(format_defaultness(defaultness));
834 result.push_str(format_unsafety(unsafety));
836 let shape = generics_shape_from_config(
838 Shape::indented(offset + last_line_width(&result), context.config),
841 let generics_str = rewrite_generics(context, "impl", generics, shape)?;
842 result.push_str(&generics_str);
844 let polarity_str = if polarity == ast::ImplPolarity::Negative {
850 if let Some(ref trait_ref) = *trait_ref {
851 let result_len = last_line_width(&result);
852 result.push_str(&rewrite_trait_ref(
861 // Try to put the self type in a single line.
863 let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
864 let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
865 // If there is no where clause adapt budget for type formatting to take space and curly
866 // brace into account.
867 match context.config.brace_style() {
868 BraceStyle::AlwaysNextLine => 0,
874 let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
875 // 1 = space before the type.
876 let budget = context.budget(used_space + 1);
877 if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
878 if !self_ty_str.contains('\n') {
879 if trait_ref.is_some() {
880 result.push_str(" for ");
884 result.push_str(&self_ty_str);
889 // Couldn't fit the self type on a single line, put it on a new line.
891 // Add indentation of one additional tab.
892 let new_line_offset = offset.block_indent(context.config);
893 result.push_str(&new_line_offset.to_string(context.config));
894 if trait_ref.is_some() {
895 result.push_str("for ");
897 let budget = context.budget(last_line_width(&result));
898 let type_offset = match context.config.indent_style() {
899 IndentStyle::Visual => new_line_offset + trait_ref_overhead,
900 IndentStyle::Block => new_line_offset,
902 result.push_str(&*self_ty.rewrite(context, Shape::legacy(budget, type_offset))?);
909 fn rewrite_trait_ref(
910 context: &RewriteContext,
911 trait_ref: &ast::TraitRef,
915 ) -> Option<String> {
916 // 1 = space between generics and trait_ref
917 let used_space = 1 + polarity_str.len() + result_len;
918 let shape = Shape::indented(offset + used_space, context.config);
919 if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
920 if !trait_ref_str.contains('\n') {
921 return Some(format!(" {}{}", polarity_str, &trait_ref_str));
924 // We could not make enough space for trait_ref, so put it on new line.
925 let offset = offset.block_indent(context.config);
926 let shape = Shape::indented(offset, context.config);
927 let trait_ref_str = trait_ref.rewrite(context, shape)?;
930 &offset.to_string_with_newline(context.config),
936 pub struct StructParts<'a> {
939 vis: &'a ast::Visibility,
940 def: &'a ast::VariantData,
941 generics: Option<&'a ast::Generics>,
945 impl<'a> StructParts<'a> {
946 fn format_header(&self, context: &RewriteContext) -> String {
947 format_header(context, self.prefix, self.ident, self.vis)
950 fn from_variant(variant: &'a ast::Variant) -> Self {
953 ident: variant.node.ident,
954 vis: &DEFAULT_VISIBILITY,
955 def: &variant.node.data,
961 pub fn from_item(item: &'a ast::Item) -> Self {
962 let (prefix, def, generics) = match item.node {
963 ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics),
964 ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics),
972 generics: Some(generics),
979 context: &RewriteContext,
980 struct_parts: &StructParts,
982 one_line_width: Option<usize>,
983 ) -> Option<String> {
984 match *struct_parts.def {
985 ast::VariantData::Unit(..) => format_unit_struct(context, struct_parts, offset),
986 ast::VariantData::Tuple(ref fields, _) => {
987 format_tuple_struct(context, struct_parts, fields, offset)
989 ast::VariantData::Struct(ref fields, _) => {
990 format_struct_struct(context, struct_parts, fields, offset, one_line_width)
995 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
996 if let ast::ItemKind::Trait(
1004 let mut result = String::with_capacity(128);
1005 let header = format!(
1007 format_visibility(context, &item.vis),
1008 format_unsafety(unsafety),
1009 format_auto(is_auto),
1011 result.push_str(&header);
1013 let body_lo = context.snippet_provider.span_after(item.span, "{");
1015 let shape = Shape::indented(offset, context.config).offset_left(result.len())?;
1017 rewrite_generics(context, rewrite_ident(context, item.ident), generics, shape)?;
1018 result.push_str(&generics_str);
1020 // FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
1021 if !generic_bounds.is_empty() {
1022 let ident_hi = context
1024 .span_after(item.span, &item.ident.as_str());
1025 let bound_hi = generic_bounds.last().unwrap().span().hi();
1026 let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
1027 if contains_comment(snippet) {
1031 result = rewrite_assign_rhs_with(
1036 RhsTactics::ForceNextLineWithoutIndent,
1040 // Rewrite where clause.
1041 if !generics.where_clause.predicates.is_empty() {
1042 let where_density = if context.config.indent_style() == IndentStyle::Block {
1048 let where_budget = context.budget(last_line_width(&result));
1049 let pos_before_where = if generic_bounds.is_empty() {
1050 generics.where_clause.span.lo()
1052 generic_bounds[generic_bounds.len() - 1].span().hi()
1054 let option = WhereClauseOption::snuggled(&generics_str);
1055 let where_clause_str = rewrite_where_clause(
1057 &generics.where_clause,
1058 context.config.brace_style(),
1059 Shape::legacy(where_budget, offset.block_only()),
1067 // If the where clause cannot fit on the same line,
1068 // put the where clause on a new line
1069 if !where_clause_str.contains('\n')
1070 && last_line_width(&result) + where_clause_str.len() + offset.width()
1071 > context.config.comment_width()
1073 let width = offset.block_indent + context.config.tab_spaces() - 1;
1074 let where_indent = Indent::new(0, width);
1075 result.push_str(&where_indent.to_string_with_newline(context.config));
1077 result.push_str(&where_clause_str);
1079 let item_snippet = context.snippet(item.span);
1080 if let Some(lo) = item_snippet.find('/') {
1082 let comment_hi = body_lo - BytePos(1);
1083 let comment_lo = item.span.lo() + BytePos(lo as u32);
1084 if comment_lo < comment_hi {
1085 match recover_missing_comment_in_span(
1086 mk_sp(comment_lo, comment_hi),
1087 Shape::indented(offset, context.config),
1089 last_line_width(&result),
1091 Some(ref missing_comment) if !missing_comment.is_empty() => {
1092 result.push_str(missing_comment);
1100 match context.config.brace_style() {
1101 _ if last_line_contains_single_line_comment(&result)
1102 || last_line_width(&result) + 2 > context.budget(offset.width()) =>
1104 result.push_str(&offset.to_string_with_newline(context.config));
1106 BraceStyle::AlwaysNextLine => {
1107 result.push_str(&offset.to_string_with_newline(context.config));
1109 BraceStyle::PreferSameLine => result.push(' '),
1110 BraceStyle::SameLineWhere => {
1111 if result.contains('\n')
1112 || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
1114 result.push_str(&offset.to_string_with_newline(context.config));
1122 let snippet = context.snippet(item.span);
1123 let open_pos = snippet.find_uncommented("{")? + 1;
1125 if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1126 let mut visitor = FmtVisitor::from_context(context);
1127 visitor.block_indent = offset.block_only().block_indent(context.config);
1128 visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1130 for item in trait_items {
1131 visitor.visit_trait_item(item);
1134 visitor.format_missing(item.span.hi() - BytePos(1));
1136 let inner_indent_str = visitor.block_indent.to_string_with_newline(context.config);
1137 let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
1139 result.push_str(&inner_indent_str);
1140 result.push_str(visitor.buffer.to_string().trim());
1141 result.push_str(&outer_indent_str);
1142 } else if result.contains('\n') {
1153 pub fn format_trait_alias(
1154 context: &RewriteContext,
1156 generics: &ast::Generics,
1157 generic_bounds: &ast::GenericBounds,
1159 ) -> Option<String> {
1160 let alias = rewrite_ident(context, ident);
1161 // 6 = "trait ", 2 = " ="
1162 let g_shape = shape.offset_left(6)?.sub_width(2)?;
1163 let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
1164 let lhs = format!("trait {} =", generics_str);
1166 rewrite_assign_rhs(context, lhs, generic_bounds, shape.sub_width(1)?).map(|s| s + ";")
1169 fn format_unit_struct(context: &RewriteContext, p: &StructParts, offset: Indent) -> Option<String> {
1170 let header_str = format_header(context, p.prefix, p.ident, p.vis);
1171 let generics_str = if let Some(generics) = p.generics {
1172 let hi = if generics.where_clause.predicates.is_empty() {
1175 generics.where_clause.span.hi()
1180 context.config.brace_style(),
1183 mk_sp(generics.span.lo(), hi),
1184 last_line_width(&header_str),
1189 Some(format!("{}{};", header_str, generics_str))
1192 pub fn format_struct_struct(
1193 context: &RewriteContext,
1194 struct_parts: &StructParts,
1195 fields: &[ast::StructField],
1197 one_line_width: Option<usize>,
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(context);
1203 result.push_str(&header_str);
1205 let header_hi = span.lo() + BytePos(header_str.len() as u32);
1206 let body_lo = context.snippet_provider.span_after(span, "{");
1208 let generics_str = match struct_parts.generics {
1209 Some(g) => format_generics(
1212 context.config.brace_style(),
1213 if fields.is_empty() {
1214 BracePos::ForceSameLine
1219 mk_sp(header_hi, body_lo),
1220 last_line_width(&result),
1223 // 3 = ` {}`, 2 = ` {`.
1224 let overhead = if fields.is_empty() { 3 } else { 2 };
1225 if (context.config.brace_style() == BraceStyle::AlwaysNextLine && !fields.is_empty())
1226 || context.config.max_width() < overhead + result.len()
1228 format!("\n{}{{", offset.block_only().to_string(context.config))
1235 let overhead = if fields.is_empty() { 1 } else { 0 };
1236 let total_width = result.len() + generics_str.len() + overhead;
1237 if !generics_str.is_empty()
1238 && !generics_str.contains('\n')
1239 && total_width > context.config.max_width()
1242 result.push_str(&offset.to_string(context.config));
1243 result.push_str(generics_str.trim_left());
1245 result.push_str(&generics_str);
1248 if fields.is_empty() {
1249 let inner_span = mk_sp(body_lo, span.hi() - BytePos(1));
1250 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "", "}");
1251 return Some(result);
1255 let one_line_budget = context.budget(result.len() + 3 + offset.width());
1256 let one_line_budget =
1257 one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1259 let items_str = rewrite_with_alignment(
1262 Shape::indented(offset, context.config).sub_width(1)?,
1263 mk_sp(body_lo, span.hi()),
1267 if !items_str.contains('\n')
1268 && !result.contains('\n')
1269 && items_str.len() <= one_line_budget
1270 && !last_line_contains_single_line_comment(&items_str)
1272 Some(format!("{} {} }}", result, items_str))
1278 .block_indent(context.config)
1279 .to_string(context.config),
1281 offset.to_string(context.config)
1286 fn get_bytepos_after_visibility(vis: &ast::Visibility, default_span: Span) -> BytePos {
1288 ast::VisibilityKind::Crate(..) | ast::VisibilityKind::Restricted { .. } => vis.span.hi(),
1289 _ => default_span.lo(),
1293 // Format tuple or struct without any fields. We need to make sure that the comments
1294 // inside the delimiters are preserved.
1295 fn format_empty_struct_or_tuple(
1296 context: &RewriteContext,
1299 result: &mut String,
1303 // 3 = " {}" or "();"
1304 let used_width = last_line_used_width(&result, offset.width()) + 3;
1305 if used_width > context.config.max_width() {
1306 result.push_str(&offset.to_string_with_newline(context.config))
1308 result.push_str(opener);
1309 match rewrite_missing_comment(span, Shape::indented(offset, context.config), context) {
1310 Some(ref s) if s.is_empty() => (),
1312 if !is_single_line(s) || first_line_contains_single_line_comment(s) {
1313 let nested_indent_str = offset
1314 .block_indent(context.config)
1315 .to_string_with_newline(context.config);
1316 result.push_str(&nested_indent_str);
1319 if last_line_contains_single_line_comment(s) {
1320 result.push_str(&offset.to_string_with_newline(context.config));
1323 None => result.push_str(context.snippet(span)),
1325 result.push_str(closer);
1328 fn format_tuple_struct(
1329 context: &RewriteContext,
1330 struct_parts: &StructParts,
1331 fields: &[ast::StructField],
1333 ) -> Option<String> {
1334 let mut result = String::with_capacity(1024);
1335 let span = struct_parts.span;
1337 let header_str = struct_parts.format_header(context);
1338 result.push_str(&header_str);
1340 let body_lo = if fields.is_empty() {
1341 let lo = get_bytepos_after_visibility(struct_parts.vis, span);
1344 .span_after(mk_sp(lo, span.hi()), "(")
1348 let body_hi = if fields.is_empty() {
1351 .span_after(mk_sp(body_lo, span.hi()), ")")
1353 // This is a dirty hack to work around a missing `)` from the span of the last field.
1354 let last_arg_span = fields[fields.len() - 1].span;
1357 .opt_span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1358 .unwrap_or(last_arg_span.hi())
1361 let where_clause_str = match struct_parts.generics {
1363 let budget = context.budget(last_line_width(&header_str));
1364 let shape = Shape::legacy(budget, offset);
1365 let generics_str = rewrite_generics(context, "", generics, shape)?;
1366 result.push_str(&generics_str);
1368 let where_budget = context.budget(last_line_width(&result));
1369 let option = WhereClauseOption::new(true, false);
1370 rewrite_where_clause(
1372 &generics.where_clause,
1373 context.config.brace_style(),
1374 Shape::legacy(where_budget, offset.block_only()),
1375 Density::Compressed,
1383 None => "".to_owned(),
1386 if fields.is_empty() {
1387 let body_hi = context
1389 .span_before(mk_sp(body_lo, span.hi()), ")");
1390 let inner_span = mk_sp(body_lo, body_hi);
1391 format_empty_struct_or_tuple(context, inner_span, offset, &mut result, "(", ")");
1393 let shape = Shape::indented(offset, context.config).sub_width(1)?;
1394 result = overflow::rewrite_with_parens(
1400 context.config.width_heuristics().fn_call_width,
1405 if !where_clause_str.is_empty()
1406 && !where_clause_str.contains('\n')
1407 && (result.contains('\n')
1408 || offset.block_indent + result.len() + where_clause_str.len() + 1
1409 > context.config.max_width())
1411 // We need to put the where clause on a new line, but we didn't
1412 // know that earlier, so the where clause will not be indented properly.
1415 &(offset.block_only() + (context.config.tab_spaces() - 1)).to_string(context.config),
1418 result.push_str(&where_clause_str);
1423 fn rewrite_type_prefix(
1424 context: &RewriteContext,
1428 generics: &ast::Generics,
1429 ) -> Option<String> {
1430 let mut result = String::with_capacity(128);
1431 result.push_str(prefix);
1432 let ident_str = rewrite_ident(context, ident);
1435 if generics.params.is_empty() {
1436 result.push_str(ident_str)
1438 let g_shape = Shape::indented(indent, context.config)
1439 .offset_left(result.len())?
1441 let generics_str = rewrite_generics(context, ident_str, generics, g_shape)?;
1442 result.push_str(&generics_str);
1445 let where_budget = context.budget(last_line_width(&result));
1446 let option = WhereClauseOption::snuggled(&result);
1447 let where_clause_str = rewrite_where_clause(
1449 &generics.where_clause,
1450 context.config.brace_style(),
1451 Shape::legacy(where_budget, indent),
1459 result.push_str(&where_clause_str);
1464 fn rewrite_type_item<R: Rewrite>(
1465 context: &RewriteContext,
1471 generics: &ast::Generics,
1472 vis: &ast::Visibility,
1473 ) -> Option<String> {
1474 let mut result = String::with_capacity(128);
1475 result.push_str(&rewrite_type_prefix(
1478 &format!("{}{} ", format_visibility(context, vis), prefix),
1483 if generics.where_clause.predicates.is_empty() {
1484 result.push_str(suffix);
1486 result.push_str(&indent.to_string_with_newline(context.config));
1487 result.push_str(suffix.trim_left());
1491 let rhs_shape = Shape::indented(indent, context.config).sub_width(1)?;
1492 rewrite_assign_rhs(context, result, rhs, rhs_shape).map(|s| s + ";")
1495 pub fn rewrite_type_alias(
1496 context: &RewriteContext,
1500 generics: &ast::Generics,
1501 vis: &ast::Visibility,
1502 ) -> Option<String> {
1503 rewrite_type_item(context, indent, "type", " =", ident, ty, generics, vis)
1506 pub fn rewrite_existential_type(
1507 context: &RewriteContext,
1510 generic_bounds: &ast::GenericBounds,
1511 generics: &ast::Generics,
1512 vis: &ast::Visibility,
1513 ) -> Option<String> {
1526 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1528 if config.space_before_colon() { " " } else { "" },
1529 if config.space_after_colon() { " " } else { "" },
1533 pub fn rewrite_struct_field_prefix(
1534 context: &RewriteContext,
1535 field: &ast::StructField,
1536 ) -> Option<String> {
1537 let vis = format_visibility(context, &field.vis);
1538 let type_annotation_spacing = type_annotation_spacing(context.config);
1539 Some(match field.ident {
1540 Some(name) => format!(
1543 rewrite_ident(context, name),
1544 type_annotation_spacing.0
1546 None => format!("{}", vis),
1550 impl Rewrite for ast::StructField {
1551 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1552 rewrite_struct_field(context, self, shape, 0)
1556 pub fn rewrite_struct_field(
1557 context: &RewriteContext,
1558 field: &ast::StructField,
1560 lhs_max_width: usize,
1561 ) -> Option<String> {
1562 if contains_skip(&field.attrs) {
1563 return Some(context.snippet(field.span()).to_owned());
1566 let type_annotation_spacing = type_annotation_spacing(context.config);
1567 let prefix = rewrite_struct_field_prefix(context, field)?;
1569 let attrs_str = field.attrs.rewrite(context, shape)?;
1570 let attrs_extendable = field.ident.is_none() && is_attributes_extendable(&attrs_str);
1571 let missing_span = if field.attrs.is_empty() {
1572 mk_sp(field.span.lo(), field.span.lo())
1574 mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1576 let mut spacing = String::from(if field.ident.is_some() {
1577 type_annotation_spacing.1
1581 // Try to put everything on a single line.
1582 let attr_prefix = combine_strs_with_missing_comments(
1590 let overhead = last_line_width(&attr_prefix);
1591 let lhs_offset = lhs_max_width.saturating_sub(overhead);
1592 for _ in 0..lhs_offset {
1595 // In this extreme case we will be missing a space betweeen an attribute and a field.
1596 if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1600 .offset_left(overhead + spacing.len())
1601 .and_then(|ty_shape| field.ty.rewrite(context, ty_shape));
1602 if let Some(ref ty) = orig_ty {
1603 if !ty.contains('\n') {
1604 return Some(attr_prefix + &spacing + ty);
1608 let is_prefix_empty = prefix.is_empty();
1609 // We must use multiline. We are going to put attributes and a field on different lines.
1610 let field_str = rewrite_assign_rhs(context, prefix, &*field.ty, shape)?;
1611 // Remove a leading white-space from `rewrite_assign_rhs()` when rewriting a tuple struct.
1612 let field_str = if is_prefix_empty {
1613 field_str.trim_left()
1617 combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false)
1620 pub struct StaticParts<'a> {
1622 vis: &'a ast::Visibility,
1625 mutability: ast::Mutability,
1626 expr_opt: Option<&'a ptr::P<ast::Expr>>,
1627 defaultness: Option<ast::Defaultness>,
1631 impl<'a> StaticParts<'a> {
1632 pub fn from_item(item: &'a ast::Item) -> Self {
1633 let (prefix, ty, mutability, expr) = match item.node {
1634 ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr),
1635 ast::ItemKind::Const(ref ty, ref expr) => {
1636 ("const", ty, ast::Mutability::Immutable, expr)
1638 _ => unreachable!(),
1646 expr_opt: Some(expr),
1652 pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self {
1653 let (ty, expr_opt) = match ti.node {
1654 ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt),
1655 _ => unreachable!(),
1659 vis: &DEFAULT_VISIBILITY,
1662 mutability: ast::Mutability::Immutable,
1663 expr_opt: expr_opt.as_ref(),
1669 pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self {
1670 let (ty, expr) = match ii.node {
1671 ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr),
1672 _ => unreachable!(),
1679 mutability: ast::Mutability::Immutable,
1680 expr_opt: Some(expr),
1681 defaultness: Some(ii.defaultness),
1688 context: &RewriteContext,
1689 static_parts: &StaticParts,
1691 ) -> Option<String> {
1692 let colon = colon_spaces(
1693 context.config.space_before_colon(),
1694 context.config.space_after_colon(),
1696 let mut prefix = format!(
1698 format_visibility(context, static_parts.vis),
1699 static_parts.defaultness.map_or("", format_defaultness),
1700 static_parts.prefix,
1701 format_mutability(static_parts.mutability),
1707 Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?;
1708 let ty_str = match static_parts.ty.rewrite(context, ty_shape) {
1709 Some(ty_str) => ty_str,
1711 if prefix.ends_with(' ') {
1714 let nested_indent = offset.block_indent(context.config);
1715 let nested_shape = Shape::indented(nested_indent, context.config);
1716 let ty_str = static_parts.ty.rewrite(context, nested_shape)?;
1719 nested_indent.to_string_with_newline(context.config),
1725 if let Some(expr) = static_parts.expr_opt {
1726 let lhs = format!("{}{} =", prefix, ty_str);
1728 let remaining_width = context.budget(offset.block_indent + 1);
1733 Shape::legacy(remaining_width, offset.block_only()),
1735 .and_then(|res| recover_comment_removed(res, static_parts.span, context))
1736 .map(|s| if s.ends_with(';') { s } else { s + ";" })
1738 Some(format!("{}{};", prefix, ty_str))
1742 pub fn rewrite_associated_type(
1744 ty_opt: Option<&ptr::P<ast::Ty>>,
1745 generics: &ast::Generics,
1746 generic_bounds_opt: Option<&ast::GenericBounds>,
1747 context: &RewriteContext,
1749 ) -> Option<String> {
1750 let ident_str = rewrite_ident(context, ident);
1752 let generics_shape = Shape::indented(indent, context.config).offset_left(5)?;
1753 let generics_str = rewrite_generics(context, ident_str, generics, generics_shape)?;
1754 let prefix = format!("type {}", generics_str);
1756 let type_bounds_str = if let Some(bounds) = generic_bounds_opt {
1757 if bounds.is_empty() {
1761 let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1762 bounds.rewrite(context, shape).map(|s| format!(": {}", s))?
1768 if let Some(ty) = ty_opt {
1770 let shape = Shape::indented(indent, context.config).sub_width(1)?;
1771 let lhs = format!("{}{} =", prefix, type_bounds_str);
1772 rewrite_assign_rhs(context, lhs, &**ty, shape).map(|s| s + ";")
1774 Some(format!("{}{};", prefix, type_bounds_str))
1778 pub fn rewrite_existential_impl_type(
1779 context: &RewriteContext,
1781 generics: &ast::Generics,
1782 generic_bounds: &ast::GenericBounds,
1784 ) -> Option<String> {
1785 rewrite_associated_type(ident, None, generics, Some(generic_bounds), context, indent)
1786 .map(|s| format!("existential {}", s))
1789 pub fn rewrite_associated_impl_type(
1791 defaultness: ast::Defaultness,
1792 ty_opt: Option<&ptr::P<ast::Ty>>,
1793 generics: &ast::Generics,
1794 context: &RewriteContext,
1796 ) -> Option<String> {
1797 let result = rewrite_associated_type(ident, ty_opt, generics, None, context, indent)?;
1800 ast::Defaultness::Default => Some(format!("default {}", result)),
1805 impl Rewrite for ast::FunctionRetTy {
1806 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1808 ast::FunctionRetTy::Default(_) => Some(String::new()),
1809 ast::FunctionRetTy::Ty(ref ty) => {
1810 let inner_width = shape.width.checked_sub(3)?;
1811 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1812 .map(|r| format!("-> {}", r))
1818 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1820 ast::TyKind::Infer => {
1821 let original = context.snippet(ty.span);
1828 impl Rewrite for ast::Arg {
1829 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1830 if is_named_arg(self) {
1831 let mut result = self
1833 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1835 if !is_empty_infer(context, &*self.ty) {
1836 if context.config.space_before_colon() {
1837 result.push_str(" ");
1839 result.push_str(":");
1840 if context.config.space_after_colon() {
1841 result.push_str(" ");
1843 let overhead = last_line_width(&result);
1844 let max_width = shape.width.checked_sub(overhead)?;
1847 .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1848 result.push_str(&ty_str);
1853 self.ty.rewrite(context, shape)
1858 fn rewrite_explicit_self(
1859 explicit_self: &ast::ExplicitSelf,
1861 context: &RewriteContext,
1862 ) -> Option<String> {
1863 match explicit_self.node {
1864 ast::SelfKind::Region(lt, m) => {
1865 let mut_str = format_mutability(m);
1868 let lifetime_str = l.rewrite(
1870 Shape::legacy(context.config.max_width(), Indent::empty()),
1872 Some(format!("&{} {}self", lifetime_str, mut_str))
1874 None => Some(format!("&{}self", mut_str)),
1877 ast::SelfKind::Explicit(ref ty, _) => {
1878 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1880 let mutability = explicit_self_mutability(&args[0]);
1881 let type_str = ty.rewrite(
1883 Shape::legacy(context.config.max_width(), Indent::empty()),
1888 format_mutability(mutability),
1892 ast::SelfKind::Value(_) => {
1893 assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1895 let mutability = explicit_self_mutability(&args[0]);
1897 Some(format!("{}self", format_mutability(mutability)))
1902 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1903 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1904 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1905 if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1912 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1913 if is_named_arg(arg) {
1920 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1922 ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1923 ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1924 _ => arg.ty.span.hi(),
1928 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1929 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1930 ident != symbol::keywords::Invalid.ident()
1936 // Return type is (result, force_new_line_for_brace)
1938 context: &RewriteContext,
1943 newline_brace: bool,
1945 ) -> Option<(String, bool)> {
1946 let mut force_new_line_for_brace = false;
1948 let where_clause = &fn_sig.generics.where_clause;
1950 let mut result = String::with_capacity(1024);
1951 result.push_str(&fn_sig.to_str(context));
1954 result.push_str("fn ");
1957 let overhead = if has_body && !newline_brace {
1964 let used_width = last_line_used_width(&result, indent.width());
1965 let one_line_budget = context.budget(used_width + overhead);
1967 width: one_line_budget,
1971 let fd = fn_sig.decl;
1972 let generics_str = rewrite_generics(
1974 rewrite_ident(context, ident),
1978 result.push_str(&generics_str);
1980 let snuggle_angle_bracket = generics_str
1983 .map_or(false, |l| l.trim_left().len() == 1);
1985 // Note that the width and indent don't really matter, we'll re-layout the
1986 // return type later anyway.
1989 .rewrite(context, Shape::indented(indent, context.config))?;
1991 let multi_line_ret_str = ret_str.contains('\n');
1992 let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1995 let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
2006 "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
2007 one_line_budget, multi_line_budget, arg_indent
2010 // Check if vertical layout was forced.
2011 if one_line_budget == 0 {
2012 if snuggle_angle_bracket {
2015 result.push_str("(");
2016 if context.config.indent_style() == IndentStyle::Visual {
2017 result.push_str(&arg_indent.to_string_with_newline(context.config));
2024 // Skip `pub(crate)`.
2025 let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
2026 // A conservative estimation, to goal is to be over all parens in generics
2027 let args_start = fn_sig
2032 .map_or(lo_after_visibility, |param| param.span().hi());
2033 let args_end = if fd.inputs.is_empty() {
2036 .span_after(mk_sp(args_start, span.hi()), ")")
2038 let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
2039 context.snippet_provider.span_after(last_span, ")")
2041 let args_span = mk_sp(
2044 .span_after(mk_sp(args_start, span.hi()), "("),
2047 let arg_str = rewrite_args(
2050 fd.get_self().as_ref(),
2057 generics_str.contains('\n'),
2060 let put_args_in_block = match context.config.indent_style() {
2061 IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
2063 } && !fd.inputs.is_empty();
2065 let mut args_last_line_contains_comment = false;
2066 if put_args_in_block {
2067 arg_indent = indent.block_indent(context.config);
2068 result.push_str(&arg_indent.to_string_with_newline(context.config));
2069 result.push_str(&arg_str);
2070 result.push_str(&indent.to_string_with_newline(context.config));
2073 result.push_str(&arg_str);
2074 let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
2075 // Put the closing brace on the next line if it overflows the max width.
2077 let closing_paren_overflow_max_width =
2078 fd.inputs.is_empty() && used_width + 1 > context.config.max_width();
2079 // If the last line of args contains comment, we cannot put the closing paren
2080 // on the same line.
2081 args_last_line_contains_comment = arg_str
2084 .map_or(false, |last_line| last_line.contains("//"));
2085 if closing_paren_overflow_max_width || args_last_line_contains_comment {
2086 result.push_str(&indent.to_string_with_newline(context.config));
2092 if let ast::FunctionRetTy::Ty(..) = fd.output {
2093 let ret_should_indent = match context.config.indent_style() {
2094 // If our args are block layout then we surely must have space.
2095 IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
2096 _ if args_last_line_contains_comment => false,
2097 _ if result.contains('\n') || multi_line_ret_str => true,
2099 // If the return type would push over the max width, then put the return type on
2100 // a new line. With the +1 for the signature length an additional space between
2101 // the closing parenthesis of the argument and the arrow '->' is considered.
2102 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
2104 // If there is no where clause, take into account the space after the return type
2106 if where_clause.predicates.is_empty() {
2110 sig_length > context.config.max_width()
2113 let ret_indent = if ret_should_indent {
2114 let indent = if arg_str.is_empty() {
2115 // Aligning with non-existent args looks silly.
2116 force_new_line_for_brace = true;
2119 // FIXME: we might want to check that using the arg indent
2120 // doesn't blow our budget, and if it does, then fallback to
2121 // the where clause indent.
2125 result.push_str(&indent.to_string_with_newline(context.config));
2129 Indent::new(indent.block_indent, last_line_width(&result))
2132 if multi_line_ret_str || ret_should_indent {
2133 // Now that we know the proper indent and width, we need to
2134 // re-layout the return type.
2137 .rewrite(context, Shape::indented(ret_indent, context.config))?;
2138 result.push_str(&ret_str);
2140 result.push_str(&ret_str);
2143 // Comment between return type and the end of the decl.
2144 let snippet_lo = fd.output.span().hi();
2145 if where_clause.predicates.is_empty() {
2146 let snippet_hi = span.hi();
2147 let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
2148 // Try to preserve the layout of the original snippet.
2149 let original_starts_with_newline = snippet
2151 .map_or(false, |i| starts_with_newline(&snippet[i..]));
2152 let original_ends_with_newline = snippet
2153 .rfind(|c| c != ' ')
2154 .map_or(false, |i| snippet[i..].ends_with('\n'));
2155 let snippet = snippet.trim();
2156 if !snippet.is_empty() {
2157 result.push(if original_starts_with_newline {
2162 result.push_str(snippet);
2163 if original_ends_with_newline {
2164 force_new_line_for_brace = true;
2170 let pos_before_where = match fd.output {
2171 ast::FunctionRetTy::Default(..) => args_span.hi(),
2172 ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
2175 let is_args_multi_lined = arg_str.contains('\n');
2177 let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
2178 let where_clause_str = rewrite_where_clause(
2181 context.config.brace_style(),
2182 Shape::indented(indent, context.config),
2188 is_args_multi_lined,
2190 // If there are neither where clause nor return type, we may be missing comments between
2192 if where_clause_str.is_empty() {
2193 if let ast::FunctionRetTy::Default(ret_span) = fd.output {
2194 match recover_missing_comment_in_span(
2195 mk_sp(args_span.hi(), ret_span.hi()),
2198 last_line_width(&result),
2200 Some(ref missing_comment) if !missing_comment.is_empty() => {
2201 result.push_str(missing_comment);
2202 force_new_line_for_brace = true;
2209 result.push_str(&where_clause_str);
2211 force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2212 force_new_line_for_brace |= is_args_multi_lined && context.config.where_single_line();
2213 Some((result, force_new_line_for_brace))
2216 #[derive(Copy, Clone)]
2217 struct WhereClauseOption {
2218 suppress_comma: bool, // Force no trailing comma
2219 snuggle: bool, // Do not insert newline before `where`
2220 compress_where: bool, // Try single line where clause instead of vertical layout
2223 impl WhereClauseOption {
2224 pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2228 compress_where: false,
2232 pub fn snuggled(current: &str) -> WhereClauseOption {
2234 suppress_comma: false,
2235 snuggle: last_line_width(current) == 1,
2236 compress_where: false,
2240 pub fn suppress_comma(&mut self) {
2241 self.suppress_comma = true
2244 pub fn compress_where(&mut self) {
2245 self.compress_where = true
2248 pub fn snuggle(&mut self) {
2254 context: &RewriteContext,
2256 explicit_self: Option<&ast::ExplicitSelf>,
2257 one_line_budget: usize,
2258 multi_line_budget: usize,
2263 generics_str_contains_newline: bool,
2264 ) -> Option<String> {
2265 let mut arg_item_strs = args
2268 arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent))
2269 .unwrap_or_else(|| context.snippet(arg.span()).to_owned())
2271 .collect::<Vec<_>>();
2273 // Account for sugary self.
2274 // FIXME: the comment for the self argument is dropped. This is blocked
2275 // on rust issue #27522.
2276 let min_args = explicit_self
2277 .and_then(|explicit_self| rewrite_explicit_self(explicit_self, args, context))
2278 .map_or(1, |self_str| {
2279 arg_item_strs[0] = self_str;
2283 // Comments between args.
2284 let mut arg_items = Vec::new();
2286 arg_items.push(ListItem::from_str(""));
2289 // FIXME(#21): if there are no args, there might still be a comment, but
2290 // without spans for the comment or parens, there is no chance of
2291 // getting it right. You also don't get to put a comment on self, unless
2293 if args.len() >= min_args || variadic {
2294 let comment_span_start = if min_args == 2 {
2295 let second_arg_start = if arg_has_pattern(&args[1]) {
2296 args[1].pat.span.lo()
2298 args[1].ty.span.lo()
2300 let reduced_span = mk_sp(span.lo(), second_arg_start);
2302 context.snippet_provider.span_after_last(reduced_span, ",")
2307 enum ArgumentKind<'a> {
2308 Regular(&'a ast::Arg),
2312 let variadic_arg = if variadic {
2313 let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2314 let variadic_start =
2315 context.snippet_provider.span_after(variadic_span, "...") - BytePos(3);
2316 Some(ArgumentKind::Variadic(variadic_start))
2321 let more_items = itemize_list(
2322 context.snippet_provider,
2323 args[min_args - 1..]
2325 .map(ArgumentKind::Regular)
2326 .chain(variadic_arg),
2330 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2331 ArgumentKind::Variadic(start) => start,
2334 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2335 ArgumentKind::Variadic(start) => start + BytePos(3),
2338 ArgumentKind::Regular(..) => None,
2339 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2346 arg_items.extend(more_items);
2349 let fits_in_one_line = !generics_str_contains_newline
2350 && (arg_items.is_empty()
2351 || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2353 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2354 item.item = Some(arg);
2357 let last_line_ends_with_comment = arg_items
2360 .and_then(|item| item.post_comment.as_ref())
2361 .map_or(false, |s| s.trim().starts_with("//"));
2363 let (indent, trailing_comma) = match context.config.indent_style() {
2364 IndentStyle::Block if fits_in_one_line => {
2365 (indent.block_indent(context.config), SeparatorTactic::Never)
2367 IndentStyle::Block => (
2368 indent.block_indent(context.config),
2369 context.config.trailing_comma(),
2371 IndentStyle::Visual if last_line_ends_with_comment => {
2372 (arg_indent, context.config.trailing_comma())
2374 IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2377 let tactic = definitive_tactic(
2379 context.config.fn_args_density().to_list_tactic(),
2383 let budget = match tactic {
2384 DefinitiveListTactic::Horizontal => one_line_budget,
2385 _ => multi_line_budget,
2388 debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2390 let trailing_separator = if variadic {
2391 SeparatorTactic::Never
2395 let fmt = ListFormatting::new(Shape::legacy(budget, indent), context.config)
2397 .trailing_separator(trailing_separator)
2398 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2399 .preserve_newline(true);
2400 write_list(&arg_items, &fmt)
2403 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2404 if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2405 ident != symbol::keywords::Invalid.ident()
2411 fn compute_budgets_for_args(
2412 context: &RewriteContext,
2416 newline_brace: bool,
2418 force_vertical_layout: bool,
2419 ) -> Option<((usize, usize, Indent))> {
2421 "compute_budgets_for_args {} {:?}, {}, {}",
2427 // Try keeping everything on the same line.
2428 if !result.contains('\n') && !force_vertical_layout {
2429 // 2 = `()`, 3 = `() `, space is before ret_string.
2430 let overhead = if ret_str_len == 0 { 2 } else { 3 };
2431 let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2441 let one_line_budget = context.budget(used_space);
2443 if one_line_budget > 0 {
2445 let (indent, multi_line_budget) = match context.config.indent_style() {
2446 IndentStyle::Block => {
2447 let indent = indent.block_indent(context.config);
2448 (indent, context.budget(indent.width() + 1))
2450 IndentStyle::Visual => {
2451 let indent = indent + result.len() + 1;
2452 let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2453 (indent, context.budget(multi_line_overhead))
2457 return Some((one_line_budget, multi_line_budget, indent));
2461 // Didn't work. we must force vertical layout and put args on a newline.
2462 let new_indent = indent.block_indent(context.config);
2463 let used_space = match context.config.indent_style() {
2465 IndentStyle::Block => new_indent.width() + 1,
2466 // Account for `)` and possibly ` {`.
2467 IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2469 Some((0, context.budget(used_space), new_indent))
2472 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause) -> bool {
2473 let predicate_count = where_clause.predicates.len();
2475 if config.where_single_line() && predicate_count == 1 {
2478 let brace_style = config.brace_style();
2480 brace_style == BraceStyle::AlwaysNextLine
2481 || (brace_style == BraceStyle::SameLineWhere && predicate_count > 0)
2484 fn rewrite_generics(
2485 context: &RewriteContext,
2487 generics: &ast::Generics,
2489 ) -> Option<String> {
2490 // FIXME: convert bounds to where clauses where they get too big or if
2491 // there is a where clause at all.
2493 if generics.params.is_empty() {
2494 return Some(ident.to_owned());
2497 let params = generics.params.iter();
2498 overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span)
2501 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2502 match config.indent_style() {
2503 IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2504 IndentStyle::Block => {
2508 .block_indent(config.tab_spaces())
2509 .with_max_width(config)
2515 fn rewrite_where_clause_rfc_style(
2516 context: &RewriteContext,
2517 where_clause: &ast::WhereClause,
2520 span_end: Option<BytePos>,
2521 span_end_before_where: BytePos,
2522 where_clause_option: WhereClauseOption,
2523 is_args_multi_line: bool,
2524 ) -> Option<String> {
2525 let block_shape = shape.block().with_max_width(context.config);
2527 let (span_before, span_after) =
2528 missing_span_before_after_where(span_end_before_where, where_clause);
2529 let (comment_before, comment_after) =
2530 rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2532 let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2535 block_shape.indent.to_string_with_newline(context.config)
2538 let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2540 let clause_shape = clause_shape.sub_width(1)?;
2541 // each clause on one line, trailing comma (except if suppress_comma)
2542 let span_start = where_clause.predicates[0].span().lo();
2543 // If we don't have the start of the next span, then use the end of the
2544 // predicates, but that means we miss comments.
2545 let len = where_clause.predicates.len();
2546 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2547 let span_end = span_end.unwrap_or(end_of_preds);
2548 let items = itemize_list(
2549 context.snippet_provider,
2550 where_clause.predicates.iter(),
2553 |pred| pred.span().lo(),
2554 |pred| pred.span().hi(),
2555 |pred| pred.rewrite(context, clause_shape),
2560 let where_single_line = context.config.where_single_line() && len == 1 && !is_args_multi_line;
2561 let comma_tactic = if where_clause_option.suppress_comma || where_single_line {
2562 SeparatorTactic::Never
2564 context.config.trailing_comma()
2567 // shape should be vertical only and only if we have `where_single_line` option enabled
2568 // and the number of items of the where clause is equal to 1
2569 let shape_tactic = if where_single_line {
2570 DefinitiveListTactic::Horizontal
2572 DefinitiveListTactic::Vertical
2575 let fmt = ListFormatting::new(clause_shape, context.config)
2576 .tactic(shape_tactic)
2577 .trailing_separator(comma_tactic)
2578 .preserve_newline(true);
2579 let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2581 let comment_separator = |comment: &str, shape: Shape| {
2582 if comment.is_empty() {
2585 shape.indent.to_string_with_newline(context.config)
2588 let newline_before_where = comment_separator(&comment_before, shape);
2589 let newline_after_where = comment_separator(&comment_after, clause_shape);
2592 let clause_sep = if where_clause_option.compress_where
2593 && comment_before.is_empty()
2594 && comment_after.is_empty()
2595 && !preds_str.contains('\n')
2596 && 6 + preds_str.len() <= shape.width
2597 || where_single_line
2601 clause_shape.indent.to_string_with_newline(context.config)
2604 "{}{}{}where{}{}{}{}",
2607 newline_before_where,
2608 newline_after_where,
2615 fn rewrite_where_clause(
2616 context: &RewriteContext,
2617 where_clause: &ast::WhereClause,
2618 brace_style: BraceStyle,
2622 span_end: Option<BytePos>,
2623 span_end_before_where: BytePos,
2624 where_clause_option: WhereClauseOption,
2625 is_args_multi_line: bool,
2626 ) -> Option<String> {
2627 if where_clause.predicates.is_empty() {
2628 return Some(String::new());
2631 if context.config.indent_style() == IndentStyle::Block {
2632 return rewrite_where_clause_rfc_style(
2638 span_end_before_where,
2639 where_clause_option,
2644 let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2646 let offset = match context.config.indent_style() {
2647 IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2648 // 6 = "where ".len()
2649 IndentStyle::Visual => shape.indent + extra_indent + 6,
2651 // FIXME: if indent_style != Visual, then the budgets below might
2652 // be out by a char or two.
2654 let budget = context.config.max_width() - offset.width();
2655 let span_start = where_clause.predicates[0].span().lo();
2656 // If we don't have the start of the next span, then use the end of the
2657 // predicates, but that means we miss comments.
2658 let len = where_clause.predicates.len();
2659 let end_of_preds = where_clause.predicates[len - 1].span().hi();
2660 let span_end = span_end.unwrap_or(end_of_preds);
2661 let items = itemize_list(
2662 context.snippet_provider,
2663 where_clause.predicates.iter(),
2666 |pred| pred.span().lo(),
2667 |pred| pred.span().hi(),
2668 |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2673 let item_vec = items.collect::<Vec<_>>();
2674 // FIXME: we don't need to collect here
2675 let tactic = definitive_tactic(&item_vec, ListTactic::Vertical, Separator::Comma, budget);
2677 let mut comma_tactic = context.config.trailing_comma();
2678 // Kind of a hack because we don't usually have trailing commas in where clauses.
2679 if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2680 comma_tactic = SeparatorTactic::Never;
2683 let fmt = ListFormatting::new(Shape::legacy(budget, offset), context.config)
2685 .trailing_separator(comma_tactic)
2686 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
2687 .preserve_newline(true);
2688 let preds_str = write_list(&item_vec, &fmt)?;
2690 let end_length = if terminator == "{" {
2691 // If the brace is on the next line we don't need to count it otherwise it needs two
2694 BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2695 BraceStyle::PreferSameLine => 2,
2697 } else if terminator == "=" {
2702 if density == Density::Tall
2703 || preds_str.contains('\n')
2704 || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2708 (shape.indent + extra_indent).to_string(context.config),
2712 Some(format!(" where {}", preds_str))
2716 fn missing_span_before_after_where(
2717 before_item_span_end: BytePos,
2718 where_clause: &ast::WhereClause,
2720 let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2722 let pos_after_where = where_clause.span.lo() + BytePos(5);
2723 let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2724 (missing_span_before, missing_span_after)
2727 fn rewrite_comments_before_after_where(
2728 context: &RewriteContext,
2729 span_before_where: Span,
2730 span_after_where: Span,
2732 ) -> Option<(String, String)> {
2733 let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2734 let after_comment = rewrite_missing_comment(
2736 shape.block_indent(context.config.tab_spaces()),
2739 Some((before_comment, after_comment))
2743 context: &RewriteContext,
2746 vis: &ast::Visibility,
2750 format_visibility(context, vis),
2752 rewrite_ident(context, ident)
2756 #[derive(PartialEq, Eq, Clone, Copy)]
2764 context: &RewriteContext,
2765 generics: &ast::Generics,
2766 brace_style: BraceStyle,
2767 brace_pos: BracePos,
2771 ) -> Option<String> {
2772 let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2773 let mut result = rewrite_generics(context, "", generics, shape)?;
2775 let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2776 let budget = context.budget(last_line_used_width(&result, offset.width()));
2777 let mut option = WhereClauseOption::snuggled(&result);
2778 if brace_pos == BracePos::None {
2779 option.suppress_comma = true;
2781 // If the generics are not parameterized then generics.span.hi() == 0,
2782 // so we use span.lo(), which is the position after `struct Foo`.
2783 let span_end_before_where = if !generics.params.is_empty() {
2788 let where_clause_str = rewrite_where_clause(
2790 &generics.where_clause,
2792 Shape::legacy(budget, offset.block_only()),
2796 span_end_before_where,
2800 result.push_str(&where_clause_str);
2801 brace_pos == BracePos::ForceSameLine
2802 || brace_style == BraceStyle::PreferSameLine
2803 || (generics.where_clause.predicates.is_empty()
2804 && trimmed_last_line_width(&result) == 1)
2806 brace_pos == BracePos::ForceSameLine
2807 || trimmed_last_line_width(&result) == 1
2808 || brace_style != BraceStyle::AlwaysNextLine
2810 if brace_pos == BracePos::None {
2811 return Some(result);
2813 let total_used_width = last_line_used_width(&result, used_width);
2814 let remaining_budget = context.budget(total_used_width);
2815 // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2816 // and hence we take the closer into account as well for one line budget.
2817 // We assume that the closer has the same length as the opener.
2818 let overhead = if brace_pos == BracePos::ForceSameLine {
2825 let forbid_same_line_brace = overhead > remaining_budget;
2826 if !forbid_same_line_brace && same_line_brace {
2830 result.push_str(&offset.block_only().to_string(context.config));
2837 impl Rewrite for ast::ForeignItem {
2838 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2839 let attrs_str = self.attrs.rewrite(context, shape)?;
2840 // Drop semicolon or it will be interpreted as comment.
2841 // FIXME: this may be a faulty span from libsyntax.
2842 let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2844 let item_str = match self.node {
2845 ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2849 &FnSig::new(fn_decl, generics, self.vis.clone()),
2854 .map(|(s, _)| format!("{};", s)),
2855 ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2856 // FIXME(#21): we're dropping potential comments in between the
2857 // function keywords here.
2858 let vis = format_visibility(context, &self.vis);
2859 let mut_str = if is_mutable { "mut " } else { "" };
2860 let prefix = format!(
2864 rewrite_ident(context, self.ident)
2867 rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
2869 ast::ForeignItemKind::Ty => {
2870 let vis = format_visibility(context, &self.vis);
2874 rewrite_ident(context, self.ident)
2877 ast::ForeignItemKind::Macro(ref mac) => {
2878 rewrite_macro(mac, None, context, shape, MacroPosition::Item)
2882 let missing_span = if self.attrs.is_empty() {
2883 mk_sp(self.span.lo(), self.span.lo())
2885 mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2887 combine_strs_with_missing_comments(
2898 /// Rewrite an inline mod.
2899 pub fn rewrite_mod(context: &RewriteContext, item: &ast::Item) -> String {
2900 let mut result = String::with_capacity(32);
2901 result.push_str(&*format_visibility(context, &item.vis));
2902 result.push_str("mod ");
2903 result.push_str(rewrite_ident(context, item.ident));
2908 /// Rewrite `extern crate foo;` WITHOUT attributes.
2909 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
2910 assert!(is_extern_crate(item));
2911 let new_str = context.snippet(item.span);
2912 Some(if contains_comment(new_str) {
2915 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
2916 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
2920 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
2921 pub fn is_mod_decl(item: &ast::Item) -> bool {
2923 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
2928 pub fn is_use_item(item: &ast::Item) -> bool {
2930 ast::ItemKind::Use(_) => true,
2935 pub fn is_extern_crate(item: &ast::Item) -> bool {
2937 ast::ItemKind::ExternCrate(..) => true,