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.
13 use strings::string_buffer::StringBuffer;
14 use syntax::{ast, visit};
15 use syntax::attr::HasAttrs;
16 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
17 use syntax::parse::ParseSess;
19 use {Indent, Shape, Spanned};
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{contains_comment, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices,
23 use comment::rewrite_comment;
24 use config::{BraceStyle, Config};
25 use items::{format_impl, format_struct, format_struct_struct, format_trait,
26 rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
28 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
30 use macros::{rewrite_macro, MacroPosition};
32 use rewrite::{Rewrite, RewriteContext};
33 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
35 fn is_use_item(item: &ast::Item) -> bool {
37 ast::ItemKind::Use(_) => true,
42 fn is_extern_crate(item: &ast::Item) -> bool {
44 ast::ItemKind::ExternCrate(..) => true,
49 pub struct FmtVisitor<'a> {
50 pub parse_session: &'a ParseSess,
51 pub codemap: &'a CodeMap,
52 pub buffer: StringBuffer,
53 pub last_pos: BytePos,
54 // FIXME: use an RAII util or closure for indenting
55 pub block_indent: Indent,
56 pub config: &'a Config,
57 pub is_if_else_block: bool,
60 impl<'a> FmtVisitor<'a> {
61 pub fn shape(&self) -> Shape {
62 Shape::indented(self.block_indent, self.config)
65 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
67 "visit_stmt: {:?} {:?}",
68 self.codemap.lookup_char_pos(stmt.span.lo()),
69 self.codemap.lookup_char_pos(stmt.span.hi())
73 ast::StmtKind::Item(ref item) => {
74 self.visit_item(item);
76 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
77 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
78 self.push_rewrite(stmt.span(), rewrite)
80 ast::StmtKind::Mac(ref mac) => {
81 let (ref mac, _macro_style, ref attrs) = **mac;
82 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
83 self.push_rewrite(stmt.span(), None);
85 self.visit_mac(mac, None, MacroPosition::Statement);
87 self.format_missing(stmt.span.hi());
92 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
94 "visit_block: {:?} {:?}",
95 self.codemap.lookup_char_pos(b.span.lo()),
96 self.codemap.lookup_char_pos(b.span.hi())
99 // Check if this block has braces.
100 let snippet = self.snippet(b.span);
101 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
102 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
104 self.last_pos = self.last_pos + brace_compensation;
105 self.block_indent = self.block_indent.block_indent(self.config);
106 self.buffer.push_str("{");
108 if self.config.remove_blank_lines_at_start_or_end_of_block() {
109 if let Some(first_stmt) = b.stmts.first() {
110 let attr_lo = inner_attrs
112 inner_attributes(attrs).first().map(|attr| attr.span.lo())
115 // Attributes for an item in a statement position
116 // do not belong to the statement. (rust-lang/rust#34459)
117 if let ast::StmtKind::Item(ref item) = first_stmt.node {
120 first_stmt.attrs().first()
122 // Some stmts can have embedded attributes.
123 // e.g. `match { #![attr] ... }`
124 let attr_lo = attr.span.lo();
125 if attr_lo < first_stmt.span.lo() {
133 let snippet = self.snippet(mk_sp(
135 attr_lo.unwrap_or(first_stmt.span.lo()),
137 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
138 |(kind, _, s)| if kind == CodeCharKind::Normal {
144 if let Some(len) = len {
145 self.last_pos = self.last_pos + BytePos::from_usize(len);
150 // Format inner attributes if available.
151 if let Some(attrs) = inner_attrs {
152 self.visit_attrs(attrs, ast::AttrStyle::Inner);
155 self.walk_block_stmts(b);
157 if !b.stmts.is_empty() {
158 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
159 if utils::semicolon_for_expr(&self.get_context(), expr) {
160 self.buffer.push_str(";");
165 let mut remove_len = BytePos(0);
166 if self.config.remove_blank_lines_at_start_or_end_of_block() {
167 if let Some(stmt) = b.stmts.last() {
168 let snippet = self.snippet(mk_sp(
170 source!(self, b.span).hi() - brace_compensation,
172 let len = CommentCodeSlices::new(&snippet)
174 .and_then(|(kind, _, s)| {
175 if kind == CodeCharKind::Normal && s.trim().is_empty() {
181 if let Some(len) = len {
182 remove_len = BytePos::from_usize(len);
187 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
188 if unindent_comment {
189 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
190 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
191 unindent_comment = snippet.contains("//") || snippet.contains("/*");
193 // FIXME: we should compress any newlines here to just one
194 if unindent_comment {
195 self.block_indent = self.block_indent.block_unindent(self.config);
197 self.format_missing_with_indent(
198 source!(self, b.span).hi() - brace_compensation - remove_len,
200 if unindent_comment {
201 self.block_indent = self.block_indent.block_indent(self.config);
203 self.close_block(unindent_comment);
204 self.last_pos = source!(self, b.span).hi();
207 // FIXME: this is a terrible hack to indent the comments between the last
208 // item in the block and the closing brace to the block's level.
209 // The closing brace itself, however, should be indented at a shallower
211 fn close_block(&mut self, unindent_comment: bool) {
212 let total_len = self.buffer.len;
213 let chars_too_many = if unindent_comment {
215 } else if self.config.hard_tabs() {
218 self.config.tab_spaces()
220 self.buffer.truncate(total_len - chars_too_many);
221 self.buffer.push_str("}");
222 self.block_indent = self.block_indent.block_unindent(self.config);
225 // Note that this only gets called for function definitions. Required methods
226 // on traits do not get handled here.
233 defaultness: ast::Defaultness,
234 inner_attrs: Option<&[ast::Attribute]>,
236 let indent = self.block_indent;
238 let rewrite = match fk {
239 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
251 mk_sp(s.lo(), b.span.lo()),
255 visit::FnKind::Method(ident, sig, vis, b) => {
266 vis.unwrap_or(&ast::Visibility::Inherited),
267 mk_sp(s.lo(), b.span.lo()),
271 visit::FnKind::Closure(_) => unreachable!(),
274 if let Some(fn_str) = rewrite {
275 self.format_missing_with_indent(source!(self, s).lo());
276 self.buffer.push_str(&fn_str);
277 if let Some(c) = fn_str.chars().last() {
279 self.last_pos = source!(self, block.span).hi();
284 self.format_missing(source!(self, block.span).lo());
287 self.last_pos = source!(self, block.span).lo();
288 self.visit_block(block, inner_attrs)
291 pub fn visit_item(&mut self, item: &ast::Item) {
292 skip_out_of_file_lines_range_visitor!(self, item.span);
294 // This is where we bail out if there is a skip attribute. This is only
295 // complex in the module case. It is complex because the module could be
296 // in a separate file and there might be attributes in both files, but
297 // the AST lumps them all together.
299 let mut attrs = &item.attrs;
301 ast::ItemKind::Mod(ref m) => {
302 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
303 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
304 if outer_file.name == inner_file.name {
305 // Module is inline, in this case we treat modules like any
307 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
308 self.push_rewrite(item.span, None);
311 } else if contains_skip(&item.attrs) {
312 // Module is not inline, but should be skipped.
315 // Module is not inline and should not be skipped. We want
316 // to process only the attributes in the current file.
317 filterd_attrs = item.attrs
320 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
321 if attr_file.name == outer_file.name {
327 .collect::<Vec<_>>();
328 // Assert because if we should skip it should be caught by
330 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
331 attrs = &filterd_attrs;
334 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
335 self.push_rewrite(item.span, None);
341 ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
342 ast::ItemKind::Impl(..) => {
343 let snippet = self.snippet(item.span);
344 let where_span_end = snippet
345 .find_uncommented("{")
346 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
347 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
348 self.push_rewrite(item.span, rw);
350 ast::ItemKind::Trait(..) => {
351 let rw = format_trait(&self.get_context(), item, self.block_indent);
352 self.push_rewrite(item.span, rw);
354 ast::ItemKind::ExternCrate(_) => {
355 let rw = rewrite_extern_crate(&self.get_context(), item);
356 self.push_rewrite(item.span, rw);
358 ast::ItemKind::Struct(ref def, ref generics) => {
359 let rewrite = format_struct(
369 ).map(|s| match *def {
370 ast::VariantData::Tuple(..) => s + ";",
373 self.push_rewrite(item.span, rewrite);
375 ast::ItemKind::Enum(ref def, ref generics) => {
376 self.format_missing_with_indent(source!(self, item.span).lo());
377 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
378 self.last_pos = source!(self, item.span).hi();
380 ast::ItemKind::Mod(ref module) => {
381 self.format_missing_with_indent(source!(self, item.span).lo());
382 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
384 ast::ItemKind::Mac(ref mac) => {
385 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
387 ast::ItemKind::ForeignMod(ref foreign_mod) => {
388 self.format_missing_with_indent(source!(self, item.span).lo());
389 self.format_foreign_mod(foreign_mod, item.span);
391 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
392 let rewrite = rewrite_static(
403 self.push_rewrite(item.span, rewrite);
405 ast::ItemKind::Const(ref ty, ref expr) => {
406 let rewrite = rewrite_static(
411 ast::Mutability::Immutable,
417 self.push_rewrite(item.span, rewrite);
419 ast::ItemKind::DefaultImpl(..) => {
420 // FIXME(#78): format impl definitions.
422 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
424 visit::FnKind::ItemFn(
436 ast::Defaultness::Final,
440 ast::ItemKind::Ty(ref ty, ref generics) => {
441 let rewrite = rewrite_type_alias(
450 self.push_rewrite(item.span, rewrite);
452 ast::ItemKind::Union(ref def, ref generics) => {
453 let rewrite = format_struct_struct(
464 self.push_rewrite(item.span, rewrite);
466 ast::ItemKind::GlobalAsm(..) => {
467 let snippet = Some(self.snippet(item.span));
468 self.push_rewrite(item.span, snippet);
470 ast::ItemKind::MacroDef(..) => {
471 // FIXME(#1539): macros 2.0
472 let mac_snippet = Some(self.snippet(item.span));
473 self.push_rewrite(item.span, mac_snippet);
478 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
479 skip_out_of_file_lines_range_visitor!(self, ti.span);
481 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
482 self.push_rewrite(ti.span, None);
487 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
488 let rewrite = rewrite_static(
490 &ast::Visibility::Inherited,
493 ast::Mutability::Immutable,
499 self.push_rewrite(ti.span, rewrite);
501 ast::TraitItemKind::Method(ref sig, None) => {
502 let indent = self.block_indent;
503 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
504 self.push_rewrite(ti.span, rewrite);
506 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
508 visit::FnKind::Method(ti.ident, sig, None, body),
512 ast::Defaultness::Final,
516 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
517 let rewrite = rewrite_associated_type(
519 type_default.as_ref(),
520 Some(type_param_bounds),
524 self.push_rewrite(ti.span, rewrite);
526 ast::TraitItemKind::Macro(ref mac) => {
527 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
532 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
533 skip_out_of_file_lines_range_visitor!(self, ii.span);
535 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
536 self.push_rewrite(ii.span, None);
541 ast::ImplItemKind::Method(ref sig, ref body) => {
543 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
551 ast::ImplItemKind::Const(ref ty, ref expr) => {
552 let rewrite = rewrite_static(
557 ast::Mutability::Immutable,
563 self.push_rewrite(ii.span, rewrite);
565 ast::ImplItemKind::Type(ref ty) => {
566 let rewrite = rewrite_associated_impl_type(
574 self.push_rewrite(ii.span, rewrite);
576 ast::ImplItemKind::Macro(ref mac) => {
577 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
582 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
583 skip_out_of_file_lines_range_visitor!(self, mac.span);
586 let shape = self.shape().sub_width(1).unwrap();
587 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
588 self.push_rewrite(mac.span, rewrite);
591 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
592 self.format_missing_with_indent(source!(self, span).lo());
593 let result = rewrite.unwrap_or_else(|| self.snippet(span));
594 self.buffer.push_str(&result);
595 self.last_pos = source!(self, span).hi();
598 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
600 parse_session: parse_session,
601 codemap: parse_session.codemap(),
602 buffer: StringBuffer::new(),
603 last_pos: BytePos(0),
604 block_indent: Indent::empty(),
606 is_if_else_block: false,
610 pub fn snippet(&self, span: Span) -> String {
611 match self.codemap.span_to_snippet(span) {
615 "Couldn't make snippet for span {:?}->{:?}",
616 self.codemap.lookup_char_pos(span.lo()),
617 self.codemap.lookup_char_pos(span.hi())
624 // Returns true if we should skip the following item.
625 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
626 if contains_skip(attrs) {
630 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
631 if attrs.is_empty() {
635 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
636 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
637 self.push_rewrite(span, rewrite);
642 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
644 F: Fn(&ast::Item) -> bool,
646 let mut last = self.codemap.lookup_line_range(items_left[0].span());
647 let item_length = items_left
650 is_item(&***ppi) && (!in_group || {
651 let current = self.codemap.lookup_line_range(ppi.span());
652 let in_same_group = current.lo < last.hi + 2;
658 let items = &items_left[..item_length];
660 let at_least_one_in_file_lines = items
662 .any(|item| !out_of_file_lines_range!(self, item.span));
664 if at_least_one_in_file_lines {
665 self.format_imports(items);
668 self.push_rewrite(item.span, None);
675 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
676 while !items_left.is_empty() {
677 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
678 // to be potentially reordered within `format_imports`. Otherwise, just format the
679 // next item for output.
680 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
681 let used_items_len = self.reorder_items(
684 self.config.reorder_imports_in_group(),
686 let (_, rest) = items_left.split_at(used_items_len);
688 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
689 let used_items_len = self.reorder_items(
692 self.config.reorder_extern_crates_in_group(),
694 let (_, rest) = items_left.split_at(used_items_len);
697 // `unwrap()` is safe here because we know `items_left`
698 // has elements from the loop condition
699 let (item, rest) = items_left.split_first().unwrap();
700 self.visit_item(item);
706 fn walk_mod_items(&mut self, m: &ast::Mod) {
707 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
710 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
711 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
713 ast::StmtKind::Item(ref item) => Some(&**item),
718 if stmts.is_empty() {
722 // Extract leading `use ...;`.
723 let items: Vec<_> = stmts
725 .take_while(|stmt| to_stmt_item(stmt).is_some())
726 .filter_map(|stmt| to_stmt_item(stmt))
727 .take_while(|item| is_use_item(item))
730 if items.is_empty() {
731 self.visit_stmt(&stmts[0]);
732 self.walk_stmts(&stmts[1..]);
734 self.walk_items(&items);
735 self.walk_stmts(&stmts[items.len()..]);
739 fn walk_block_stmts(&mut self, b: &ast::Block) {
740 self.walk_stmts(&b.stmts)
746 vis: &ast::Visibility,
749 attrs: &[ast::Attribute],
751 // Decide whether this is an inline mod or an external mod.
752 let local_file_name = self.codemap.span_to_filename(s);
753 let inner_span = source!(self, m.inner);
754 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
755 && local_file_name == self.codemap.span_to_filename(inner_span);
757 self.buffer.push_str(&*utils::format_visibility(vis));
758 self.buffer.push_str("mod ");
759 self.buffer.push_str(&ident.to_string());
762 match self.config.item_brace_style() {
763 BraceStyle::AlwaysNextLine => self.buffer
764 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
765 _ => self.buffer.push_str(" {"),
767 // Hackery to account for the closing }.
768 let mod_lo = self.codemap.span_after(source!(self, s), "{");
770 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
771 let body_snippet = body_snippet.trim();
772 if body_snippet.is_empty() {
773 self.buffer.push_str("}");
775 self.last_pos = mod_lo;
776 self.block_indent = self.block_indent.block_indent(self.config);
777 self.visit_attrs(attrs, ast::AttrStyle::Inner);
778 self.walk_mod_items(m);
779 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
780 self.close_block(false);
782 self.last_pos = source!(self, m.inner).hi();
784 self.buffer.push_str(";");
785 self.last_pos = source!(self, s).hi();
789 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
790 self.block_indent = Indent::empty();
791 self.walk_mod_items(m);
792 self.format_missing_with_indent(filemap.end_pos);
795 pub fn get_context(&self) -> RewriteContext {
797 parse_session: self.parse_session,
798 codemap: self.codemap,
802 is_if_else_block: false,
803 force_one_line_chain: false,
808 impl Rewrite for ast::NestedMetaItem {
809 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
811 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
812 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
817 impl Rewrite for ast::MetaItem {
818 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
819 Some(match self.node {
820 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
821 ast::MetaItemKind::List(ref list) => {
822 let name = self.name.as_str();
823 // 3 = `#[` and `(`, 2 = `]` and `)`
824 let item_shape = try_opt!(
826 .shrink_left(name.len() + 3)
827 .and_then(|s| s.sub_width(2))
829 let items = itemize_list(
833 |nested_meta_item| nested_meta_item.span.lo(),
834 |nested_meta_item| nested_meta_item.span.hi(),
835 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
840 let item_vec = items.collect::<Vec<_>>();
841 let fmt = ListFormatting {
842 tactic: DefinitiveListTactic::Mixed,
844 trailing_separator: SeparatorTactic::Never,
845 separator_place: SeparatorPlace::Back,
847 ends_with_newline: false,
848 preserve_newline: false,
849 config: context.config,
851 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
853 ast::MetaItemKind::NameValue(ref literal) => {
854 let name = self.name.as_str();
855 let value = context.snippet(literal.span);
856 if &*name == "doc" && contains_comment(&value) {
857 let doc_shape = Shape {
858 width: cmp::min(shape.width, context.config.comment_width())
859 .checked_sub(shape.indent.width())
863 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
865 format!("{} = {}", name, value)
872 impl Rewrite for ast::Attribute {
873 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
874 try_opt!(self.meta())
875 .rewrite(context, shape)
876 .map(|rw| if self.is_sugared_doc {
879 let original = context.snippet(self.span);
880 let prefix = match self.style {
881 ast::AttrStyle::Inner => "#!",
882 ast::AttrStyle::Outer => "#",
884 if contains_comment(&original) {
887 format!("{}[{}]", prefix, rw)
893 impl<'a> Rewrite for [ast::Attribute] {
894 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
896 return Some(String::new());
898 let mut result = String::with_capacity(128);
899 let indent = shape.indent.to_string(context.config);
901 let mut derive_args = Vec::new();
903 let mut iter = self.iter().enumerate().peekable();
904 let mut insert_new_line = true;
905 let mut is_prev_sugared_doc = false;
906 while let Some((i, a)) = iter.next() {
907 let a_str = try_opt!(a.rewrite(context, shape));
909 // Write comments and blank lines between attributes.
911 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
912 // This particular horror show is to preserve line breaks in between doc
913 // comments. An alternative would be to force such line breaks to start
914 // with the usual doc comment token.
915 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
916 || is_prev_sugared_doc
918 // Look at before and after comment and see if there are any empty lines.
919 let comment_begin = comment.chars().position(|c| c == '/');
920 let len = comment_begin.unwrap_or_else(|| comment.len());
921 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
922 let mla = if comment_begin.is_none() {
925 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
926 let len = comment_end.unwrap();
931 .filter(|c| *c == '\n')
939 let comment = try_opt!(recover_missing_comment_in_span(
940 mk_sp(self[i - 1].span.hi(), a.span.lo()),
941 shape.with_max_width(context.config),
946 if !comment.is_empty() {
947 if multi_line_before {
950 result.push_str(&comment);
952 if multi_line_after {
955 } else if insert_new_line {
957 if multi_line_after {
962 if derive_args.is_empty() {
963 result.push_str(&indent);
966 insert_new_line = true;
969 // Write the attribute itself.
970 if context.config.merge_derives() {
971 // If the attribute is `#[derive(...)]`, take the arguments.
972 if let Some(mut args) = get_derive_args(context, a) {
973 derive_args.append(&mut args);
975 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
976 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
977 // If not, rewrite the merged derives.
979 result.push_str(&try_opt!(format_derive(context, &derive_args, shape)));
984 result.push_str(&a_str);
987 result.push_str(&a_str);
990 is_prev_sugared_doc = a.is_sugared_doc;
996 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
997 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
998 let mut result = String::with_capacity(128);
999 result.push_str("#[derive(");
1000 // 11 = `#[derive()]`
1001 let initial_budget = try_opt!(shape.width.checked_sub(11));
1002 let mut budget = initial_budget;
1003 let num = derive_args.len();
1004 for (i, a) in derive_args.iter().enumerate() {
1006 let width = a.len() + 2;
1009 // Remove trailing whitespace.
1014 result.push_str(&(shape.indent + 9).to_string(context.config));
1015 budget = initial_budget;
1017 budget = budget.checked_sub(width).unwrap_or(0);
1021 result.push_str(", ")
1024 result.push_str(")]");
1028 fn is_derive(attr: &ast::Attribute) -> bool {
1030 Some(meta_item) => match meta_item.node {
1031 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1038 /// Returns the arguments of `#[derive(...)]`.
1039 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1040 attr.meta().and_then(|meta_item| match meta_item.node {
1041 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1042 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1045 .map(|a| context.snippet(a.span))
1046 .collect::<Vec<_>>(),
1053 // Rewrite `extern crate foo;` WITHOUT attributes.
1054 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1055 assert!(is_extern_crate(item));
1056 let new_str = context.snippet(item.span);
1057 Some(if contains_comment(&new_str) {
1060 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1061 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))