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, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices,
23 use comment::rewrite_comment;
24 use config::{BraceStyle, Config};
25 use expr::{format_expr, ExprType};
26 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
27 rewrite_static, rewrite_type_alias};
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, mk_sp};
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 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
63 "visit_stmt: {:?} {:?}",
64 self.codemap.lookup_char_pos(stmt.span.lo),
65 self.codemap.lookup_char_pos(stmt.span.hi)
69 ast::StmtKind::Item(ref item) => {
70 self.visit_item(item);
72 ast::StmtKind::Local(ref local) => {
73 let rewrite = if contains_skip(&local.attrs) {
78 Shape::indented(self.block_indent, self.config),
81 self.push_rewrite(stmt.span, rewrite);
83 ast::StmtKind::Expr(ref expr) => {
84 let rewrite = format_expr(
88 Shape::indented(self.block_indent, self.config),
90 let span = if expr.attrs.is_empty() {
93 mk_sp(expr.span().lo, stmt.span.hi)
95 self.push_rewrite(span, rewrite)
97 ast::StmtKind::Semi(ref expr) => {
98 let rewrite = stmt.rewrite(
100 Shape::indented(self.block_indent, self.config),
102 let span = if expr.attrs.is_empty() {
105 mk_sp(expr.span().lo, stmt.span.hi)
107 self.push_rewrite(span, rewrite)
109 ast::StmtKind::Mac(ref mac) => {
110 let (ref mac, _macro_style, ref attrs) = **mac;
111 if contains_skip(attrs) {
112 self.push_rewrite(mac.span, None);
114 self.visit_mac(mac, None, MacroPosition::Statement);
116 self.format_missing(stmt.span.hi);
121 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
123 "visit_block: {:?} {:?}",
124 self.codemap.lookup_char_pos(b.span.lo),
125 self.codemap.lookup_char_pos(b.span.hi)
128 // Check if this block has braces.
129 let snippet = self.snippet(b.span);
130 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
131 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
133 self.last_pos = self.last_pos + brace_compensation;
134 self.block_indent = self.block_indent.block_indent(self.config);
135 self.buffer.push_str("{");
137 if self.config.remove_blank_lines_at_start_or_end_of_block() {
138 if let Some(first_stmt) = b.stmts.first() {
139 let attr_lo = inner_attrs
141 utils::inner_attributes(attrs)
143 .map(|attr| attr.span.lo)
146 // Attributes for an item in a statement position
147 // do not belong to the statement. (rust-lang/rust#34459)
148 if let ast::StmtKind::Item(ref item) = first_stmt.node {
151 first_stmt.attrs().first()
153 // Some stmts can have embedded attributes.
154 // e.g. `match { #![attr] ... }`
155 let attr_lo = attr.span.lo;
156 if attr_lo < first_stmt.span.lo {
165 self.snippet(mk_sp(self.last_pos, attr_lo.unwrap_or(first_stmt.span.lo)));
166 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
167 |(kind, _, s)| if kind == CodeCharKind::Normal {
173 if let Some(len) = len {
174 self.last_pos = self.last_pos + BytePos::from_usize(len);
179 // Format inner attributes if available.
180 if let Some(attrs) = inner_attrs {
181 self.visit_attrs(attrs, ast::AttrStyle::Inner);
184 for stmt in &b.stmts {
185 self.visit_stmt(stmt)
188 if !b.stmts.is_empty() {
189 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
190 if utils::semicolon_for_expr(&self.get_context(), expr) {
191 self.buffer.push_str(";");
196 let mut remove_len = BytePos(0);
197 if self.config.remove_blank_lines_at_start_or_end_of_block() {
198 if let Some(stmt) = b.stmts.last() {
199 let snippet = self.snippet(mk_sp(
201 source!(self, b.span).hi - brace_compensation,
203 let len = CommentCodeSlices::new(&snippet)
205 .and_then(|(kind, _, s)| {
206 if kind == CodeCharKind::Normal && s.trim().is_empty() {
212 if let Some(len) = len {
213 remove_len = BytePos::from_usize(len);
218 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
219 if unindent_comment {
220 let end_pos = source!(self, b.span).hi - brace_compensation - remove_len;
221 let snippet = self.get_context().snippet(mk_sp(self.last_pos, end_pos));
222 unindent_comment = snippet.contains("//") || snippet.contains("/*");
224 // FIXME: we should compress any newlines here to just one
225 if unindent_comment {
226 self.block_indent = self.block_indent.block_unindent(self.config);
228 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation - remove_len);
229 if unindent_comment {
230 self.block_indent = self.block_indent.block_indent(self.config);
232 self.close_block(unindent_comment);
233 self.last_pos = source!(self, b.span).hi;
236 // FIXME: this is a terrible hack to indent the comments between the last
237 // item in the block and the closing brace to the block's level.
238 // The closing brace itself, however, should be indented at a shallower
240 fn close_block(&mut self, unindent_comment: bool) {
241 let total_len = self.buffer.len;
242 let chars_too_many = if unindent_comment {
244 } else if self.config.hard_tabs() {
247 self.config.tab_spaces()
249 self.buffer.truncate(total_len - chars_too_many);
250 self.buffer.push_str("}");
251 self.block_indent = self.block_indent.block_unindent(self.config);
254 // Note that this only gets called for function definitions. Required methods
255 // on traits do not get handled here.
262 defaultness: ast::Defaultness,
263 inner_attrs: Option<&[ast::Attribute]>,
265 let indent = self.block_indent;
267 let rewrite = match fk {
268 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
280 mk_sp(s.lo, b.span.lo),
284 visit::FnKind::Method(ident, sig, vis, b) => {
295 vis.unwrap_or(&ast::Visibility::Inherited),
296 mk_sp(s.lo, b.span.lo),
300 visit::FnKind::Closure(_) => unreachable!(),
303 if let Some(fn_str) = rewrite {
304 self.format_missing_with_indent(source!(self, s).lo);
305 self.buffer.push_str(&fn_str);
306 if let Some(c) = fn_str.chars().last() {
308 self.last_pos = source!(self, block.span).hi;
313 self.format_missing(source!(self, block.span).lo);
316 self.last_pos = source!(self, block.span).lo;
317 self.visit_block(block, inner_attrs)
320 pub fn visit_item(&mut self, item: &ast::Item) {
321 skip_out_of_file_lines_range_visitor!(self, item.span);
323 // This is where we bail out if there is a skip attribute. This is only
324 // complex in the module case. It is complex because the module could be
325 // in a separate file and there might be attributes in both files, but
326 // the AST lumps them all together.
327 let mut attrs = item.attrs.clone();
329 ast::ItemKind::Mod(ref m) => {
330 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
331 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
332 if outer_file.name == inner_file.name {
333 // Module is inline, in this case we treat modules like any
335 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
336 self.push_rewrite(item.span, None);
339 } else if utils::contains_skip(&item.attrs) {
340 // Module is not inline, but should be skipped.
343 // Module is not inline and should not be skipped. We want
344 // to process only the attributes in the current file.
345 let filterd_attrs = item.attrs
348 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
349 if attr_file.name == outer_file.name {
355 .collect::<Vec<_>>();
356 // Assert because if we should skip it should be caught by
358 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
359 attrs = filterd_attrs;
362 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
363 self.push_rewrite(item.span, None);
369 ast::ItemKind::Use(ref vp) => {
370 self.format_import(&item.vis, vp, item.span, &item.attrs);
372 ast::ItemKind::Impl(..) => {
373 self.format_missing_with_indent(source!(self, item.span).lo);
374 let snippet = self.get_context().snippet(item.span);
375 let where_span_end = snippet
376 .find_uncommented("{")
377 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo);
378 if let Some(impl_str) =
379 format_impl(&self.get_context(), item, self.block_indent, where_span_end)
381 self.buffer.push_str(&impl_str);
382 self.last_pos = source!(self, item.span).hi;
385 ast::ItemKind::Trait(..) => {
386 self.format_missing_with_indent(item.span.lo);
387 if let Some(trait_str) = format_trait(&self.get_context(), item, self.block_indent)
389 self.buffer.push_str(&trait_str);
390 self.last_pos = source!(self, item.span).hi;
393 ast::ItemKind::ExternCrate(_) => {
394 self.format_missing_with_indent(source!(self, item.span).lo);
395 let new_str = self.snippet(item.span);
396 if contains_comment(&new_str) {
397 self.buffer.push_str(&new_str)
400 &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
402 .push_str(&Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"));
404 self.last_pos = source!(self, item.span).hi;
406 ast::ItemKind::Struct(ref def, ref generics) => {
408 let indent = self.block_indent;
409 let context = self.get_context();
410 ::items::format_struct(
420 ).map(|s| match *def {
421 ast::VariantData::Tuple(..) => s + ";",
425 self.push_rewrite(item.span, rewrite);
427 ast::ItemKind::Enum(ref def, ref generics) => {
428 self.format_missing_with_indent(source!(self, item.span).lo);
429 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
430 self.last_pos = source!(self, item.span).hi;
432 ast::ItemKind::Mod(ref module) => {
433 self.format_missing_with_indent(source!(self, item.span).lo);
434 self.format_mod(module, &item.vis, item.span, item.ident, &attrs);
436 ast::ItemKind::Mac(ref mac) => {
437 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
439 ast::ItemKind::ForeignMod(ref foreign_mod) => {
440 self.format_missing_with_indent(source!(self, item.span).lo);
441 self.format_foreign_mod(foreign_mod, item.span);
443 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
444 let rewrite = rewrite_static(
455 self.push_rewrite(item.span, rewrite);
457 ast::ItemKind::Const(ref ty, ref expr) => {
458 let rewrite = rewrite_static(
463 ast::Mutability::Immutable,
469 self.push_rewrite(item.span, rewrite);
471 ast::ItemKind::DefaultImpl(..) => {
472 // FIXME(#78): format impl definitions.
474 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
476 visit::FnKind::ItemFn(
488 ast::Defaultness::Final,
492 ast::ItemKind::Ty(ref ty, ref generics) => {
493 let rewrite = rewrite_type_alias(
502 self.push_rewrite(item.span, rewrite);
504 ast::ItemKind::Union(ref def, ref generics) => {
505 let rewrite = ::items::format_struct_struct(
516 self.push_rewrite(item.span, rewrite);
518 ast::ItemKind::GlobalAsm(..) => {
519 let snippet = Some(self.snippet(item.span));
520 self.push_rewrite(item.span, snippet);
522 ast::ItemKind::MacroDef(..) => {
523 // FIXME(#1539): macros 2.0
524 let snippet = Some(self.snippet(item.span));
525 self.push_rewrite(item.span, snippet);
530 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
531 skip_out_of_file_lines_range_visitor!(self, ti.span);
533 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
534 self.push_rewrite(ti.span, None);
539 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
540 let rewrite = rewrite_static(
542 &ast::Visibility::Inherited,
545 ast::Mutability::Immutable,
551 self.push_rewrite(ti.span, rewrite);
553 ast::TraitItemKind::Method(ref sig, None) => {
554 let indent = self.block_indent;
555 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
556 self.push_rewrite(ti.span, rewrite);
558 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
560 visit::FnKind::Method(ti.ident, sig, None, body),
564 ast::Defaultness::Final,
568 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
569 let rewrite = rewrite_associated_type(
571 type_default.as_ref(),
572 Some(type_param_bounds),
576 self.push_rewrite(ti.span, rewrite);
578 ast::TraitItemKind::Macro(ref mac) => {
579 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
584 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
585 skip_out_of_file_lines_range_visitor!(self, ii.span);
587 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
588 self.push_rewrite(ii.span, None);
593 ast::ImplItemKind::Method(ref sig, ref body) => {
595 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
603 ast::ImplItemKind::Const(ref ty, ref expr) => {
604 let rewrite = rewrite_static(
609 ast::Mutability::Immutable,
615 self.push_rewrite(ii.span, rewrite);
617 ast::ImplItemKind::Type(ref ty) => {
618 let rewrite = rewrite_associated_impl_type(
626 self.push_rewrite(ii.span, rewrite);
628 ast::ImplItemKind::Macro(ref mac) => {
629 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
634 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
635 skip_out_of_file_lines_range_visitor!(self, mac.span);
638 let shape = Shape::indented(self.block_indent, self.config)
641 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
642 self.push_rewrite(mac.span, rewrite);
645 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
646 self.format_missing_with_indent(source!(self, span).lo);
647 let result = rewrite.unwrap_or_else(|| self.snippet(span));
648 self.buffer.push_str(&result);
649 self.last_pos = source!(self, span).hi;
652 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
654 parse_session: parse_session,
655 codemap: parse_session.codemap(),
656 buffer: StringBuffer::new(),
657 last_pos: BytePos(0),
658 block_indent: Indent::empty(),
660 is_if_else_block: false,
664 pub fn snippet(&self, span: Span) -> String {
665 match self.codemap.span_to_snippet(span) {
669 "Couldn't make snippet for span {:?}->{:?}",
670 self.codemap.lookup_char_pos(span.lo),
671 self.codemap.lookup_char_pos(span.hi)
678 // Returns true if we should skip the following item.
679 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
680 if utils::contains_skip(attrs) {
684 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
685 if attrs.is_empty() {
689 let rewrite = attrs.rewrite(
691 Shape::indented(self.block_indent, self.config),
693 let span = mk_sp(attrs[0].span.lo, attrs[attrs.len() - 1].span.hi);
694 self.push_rewrite(span, rewrite);
701 items_left: &[ptr::P<ast::Item>],
706 F: Fn(&ast::Item) -> bool,
708 let mut last = self.codemap.lookup_line_range(items_left[0].span());
709 let item_length = items_left
712 is_item(&***ppi) && (!in_group || {
713 let current = self.codemap.lookup_line_range(ppi.span());
714 let in_same_group = current.lo < last.hi + 2;
720 let items = &items_left[..item_length];
722 let at_least_one_in_file_lines = items
724 .any(|item| !out_of_file_lines_range!(self, item.span));
726 if at_least_one_in_file_lines {
727 self.format_imports(items);
730 self.push_rewrite(item.span, None);
737 fn walk_mod_items(&mut self, m: &ast::Mod) {
738 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
739 while !items_left.is_empty() {
740 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
741 // to be potentially reordered within `format_imports`. Otherwise, just format the
742 // next item for output.
743 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
744 let used_items_len = self.reorder_items(
747 self.config.reorder_imports_in_group(),
749 let (_, rest) = items_left.split_at(used_items_len);
751 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
752 let used_items_len = self.reorder_items(
755 self.config.reorder_extern_crates_in_group(),
757 let (_, rest) = items_left.split_at(used_items_len);
760 // `unwrap()` is safe here because we know `items_left`
761 // has elements from the loop condition
762 let (item, rest) = items_left.split_first().unwrap();
763 self.visit_item(item);
772 vis: &ast::Visibility,
775 attrs: &[ast::Attribute],
777 // Decide whether this is an inline mod or an external mod.
778 let local_file_name = self.codemap.span_to_filename(s);
779 let inner_span = source!(self, m.inner);
780 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
781 local_file_name == self.codemap.span_to_filename(inner_span);
783 self.buffer.push_str(&*utils::format_visibility(vis));
784 self.buffer.push_str("mod ");
785 self.buffer.push_str(&ident.to_string());
788 match self.config.item_brace_style() {
789 BraceStyle::AlwaysNextLine => self.buffer
790 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
791 _ => self.buffer.push_str(" {"),
793 // Hackery to account for the closing }.
794 let mod_lo = self.codemap.span_after(source!(self, s), "{");
795 let body_snippet = self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
796 let body_snippet = body_snippet.trim();
797 if body_snippet.is_empty() {
798 self.buffer.push_str("}");
800 self.last_pos = mod_lo;
801 self.block_indent = self.block_indent.block_indent(self.config);
802 self.visit_attrs(attrs, ast::AttrStyle::Inner);
803 self.walk_mod_items(m);
804 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
805 self.close_block(false);
807 self.last_pos = source!(self, m.inner).hi;
809 self.buffer.push_str(";");
810 self.last_pos = source!(self, s).hi;
814 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
815 self.block_indent = Indent::empty();
816 self.walk_mod_items(m);
817 self.format_missing_with_indent(filemap.end_pos);
820 pub fn get_context(&self) -> RewriteContext {
822 parse_session: self.parse_session,
823 codemap: self.codemap,
827 is_if_else_block: false,
828 force_one_line_chain: false,
833 impl Rewrite for ast::NestedMetaItem {
834 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
836 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
837 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
842 impl Rewrite for ast::MetaItem {
843 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
844 Some(match self.node {
845 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
846 ast::MetaItemKind::List(ref list) => {
847 let name = self.name.as_str();
848 // 3 = `#[` and `(`, 2 = `]` and `)`
849 let item_shape = try_opt!(
851 .shrink_left(name.len() + 3)
852 .and_then(|s| s.sub_width(2))
854 let items = itemize_list(
858 |nested_meta_item| nested_meta_item.span.lo,
859 |nested_meta_item| nested_meta_item.span.hi,
860 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
865 let item_vec = items.collect::<Vec<_>>();
866 let fmt = ListFormatting {
867 tactic: DefinitiveListTactic::Mixed,
869 trailing_separator: SeparatorTactic::Never,
870 separator_place: SeparatorPlace::Back,
872 ends_with_newline: false,
873 preserve_newline: false,
874 config: context.config,
876 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
878 ast::MetaItemKind::NameValue(ref literal) => {
879 let name = self.name.as_str();
880 let value = context.snippet(literal.span);
881 if &*name == "doc" && contains_comment(&value) {
882 let doc_shape = Shape {
883 width: cmp::min(shape.width, context.config.comment_width())
884 .checked_sub(shape.indent.width())
890 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
893 format!("{} = {}", name, value)
900 impl Rewrite for ast::Attribute {
901 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
902 try_opt!(self.meta())
903 .rewrite(context, shape)
904 .map(|rw| if self.is_sugared_doc {
907 let original = context.snippet(self.span);
908 let prefix = match self.style {
909 ast::AttrStyle::Inner => "#!",
910 ast::AttrStyle::Outer => "#",
912 if contains_comment(&original) {
915 format!("{}[{}]", prefix, rw)
921 impl<'a> Rewrite for [ast::Attribute] {
922 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
924 return Some(String::new());
926 let mut result = String::with_capacity(128);
927 let indent = shape.indent.to_string(context.config);
929 let mut derive_args = Vec::new();
931 let mut iter = self.iter().enumerate().peekable();
932 let mut insert_new_line = true;
933 let mut is_prev_sugared_doc = false;
934 while let Some((i, a)) = iter.next() {
935 let a_str = try_opt!(a.rewrite(context, shape));
937 // Write comments and blank lines between attributes.
939 let comment = context.snippet(mk_sp(self[i - 1].span.hi, a.span.lo));
940 // This particular horror show is to preserve line breaks in between doc
941 // comments. An alternative would be to force such line breaks to start
942 // with the usual doc comment token.
943 let (multi_line_before, multi_line_after) = if a.is_sugared_doc ||
946 // Look at before and after comment and see if there are any empty lines.
947 let comment_begin = comment.chars().position(|c| c == '/');
948 let len = comment_begin.unwrap_or(comment.len());
949 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
950 let mla = if comment_begin.is_none() {
953 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
954 let len = comment_end.unwrap();
959 .filter(|c| *c == '\n')
967 let comment = try_opt!(recover_missing_comment_in_span(
968 mk_sp(self[i - 1].span.hi, a.span.lo),
969 shape.with_max_width(context.config),
974 if !comment.is_empty() {
975 if multi_line_before {
978 result.push_str(&comment);
980 if multi_line_after {
983 } else if insert_new_line {
985 if multi_line_after {
990 if derive_args.is_empty() {
991 result.push_str(&indent);
994 insert_new_line = true;
997 // Write the attribute itself.
998 if context.config.merge_derives() {
999 // If the attribute is `#[derive(...)]`, take the arguments.
1000 if let Some(mut args) = get_derive_args(context, a) {
1001 derive_args.append(&mut args);
1003 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
1004 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
1005 // If not, rewrite the merged derives.
1007 result.push_str(&format!("#[derive({})]", derive_args.join(", ")));
1008 derive_args.clear();
1012 result.push_str(&a_str);
1015 result.push_str(&a_str);
1018 is_prev_sugared_doc = a.is_sugared_doc;
1024 fn is_derive(attr: &ast::Attribute) -> bool {
1026 Some(meta_item) => match meta_item.node {
1027 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1034 /// Returns the arguments of `#[derive(...)]`.
1035 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1036 attr.meta().and_then(|meta_item| match meta_item.node {
1037 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1038 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1041 .map(|a| context.snippet(a.span))
1042 .collect::<Vec<_>>(),