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 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(ref local) => {
77 let rewrite = if contains_skip(&local.attrs) {
82 Shape::indented(self.block_indent, self.config),
85 self.push_rewrite(stmt.span, rewrite);
87 ast::StmtKind::Expr(ref expr) => {
88 let rewrite = format_expr(
92 Shape::indented(self.block_indent, self.config),
94 let span = if expr.attrs.is_empty() {
97 mk_sp(expr.span().lo, stmt.span.hi)
99 self.push_rewrite(span, rewrite)
101 ast::StmtKind::Semi(ref expr) => {
102 let rewrite = stmt.rewrite(
104 Shape::indented(self.block_indent, self.config),
106 let span = if expr.attrs.is_empty() {
109 mk_sp(expr.span().lo, stmt.span.hi)
111 self.push_rewrite(span, rewrite)
113 ast::StmtKind::Mac(ref mac) => {
114 let (ref mac, _macro_style, ref attrs) = **mac;
115 if contains_skip(attrs) {
116 self.push_rewrite(mac.span, None);
118 self.visit_mac(mac, None, MacroPosition::Statement);
120 self.format_missing(stmt.span.hi);
125 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
127 "visit_block: {:?} {:?}",
128 self.codemap.lookup_char_pos(b.span.lo),
129 self.codemap.lookup_char_pos(b.span.hi)
132 // Check if this block has braces.
133 let snippet = self.snippet(b.span);
134 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
135 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
137 self.last_pos = self.last_pos + brace_compensation;
138 self.block_indent = self.block_indent.block_indent(self.config);
139 self.buffer.push_str("{");
141 if self.config.remove_blank_lines_at_start_or_end_of_block() {
142 if let Some(first_stmt) = b.stmts.first() {
143 let attr_lo = inner_attrs
145 inner_attributes(attrs).first().map(|attr| attr.span.lo)
148 // Attributes for an item in a statement position
149 // do not belong to the statement. (rust-lang/rust#34459)
150 if let ast::StmtKind::Item(ref item) = first_stmt.node {
153 first_stmt.attrs().first()
155 // Some stmts can have embedded attributes.
156 // e.g. `match { #![attr] ... }`
157 let attr_lo = attr.span.lo;
158 if attr_lo < first_stmt.span.lo {
167 self.snippet(mk_sp(self.last_pos, attr_lo.unwrap_or(first_stmt.span.lo)));
168 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
169 |(kind, _, s)| if kind == CodeCharKind::Normal {
175 if let Some(len) = len {
176 self.last_pos = self.last_pos + BytePos::from_usize(len);
181 // Format inner attributes if available.
182 if let Some(attrs) = inner_attrs {
183 self.visit_attrs(attrs, ast::AttrStyle::Inner);
186 for stmt in &b.stmts {
187 self.visit_stmt(stmt)
190 if !b.stmts.is_empty() {
191 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
192 if utils::semicolon_for_expr(&self.get_context(), expr) {
193 self.buffer.push_str(";");
198 let mut remove_len = BytePos(0);
199 if self.config.remove_blank_lines_at_start_or_end_of_block() {
200 if let Some(stmt) = b.stmts.last() {
201 let snippet = self.snippet(mk_sp(
203 source!(self, b.span).hi - brace_compensation,
205 let len = CommentCodeSlices::new(&snippet)
207 .and_then(|(kind, _, s)| {
208 if kind == CodeCharKind::Normal && s.trim().is_empty() {
214 if let Some(len) = len {
215 remove_len = BytePos::from_usize(len);
220 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
221 if unindent_comment {
222 let end_pos = source!(self, b.span).hi - brace_compensation - remove_len;
223 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
224 unindent_comment = snippet.contains("//") || snippet.contains("/*");
226 // FIXME: we should compress any newlines here to just one
227 if unindent_comment {
228 self.block_indent = self.block_indent.block_unindent(self.config);
230 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation - remove_len);
231 if unindent_comment {
232 self.block_indent = self.block_indent.block_indent(self.config);
234 self.close_block(unindent_comment);
235 self.last_pos = source!(self, b.span).hi;
238 // FIXME: this is a terrible hack to indent the comments between the last
239 // item in the block and the closing brace to the block's level.
240 // The closing brace itself, however, should be indented at a shallower
242 fn close_block(&mut self, unindent_comment: bool) {
243 let total_len = self.buffer.len;
244 let chars_too_many = if unindent_comment {
246 } else if self.config.hard_tabs() {
249 self.config.tab_spaces()
251 self.buffer.truncate(total_len - chars_too_many);
252 self.buffer.push_str("}");
253 self.block_indent = self.block_indent.block_unindent(self.config);
256 // Note that this only gets called for function definitions. Required methods
257 // on traits do not get handled here.
264 defaultness: ast::Defaultness,
265 inner_attrs: Option<&[ast::Attribute]>,
267 let indent = self.block_indent;
269 let rewrite = match fk {
270 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
282 mk_sp(s.lo, b.span.lo),
286 visit::FnKind::Method(ident, sig, vis, b) => {
297 vis.unwrap_or(&ast::Visibility::Inherited),
298 mk_sp(s.lo, b.span.lo),
302 visit::FnKind::Closure(_) => unreachable!(),
305 if let Some(fn_str) = rewrite {
306 self.format_missing_with_indent(source!(self, s).lo);
307 self.buffer.push_str(&fn_str);
308 if let Some(c) = fn_str.chars().last() {
310 self.last_pos = source!(self, block.span).hi;
315 self.format_missing(source!(self, block.span).lo);
318 self.last_pos = source!(self, block.span).lo;
319 self.visit_block(block, inner_attrs)
322 pub fn visit_item(&mut self, item: &ast::Item) {
323 skip_out_of_file_lines_range_visitor!(self, item.span);
325 // This is where we bail out if there is a skip attribute. This is only
326 // complex in the module case. It is complex because the module could be
327 // in a separate file and there might be attributes in both files, but
328 // the AST lumps them all together.
329 let mut attrs = item.attrs.clone();
331 ast::ItemKind::Mod(ref m) => {
332 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
333 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
334 if outer_file.name == inner_file.name {
335 // Module is inline, in this case we treat modules like any
337 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
338 self.push_rewrite(item.span, None);
341 } else if contains_skip(&item.attrs) {
342 // Module is not inline, but should be skipped.
345 // Module is not inline and should not be skipped. We want
346 // to process only the attributes in the current file.
347 let filterd_attrs = item.attrs
350 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
351 if attr_file.name == outer_file.name {
357 .collect::<Vec<_>>();
358 // Assert because if we should skip it should be caught by
360 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
361 attrs = filterd_attrs;
364 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
365 self.push_rewrite(item.span, None);
371 ast::ItemKind::Use(ref vp) => {
372 self.format_import(&item.vis, vp, item.span, &item.attrs);
374 ast::ItemKind::Impl(..) => {
375 self.format_missing_with_indent(source!(self, item.span).lo);
376 let snippet = self.snippet(item.span);
377 let where_span_end = snippet
378 .find_uncommented("{")
379 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo);
380 if let Some(impl_str) =
381 format_impl(&self.get_context(), item, self.block_indent, where_span_end)
383 self.buffer.push_str(&impl_str);
384 self.last_pos = source!(self, item.span).hi;
387 ast::ItemKind::Trait(..) => {
388 self.format_missing_with_indent(item.span.lo);
389 if let Some(trait_str) = format_trait(&self.get_context(), item, self.block_indent)
391 self.buffer.push_str(&trait_str);
392 self.last_pos = source!(self, item.span).hi;
395 ast::ItemKind::ExternCrate(_) => {
396 self.format_missing_with_indent(source!(self, item.span).lo);
397 let new_str = self.snippet(item.span);
398 if contains_comment(&new_str) {
399 self.buffer.push_str(&new_str)
402 &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
404 .push_str(&Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"));
406 self.last_pos = source!(self, item.span).hi;
408 ast::ItemKind::Struct(ref def, ref generics) => {
410 let indent = self.block_indent;
411 let context = self.get_context();
412 ::items::format_struct(
422 ).map(|s| match *def {
423 ast::VariantData::Tuple(..) => s + ";",
427 self.push_rewrite(item.span, rewrite);
429 ast::ItemKind::Enum(ref def, ref generics) => {
430 self.format_missing_with_indent(source!(self, item.span).lo);
431 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
432 self.last_pos = source!(self, item.span).hi;
434 ast::ItemKind::Mod(ref module) => {
435 self.format_missing_with_indent(source!(self, item.span).lo);
436 self.format_mod(module, &item.vis, item.span, item.ident, &attrs);
438 ast::ItemKind::Mac(ref mac) => {
439 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
441 ast::ItemKind::ForeignMod(ref foreign_mod) => {
442 self.format_missing_with_indent(source!(self, item.span).lo);
443 self.format_foreign_mod(foreign_mod, item.span);
445 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
446 let rewrite = rewrite_static(
457 self.push_rewrite(item.span, rewrite);
459 ast::ItemKind::Const(ref ty, ref expr) => {
460 let rewrite = rewrite_static(
465 ast::Mutability::Immutable,
471 self.push_rewrite(item.span, rewrite);
473 ast::ItemKind::DefaultImpl(..) => {
474 // FIXME(#78): format impl definitions.
476 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
478 visit::FnKind::ItemFn(
490 ast::Defaultness::Final,
494 ast::ItemKind::Ty(ref ty, ref generics) => {
495 let rewrite = rewrite_type_alias(
504 self.push_rewrite(item.span, rewrite);
506 ast::ItemKind::Union(ref def, ref generics) => {
507 let rewrite = ::items::format_struct_struct(
518 self.push_rewrite(item.span, rewrite);
520 ast::ItemKind::GlobalAsm(..) => {
521 let snippet = Some(self.snippet(item.span));
522 self.push_rewrite(item.span, snippet);
524 ast::ItemKind::MacroDef(..) => {
525 // FIXME(#1539): macros 2.0
526 let snippet = Some(self.snippet(item.span));
527 self.push_rewrite(item.span, snippet);
532 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
533 skip_out_of_file_lines_range_visitor!(self, ti.span);
535 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
536 self.push_rewrite(ti.span, None);
541 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
542 let rewrite = rewrite_static(
544 &ast::Visibility::Inherited,
547 ast::Mutability::Immutable,
553 self.push_rewrite(ti.span, rewrite);
555 ast::TraitItemKind::Method(ref sig, None) => {
556 let indent = self.block_indent;
557 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
558 self.push_rewrite(ti.span, rewrite);
560 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
562 visit::FnKind::Method(ti.ident, sig, None, body),
566 ast::Defaultness::Final,
570 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
571 let rewrite = rewrite_associated_type(
573 type_default.as_ref(),
574 Some(type_param_bounds),
578 self.push_rewrite(ti.span, rewrite);
580 ast::TraitItemKind::Macro(ref mac) => {
581 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
586 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
587 skip_out_of_file_lines_range_visitor!(self, ii.span);
589 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
590 self.push_rewrite(ii.span, None);
595 ast::ImplItemKind::Method(ref sig, ref body) => {
597 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
605 ast::ImplItemKind::Const(ref ty, ref expr) => {
606 let rewrite = rewrite_static(
611 ast::Mutability::Immutable,
617 self.push_rewrite(ii.span, rewrite);
619 ast::ImplItemKind::Type(ref ty) => {
620 let rewrite = rewrite_associated_impl_type(
628 self.push_rewrite(ii.span, rewrite);
630 ast::ImplItemKind::Macro(ref mac) => {
631 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
636 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
637 skip_out_of_file_lines_range_visitor!(self, mac.span);
640 let shape = self.shape().sub_width(1).unwrap();
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 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(&self.get_context(), self.shape());
690 let span = mk_sp(attrs[0].span.lo, attrs[attrs.len() - 1].span.hi);
691 self.push_rewrite(span, rewrite);
698 items_left: &[ptr::P<ast::Item>],
703 F: Fn(&ast::Item) -> bool,
705 let mut last = self.codemap.lookup_line_range(items_left[0].span());
706 let item_length = items_left
709 is_item(&***ppi) && (!in_group || {
710 let current = self.codemap.lookup_line_range(ppi.span());
711 let in_same_group = current.lo < last.hi + 2;
717 let items = &items_left[..item_length];
719 let at_least_one_in_file_lines = items
721 .any(|item| !out_of_file_lines_range!(self, item.span));
723 if at_least_one_in_file_lines {
724 self.format_imports(items);
727 self.push_rewrite(item.span, None);
734 fn walk_mod_items(&mut self, m: &ast::Mod) {
735 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
736 while !items_left.is_empty() {
737 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
738 // to be potentially reordered within `format_imports`. Otherwise, just format the
739 // next item for output.
740 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
741 let used_items_len = self.reorder_items(
744 self.config.reorder_imports_in_group(),
746 let (_, rest) = items_left.split_at(used_items_len);
748 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
749 let used_items_len = self.reorder_items(
752 self.config.reorder_extern_crates_in_group(),
754 let (_, rest) = items_left.split_at(used_items_len);
757 // `unwrap()` is safe here because we know `items_left`
758 // has elements from the loop condition
759 let (item, rest) = items_left.split_first().unwrap();
760 self.visit_item(item);
769 vis: &ast::Visibility,
772 attrs: &[ast::Attribute],
774 // Decide whether this is an inline mod or an external mod.
775 let local_file_name = self.codemap.span_to_filename(s);
776 let inner_span = source!(self, m.inner);
777 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
778 local_file_name == self.codemap.span_to_filename(inner_span);
780 self.buffer.push_str(&*utils::format_visibility(vis));
781 self.buffer.push_str("mod ");
782 self.buffer.push_str(&ident.to_string());
785 match self.config.item_brace_style() {
786 BraceStyle::AlwaysNextLine => self.buffer
787 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
788 _ => self.buffer.push_str(" {"),
790 // Hackery to account for the closing }.
791 let mod_lo = self.codemap.span_after(source!(self, s), "{");
792 let body_snippet = self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
793 let body_snippet = body_snippet.trim();
794 if body_snippet.is_empty() {
795 self.buffer.push_str("}");
797 self.last_pos = mod_lo;
798 self.block_indent = self.block_indent.block_indent(self.config);
799 self.visit_attrs(attrs, ast::AttrStyle::Inner);
800 self.walk_mod_items(m);
801 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
802 self.close_block(false);
804 self.last_pos = source!(self, m.inner).hi;
806 self.buffer.push_str(";");
807 self.last_pos = source!(self, s).hi;
811 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
812 self.block_indent = Indent::empty();
813 self.walk_mod_items(m);
814 self.format_missing_with_indent(filemap.end_pos);
817 pub fn get_context(&self) -> RewriteContext {
819 parse_session: self.parse_session,
820 codemap: self.codemap,
824 is_if_else_block: false,
825 force_one_line_chain: false,
830 impl Rewrite for ast::NestedMetaItem {
831 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
833 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
834 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
839 impl Rewrite for ast::MetaItem {
840 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
841 Some(match self.node {
842 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
843 ast::MetaItemKind::List(ref list) => {
844 let name = self.name.as_str();
845 // 3 = `#[` and `(`, 2 = `]` and `)`
846 let item_shape = try_opt!(
848 .shrink_left(name.len() + 3)
849 .and_then(|s| s.sub_width(2))
851 let items = itemize_list(
855 |nested_meta_item| nested_meta_item.span.lo,
856 |nested_meta_item| nested_meta_item.span.hi,
857 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
862 let item_vec = items.collect::<Vec<_>>();
863 let fmt = ListFormatting {
864 tactic: DefinitiveListTactic::Mixed,
866 trailing_separator: SeparatorTactic::Never,
867 separator_place: SeparatorPlace::Back,
869 ends_with_newline: false,
870 preserve_newline: false,
871 config: context.config,
873 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
875 ast::MetaItemKind::NameValue(ref literal) => {
876 let name = self.name.as_str();
877 let value = context.snippet(literal.span);
878 if &*name == "doc" && contains_comment(&value) {
879 let doc_shape = Shape {
880 width: cmp::min(shape.width, context.config.comment_width())
881 .checked_sub(shape.indent.width())
887 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
890 format!("{} = {}", name, value)
897 impl Rewrite for ast::Attribute {
898 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
899 try_opt!(self.meta())
900 .rewrite(context, shape)
901 .map(|rw| if self.is_sugared_doc {
904 let original = context.snippet(self.span);
905 let prefix = match self.style {
906 ast::AttrStyle::Inner => "#!",
907 ast::AttrStyle::Outer => "#",
909 if contains_comment(&original) {
912 format!("{}[{}]", prefix, rw)
918 impl<'a> Rewrite for [ast::Attribute] {
919 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
921 return Some(String::new());
923 let mut result = String::with_capacity(128);
924 let indent = shape.indent.to_string(context.config);
926 let mut derive_args = Vec::new();
928 let mut iter = self.iter().enumerate().peekable();
929 let mut insert_new_line = true;
930 let mut is_prev_sugared_doc = false;
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_before, multi_line_after) = if a.is_sugared_doc ||
943 // Look at before and after comment and see if there are any empty lines.
944 let comment_begin = comment.chars().position(|c| c == '/');
945 let len = comment_begin.unwrap_or(comment.len());
946 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
947 let mla = if comment_begin.is_none() {
950 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
951 let len = comment_end.unwrap();
956 .filter(|c| *c == '\n')
964 let comment = try_opt!(recover_missing_comment_in_span(
965 mk_sp(self[i - 1].span.hi, a.span.lo),
966 shape.with_max_width(context.config),
971 if !comment.is_empty() {
972 if multi_line_before {
975 result.push_str(&comment);
977 if multi_line_after {
980 } else if insert_new_line {
982 if multi_line_after {
987 if derive_args.is_empty() {
988 result.push_str(&indent);
991 insert_new_line = true;
994 // Write the attribute itself.
995 if context.config.merge_derives() {
996 // If the attribute is `#[derive(...)]`, take the arguments.
997 if let Some(mut args) = get_derive_args(context, a) {
998 derive_args.append(&mut args);
1000 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
1001 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
1002 // If not, rewrite the merged derives.
1004 result.push_str(&format!("#[derive({})]", derive_args.join(", ")));
1005 derive_args.clear();
1009 result.push_str(&a_str);
1012 result.push_str(&a_str);
1015 is_prev_sugared_doc = a.is_sugared_doc;
1021 fn is_derive(attr: &ast::Attribute) -> bool {
1023 Some(meta_item) => match meta_item.node {
1024 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1031 /// Returns the arguments of `#[derive(...)]`.
1032 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1033 attr.meta().and_then(|meta_item| match meta_item.node {
1034 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1035 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1038 .map(|a| context.snippet(a.span))
1039 .collect::<Vec<_>>(),