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, ptr, 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, CodeCharKind, CommentCodeSlices, FindUncommented};
22 use comment::rewrite_comment;
23 use config::{BraceStyle, Config};
24 use expr::{format_expr, ExprType};
25 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
26 rewrite_static, rewrite_type_alias};
27 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
29 use macros::{rewrite_macro, MacroPosition};
31 use rewrite::{Rewrite, RewriteContext};
32 use utils::{self, contains_skip, mk_sp};
34 fn is_use_item(item: &ast::Item) -> bool {
36 ast::ItemKind::Use(_) => true,
41 fn is_extern_crate(item: &ast::Item) -> bool {
43 ast::ItemKind::ExternCrate(..) => true,
48 pub struct FmtVisitor<'a> {
49 pub parse_session: &'a ParseSess,
50 pub codemap: &'a CodeMap,
51 pub buffer: StringBuffer,
52 pub last_pos: BytePos,
53 // FIXME: use an RAII util or closure for indenting
54 pub block_indent: Indent,
55 pub config: &'a Config,
56 pub is_if_else_block: bool,
59 impl<'a> FmtVisitor<'a> {
60 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
62 "visit_stmt: {:?} {:?}",
63 self.codemap.lookup_char_pos(stmt.span.lo),
64 self.codemap.lookup_char_pos(stmt.span.hi)
68 ast::StmtKind::Item(ref item) => {
69 self.visit_item(item);
71 ast::StmtKind::Local(ref local) => {
72 let rewrite = if contains_skip(&local.attrs) {
77 Shape::indented(self.block_indent, self.config),
80 self.push_rewrite(stmt.span, rewrite);
82 ast::StmtKind::Expr(ref expr) => {
83 let rewrite = format_expr(
87 Shape::indented(self.block_indent, self.config),
89 let span = if expr.attrs.is_empty() {
92 mk_sp(expr.span().lo, stmt.span.hi)
94 self.push_rewrite(span, rewrite)
96 ast::StmtKind::Semi(ref expr) => {
97 let rewrite = stmt.rewrite(
99 Shape::indented(self.block_indent, self.config),
101 let span = if expr.attrs.is_empty() {
104 mk_sp(expr.span().lo, stmt.span.hi)
106 self.push_rewrite(span, rewrite)
108 ast::StmtKind::Mac(ref mac) => {
109 let (ref mac, _macro_style, ref attrs) = **mac;
110 if contains_skip(attrs) {
111 self.push_rewrite(mac.span, None);
113 self.visit_mac(mac, None, MacroPosition::Statement);
115 self.format_missing(stmt.span.hi);
120 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
122 "visit_block: {:?} {:?}",
123 self.codemap.lookup_char_pos(b.span.lo),
124 self.codemap.lookup_char_pos(b.span.hi)
127 // Check if this block has braces.
128 let snippet = self.snippet(b.span);
129 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
130 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
132 self.last_pos = self.last_pos + brace_compensation;
133 self.block_indent = self.block_indent.block_indent(self.config);
134 self.buffer.push_str("{");
136 if self.config.remove_blank_lines_at_start_or_end_of_block() {
137 if let Some(first_stmt) = b.stmts.first() {
138 let attr_lo = inner_attrs
140 utils::inner_attributes(attrs)
142 .map(|attr| attr.span.lo)
145 // Attributes for an item in a statement position
146 // do not belong to the statement. (rust-lang/rust#34459)
147 if let ast::StmtKind::Item(ref item) = first_stmt.node {
150 first_stmt.attrs().first()
152 // Some stmts can have embedded attributes.
153 // e.g. `match { #![attr] ... }`
154 let attr_lo = attr.span.lo;
155 if attr_lo < first_stmt.span.lo {
164 self.snippet(mk_sp(self.last_pos, attr_lo.unwrap_or(first_stmt.span.lo)));
165 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
166 |(kind, _, s)| if kind == CodeCharKind::Normal {
172 if let Some(len) = len {
173 self.last_pos = self.last_pos + BytePos::from_usize(len);
178 // Format inner attributes if available.
179 if let Some(attrs) = inner_attrs {
180 self.visit_attrs(attrs, ast::AttrStyle::Inner);
183 for stmt in &b.stmts {
184 self.visit_stmt(stmt)
187 if !b.stmts.is_empty() {
188 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
189 if utils::semicolon_for_expr(&self.get_context(), expr) {
190 self.buffer.push_str(";");
195 let mut remove_len = BytePos(0);
196 if self.config.remove_blank_lines_at_start_or_end_of_block() {
197 if let Some(stmt) = b.stmts.last() {
198 let snippet = self.snippet(mk_sp(
200 source!(self, b.span).hi - brace_compensation,
202 let len = CommentCodeSlices::new(&snippet)
204 .and_then(|(kind, _, s)| {
205 if kind == CodeCharKind::Normal && s.trim().is_empty() {
211 if let Some(len) = len {
212 remove_len = BytePos::from_usize(len);
217 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
218 if unindent_comment {
219 let end_pos = source!(self, b.span).hi - brace_compensation - remove_len;
220 let snippet = self.get_context().snippet(mk_sp(self.last_pos, end_pos));
221 unindent_comment = snippet.contains("//") || snippet.contains("/*");
223 // FIXME: we should compress any newlines here to just one
224 if unindent_comment {
225 self.block_indent = self.block_indent.block_unindent(self.config);
227 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation - remove_len);
228 if unindent_comment {
229 self.block_indent = self.block_indent.block_indent(self.config);
231 self.close_block(unindent_comment);
232 self.last_pos = source!(self, b.span).hi;
235 // FIXME: this is a terrible hack to indent the comments between the last
236 // item in the block and the closing brace to the block's level.
237 // The closing brace itself, however, should be indented at a shallower
239 fn close_block(&mut self, unindent_comment: bool) {
240 let total_len = self.buffer.len;
241 let chars_too_many = if unindent_comment {
243 } else if self.config.hard_tabs() {
246 self.config.tab_spaces()
248 self.buffer.truncate(total_len - chars_too_many);
249 self.buffer.push_str("}");
250 self.block_indent = self.block_indent.block_unindent(self.config);
253 // Note that this only gets called for function definitions. Required methods
254 // on traits do not get handled here.
261 defaultness: ast::Defaultness,
262 inner_attrs: Option<&[ast::Attribute]>,
264 let indent = self.block_indent;
266 let rewrite = match fk {
267 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
279 mk_sp(s.lo, b.span.lo),
283 visit::FnKind::Method(ident, sig, vis, b) => {
294 vis.unwrap_or(&ast::Visibility::Inherited),
295 mk_sp(s.lo, b.span.lo),
299 visit::FnKind::Closure(_) => unreachable!(),
302 if let Some(fn_str) = rewrite {
303 self.format_missing_with_indent(source!(self, s).lo);
304 self.buffer.push_str(&fn_str);
305 if let Some(c) = fn_str.chars().last() {
307 self.last_pos = source!(self, block.span).hi;
312 self.format_missing(source!(self, block.span).lo);
315 self.last_pos = source!(self, block.span).lo;
316 self.visit_block(block, inner_attrs)
319 pub fn visit_item(&mut self, item: &ast::Item) {
320 skip_out_of_file_lines_range_visitor!(self, item.span);
322 // This is where we bail out if there is a skip attribute. This is only
323 // complex in the module case. It is complex because the module could be
324 // in a separate file and there might be attributes in both files, but
325 // the AST lumps them all together.
326 let mut attrs = item.attrs.clone();
328 ast::ItemKind::Mod(ref m) => {
329 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
330 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
331 if outer_file.name == inner_file.name {
332 // Module is inline, in this case we treat modules like any
334 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
335 self.push_rewrite(item.span, None);
338 } else if utils::contains_skip(&item.attrs) {
339 // Module is not inline, but should be skipped.
342 // Module is not inline and should not be skipped. We want
343 // to process only the attributes in the current file.
344 let filterd_attrs = item.attrs
347 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
348 if attr_file.name == outer_file.name {
354 .collect::<Vec<_>>();
355 // Assert because if we should skip it should be caught by
357 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
358 attrs = filterd_attrs;
361 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
362 self.push_rewrite(item.span, None);
368 ast::ItemKind::Use(ref vp) => {
369 self.format_import(&item.vis, vp, item.span, &item.attrs);
371 ast::ItemKind::Impl(..) => {
372 self.format_missing_with_indent(source!(self, item.span).lo);
373 let snippet = self.get_context().snippet(item.span);
374 let where_span_end = snippet
375 .find_uncommented("{")
376 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo);
377 if let Some(impl_str) =
378 format_impl(&self.get_context(), item, self.block_indent, where_span_end)
380 self.buffer.push_str(&impl_str);
381 self.last_pos = source!(self, item.span).hi;
384 ast::ItemKind::Trait(..) => {
385 self.format_missing_with_indent(item.span.lo);
386 if let Some(trait_str) = format_trait(&self.get_context(), item, self.block_indent)
388 self.buffer.push_str(&trait_str);
389 self.last_pos = source!(self, item.span).hi;
392 ast::ItemKind::ExternCrate(_) => {
393 self.format_missing_with_indent(source!(self, item.span).lo);
394 let new_str = self.snippet(item.span);
395 if contains_comment(&new_str) {
396 self.buffer.push_str(&new_str)
399 &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
401 .push_str(&Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"));
403 self.last_pos = source!(self, item.span).hi;
405 ast::ItemKind::Struct(ref def, ref generics) => {
407 let indent = self.block_indent;
408 let context = self.get_context();
409 ::items::format_struct(
419 ).map(|s| match *def {
420 ast::VariantData::Tuple(..) => s + ";",
424 self.push_rewrite(item.span, rewrite);
426 ast::ItemKind::Enum(ref def, ref generics) => {
427 self.format_missing_with_indent(source!(self, item.span).lo);
428 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
429 self.last_pos = source!(self, item.span).hi;
431 ast::ItemKind::Mod(ref module) => {
432 self.format_missing_with_indent(source!(self, item.span).lo);
433 self.format_mod(module, &item.vis, item.span, item.ident, &attrs);
435 ast::ItemKind::Mac(ref mac) => {
436 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
438 ast::ItemKind::ForeignMod(ref foreign_mod) => {
439 self.format_missing_with_indent(source!(self, item.span).lo);
440 self.format_foreign_mod(foreign_mod, item.span);
442 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
443 let rewrite = rewrite_static(
454 self.push_rewrite(item.span, rewrite);
456 ast::ItemKind::Const(ref ty, ref expr) => {
457 let rewrite = rewrite_static(
462 ast::Mutability::Immutable,
468 self.push_rewrite(item.span, rewrite);
470 ast::ItemKind::DefaultImpl(..) => {
471 // FIXME(#78): format impl definitions.
473 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
475 visit::FnKind::ItemFn(
487 ast::Defaultness::Final,
491 ast::ItemKind::Ty(ref ty, ref generics) => {
492 let rewrite = rewrite_type_alias(
501 self.push_rewrite(item.span, rewrite);
503 ast::ItemKind::Union(ref def, ref generics) => {
504 let rewrite = ::items::format_struct_struct(
515 self.push_rewrite(item.span, rewrite);
517 ast::ItemKind::GlobalAsm(..) => {
518 let snippet = Some(self.snippet(item.span));
519 self.push_rewrite(item.span, snippet);
521 ast::ItemKind::MacroDef(..) => {
522 // FIXME(#1539): macros 2.0
523 let snippet = Some(self.snippet(item.span));
524 self.push_rewrite(item.span, snippet);
529 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
530 skip_out_of_file_lines_range_visitor!(self, ti.span);
532 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
533 self.push_rewrite(ti.span, None);
538 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
539 let rewrite = rewrite_static(
541 &ast::Visibility::Inherited,
544 ast::Mutability::Immutable,
550 self.push_rewrite(ti.span, rewrite);
552 ast::TraitItemKind::Method(ref sig, None) => {
553 let indent = self.block_indent;
554 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
555 self.push_rewrite(ti.span, rewrite);
557 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
559 visit::FnKind::Method(ti.ident, sig, None, body),
563 ast::Defaultness::Final,
567 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
568 let rewrite = rewrite_associated_type(
570 type_default.as_ref(),
571 Some(type_param_bounds),
575 self.push_rewrite(ti.span, rewrite);
577 ast::TraitItemKind::Macro(ref mac) => {
578 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
583 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
584 skip_out_of_file_lines_range_visitor!(self, ii.span);
586 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
587 self.push_rewrite(ii.span, None);
592 ast::ImplItemKind::Method(ref sig, ref body) => {
594 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
602 ast::ImplItemKind::Const(ref ty, ref expr) => {
603 let rewrite = rewrite_static(
608 ast::Mutability::Immutable,
614 self.push_rewrite(ii.span, rewrite);
616 ast::ImplItemKind::Type(ref ty) => {
617 let rewrite = rewrite_associated_impl_type(
625 self.push_rewrite(ii.span, rewrite);
627 ast::ImplItemKind::Macro(ref mac) => {
628 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
633 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
634 skip_out_of_file_lines_range_visitor!(self, mac.span);
637 let shape = Shape::indented(self.block_indent, self.config)
640 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
641 self.push_rewrite(mac.span, rewrite);
644 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
645 self.format_missing_with_indent(source!(self, span).lo);
646 let result = rewrite.unwrap_or_else(|| self.snippet(span));
647 self.buffer.push_str(&result);
648 self.last_pos = source!(self, span).hi;
651 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
653 parse_session: parse_session,
654 codemap: parse_session.codemap(),
655 buffer: StringBuffer::new(),
656 last_pos: BytePos(0),
657 block_indent: Indent::empty(),
659 is_if_else_block: false,
663 pub fn snippet(&self, span: Span) -> String {
664 match self.codemap.span_to_snippet(span) {
668 "Couldn't make snippet for span {:?}->{:?}",
669 self.codemap.lookup_char_pos(span.lo),
670 self.codemap.lookup_char_pos(span.hi)
677 // Returns true if we should skip the following item.
678 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
679 if utils::contains_skip(attrs) {
683 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
684 if attrs.is_empty() {
688 let rewrite = attrs.rewrite(
690 Shape::indented(self.block_indent, self.config),
692 let span = mk_sp(attrs[0].span.lo, attrs[attrs.len() - 1].span.hi);
693 self.push_rewrite(span, rewrite);
700 items_left: &[ptr::P<ast::Item>],
705 F: Fn(&ast::Item) -> bool,
707 let mut last = self.codemap.lookup_line_range(items_left[0].span());
708 let item_length = items_left
711 is_item(&***ppi) && (!in_group || {
712 let current = self.codemap.lookup_line_range(ppi.span());
713 let in_same_group = current.lo < last.hi + 2;
719 let items = &items_left[..item_length];
721 let at_least_one_in_file_lines = items
723 .any(|item| !out_of_file_lines_range!(self, item.span));
725 if at_least_one_in_file_lines {
726 self.format_imports(items);
729 self.push_rewrite(item.span, None);
736 fn walk_mod_items(&mut self, m: &ast::Mod) {
737 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
738 while !items_left.is_empty() {
739 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
740 // to be potentially reordered within `format_imports`. Otherwise, just format the
741 // next item for output.
742 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
743 let used_items_len = self.reorder_items(
746 self.config.reorder_imports_in_group(),
748 let (_, rest) = items_left.split_at(used_items_len);
750 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
751 let used_items_len = self.reorder_items(
754 self.config.reorder_extern_crates_in_group(),
756 let (_, rest) = items_left.split_at(used_items_len);
759 // `unwrap()` is safe here because we know `items_left`
760 // has elements from the loop condition
761 let (item, rest) = items_left.split_first().unwrap();
762 self.visit_item(item);
771 vis: &ast::Visibility,
774 attrs: &[ast::Attribute],
776 // Decide whether this is an inline mod or an external mod.
777 let local_file_name = self.codemap.span_to_filename(s);
778 let inner_span = source!(self, m.inner);
779 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
780 local_file_name == self.codemap.span_to_filename(inner_span);
782 self.buffer.push_str(&*utils::format_visibility(vis));
783 self.buffer.push_str("mod ");
784 self.buffer.push_str(&ident.to_string());
787 match self.config.item_brace_style() {
788 BraceStyle::AlwaysNextLine => self.buffer
789 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
790 _ => self.buffer.push_str(" {"),
792 // Hackery to account for the closing }.
793 let mod_lo = self.codemap.span_after(source!(self, s), "{");
794 let body_snippet = self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
795 let body_snippet = body_snippet.trim();
796 if body_snippet.is_empty() {
797 self.buffer.push_str("}");
799 self.last_pos = mod_lo;
800 self.block_indent = self.block_indent.block_indent(self.config);
801 self.visit_attrs(attrs, ast::AttrStyle::Inner);
802 self.walk_mod_items(m);
803 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
804 self.close_block(false);
806 self.last_pos = source!(self, m.inner).hi;
808 self.buffer.push_str(";");
809 self.last_pos = source!(self, s).hi;
813 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
814 self.block_indent = Indent::empty();
815 self.walk_mod_items(m);
816 self.format_missing_with_indent(filemap.end_pos);
819 pub fn get_context(&self) -> RewriteContext {
821 parse_session: self.parse_session,
822 codemap: self.codemap,
826 is_if_else_block: false,
827 force_one_line_chain: false,
832 impl Rewrite for ast::NestedMetaItem {
833 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
835 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
836 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
841 impl Rewrite for ast::MetaItem {
842 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
843 Some(match self.node {
844 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
845 ast::MetaItemKind::List(ref list) => {
846 let name = self.name.as_str();
847 // 3 = `#[` and `(`, 2 = `]` and `)`
848 let item_shape = try_opt!(
850 .shrink_left(name.len() + 3)
851 .and_then(|s| s.sub_width(2))
853 let items = itemize_list(
857 |nested_meta_item| nested_meta_item.span.lo,
858 |nested_meta_item| nested_meta_item.span.hi,
859 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
864 let item_vec = items.collect::<Vec<_>>();
865 let fmt = ListFormatting {
866 tactic: DefinitiveListTactic::Mixed,
868 trailing_separator: SeparatorTactic::Never,
869 separator_place: SeparatorPlace::Back,
871 ends_with_newline: false,
872 preserve_newline: false,
873 config: context.config,
875 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
877 ast::MetaItemKind::NameValue(ref literal) => {
878 let name = self.name.as_str();
879 let value = context.snippet(literal.span);
880 if &*name == "doc" && contains_comment(&value) {
881 let doc_shape = Shape {
882 width: cmp::min(shape.width, context.config.comment_width())
883 .checked_sub(shape.indent.width())
889 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
892 format!("{} = {}", name, value)
899 impl Rewrite for ast::Attribute {
900 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
901 try_opt!(self.meta())
902 .rewrite(context, shape)
903 .map(|rw| if self.is_sugared_doc {
906 let original = context.snippet(self.span);
907 let prefix = match self.style {
908 ast::AttrStyle::Inner => "#!",
909 ast::AttrStyle::Outer => "#",
911 if contains_comment(&original) {
914 format!("{}[{}]", prefix, rw)
920 impl<'a> Rewrite for [ast::Attribute] {
921 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
922 let mut result = String::new();
926 let indent = shape.indent.to_string(context.config);
928 let mut derive_args = Vec::new();
930 let mut iter = self.iter().enumerate().peekable();
931 while let Some((i, a)) = iter.next() {
932 let a_str = try_opt!(a.rewrite(context, shape));
934 // Write comments and blank lines between attributes.
936 let comment = context.snippet(mk_sp(self[i - 1].span.hi, a.span.lo));
937 // This particular horror show is to preserve line breaks in between doc
938 // comments. An alternative would be to force such line breaks to start
939 // with the usual doc comment token.
940 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
941 let comment = comment.trim();
942 if !comment.is_empty() {
943 let comment = try_opt!(rewrite_comment(
947 context.config.comment_width() - shape.indent.width(),
952 result.push_str(&indent);
953 result.push_str(&comment);
955 } else if multi_line {
958 if derive_args.is_empty() {
959 result.push_str(&indent);
963 // Write the attribute itself.
964 let mut insert_new_line = true;
965 if context.config.merge_derives() {
966 // If the attribute is `#[derive(...)]`, take the arguments.
967 if let Some(mut args) = get_derive_args(context, a) {
968 derive_args.append(&mut args);
970 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
971 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
972 // If not, rewrite the merged derives.
974 result.push_str(&format!("#[derive({})]", derive_args.join(", ")));
979 result.push_str(&a_str);
982 result.push_str(&a_str);
985 if insert_new_line && i < self.len() - 1 {
993 fn is_derive(attr: &ast::Attribute) -> bool {
995 Some(meta_item) => match meta_item.node {
996 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1003 /// Returns the arguments of `#[derive(...)]`.
1004 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1005 attr.meta().and_then(|meta_item| match meta_item.node {
1006 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1007 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1010 .map(|a| context.snippet(a.span))
1011 .collect::<Vec<_>>(),