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 expr::rewrite_literal;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices,
24 use comment::rewrite_comment;
25 use config::{BraceStyle, Config};
26 use items::{format_impl, format_struct, format_struct_struct, format_trait,
27 rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
29 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
31 use macros::{rewrite_macro, MacroPosition};
33 use rewrite::{Rewrite, RewriteContext};
34 use shape::{Indent, Shape};
35 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
37 fn is_use_item(item: &ast::Item) -> bool {
39 ast::ItemKind::Use(_) => true,
44 fn is_extern_crate(item: &ast::Item) -> bool {
46 ast::ItemKind::ExternCrate(..) => true,
51 pub struct FmtVisitor<'a> {
52 pub parse_session: &'a ParseSess,
53 pub codemap: &'a CodeMap,
54 pub buffer: StringBuffer,
55 pub last_pos: BytePos,
56 // FIXME: use an RAII util or closure for indenting
57 pub block_indent: Indent,
58 pub config: &'a Config,
59 pub is_if_else_block: bool,
62 impl<'a> FmtVisitor<'a> {
63 pub fn shape(&self) -> Shape {
64 Shape::indented(self.block_indent, self.config)
67 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
69 "visit_stmt: {:?} {:?}",
70 self.codemap.lookup_char_pos(stmt.span.lo()),
71 self.codemap.lookup_char_pos(stmt.span.hi())
75 ast::StmtKind::Item(ref item) => {
76 self.visit_item(item);
78 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
79 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
80 self.push_rewrite(stmt.span(), rewrite)
82 ast::StmtKind::Mac(ref mac) => {
83 let (ref mac, _macro_style, ref attrs) = **mac;
84 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
85 self.push_rewrite(stmt.span(), None);
87 self.visit_mac(mac, None, MacroPosition::Statement);
89 self.format_missing(stmt.span.hi());
94 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
96 "visit_block: {:?} {:?}",
97 self.codemap.lookup_char_pos(b.span.lo()),
98 self.codemap.lookup_char_pos(b.span.hi())
101 // Check if this block has braces.
102 let snippet = self.snippet(b.span);
103 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
104 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
106 self.last_pos = self.last_pos + brace_compensation;
107 self.block_indent = self.block_indent.block_indent(self.config);
108 self.buffer.push_str("{");
110 if self.config.remove_blank_lines_at_start_or_end_of_block() {
111 if let Some(first_stmt) = b.stmts.first() {
112 let attr_lo = inner_attrs
114 inner_attributes(attrs).first().map(|attr| attr.span.lo())
117 // Attributes for an item in a statement position
118 // do not belong to the statement. (rust-lang/rust#34459)
119 if let ast::StmtKind::Item(ref item) = first_stmt.node {
122 first_stmt.attrs().first()
124 // Some stmts can have embedded attributes.
125 // e.g. `match { #![attr] ... }`
126 let attr_lo = attr.span.lo();
127 if attr_lo < first_stmt.span.lo() {
135 let snippet = self.snippet(mk_sp(
137 attr_lo.unwrap_or(first_stmt.span.lo()),
139 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
140 |(kind, _, s)| if kind == CodeCharKind::Normal {
146 if let Some(len) = len {
147 self.last_pos = self.last_pos + BytePos::from_usize(len);
152 // Format inner attributes if available.
153 if let Some(attrs) = inner_attrs {
154 self.visit_attrs(attrs, ast::AttrStyle::Inner);
157 self.walk_block_stmts(b);
159 if !b.stmts.is_empty() {
160 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
161 if utils::semicolon_for_expr(&self.get_context(), expr) {
162 self.buffer.push_str(";");
167 let mut remove_len = BytePos(0);
168 if self.config.remove_blank_lines_at_start_or_end_of_block() {
169 if let Some(stmt) = b.stmts.last() {
170 let snippet = self.snippet(mk_sp(
172 source!(self, b.span).hi() - brace_compensation,
174 let len = CommentCodeSlices::new(&snippet)
176 .and_then(|(kind, _, s)| {
177 if kind == CodeCharKind::Normal && s.trim().is_empty() {
183 if let Some(len) = len {
184 remove_len = BytePos::from_usize(len);
189 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
190 if unindent_comment {
191 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
192 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
193 unindent_comment = snippet.contains("//") || snippet.contains("/*");
195 // FIXME: we should compress any newlines here to just one
196 if unindent_comment {
197 self.block_indent = self.block_indent.block_unindent(self.config);
199 self.format_missing_with_indent(
200 source!(self, b.span).hi() - brace_compensation - remove_len,
202 if unindent_comment {
203 self.block_indent = self.block_indent.block_indent(self.config);
205 self.close_block(unindent_comment);
206 self.last_pos = source!(self, b.span).hi();
209 // FIXME: this is a terrible hack to indent the comments between the last
210 // item in the block and the closing brace to the block's level.
211 // The closing brace itself, however, should be indented at a shallower
213 fn close_block(&mut self, unindent_comment: bool) {
214 let total_len = self.buffer.len;
215 let chars_too_many = if unindent_comment {
217 } else if self.config.hard_tabs() {
220 self.config.tab_spaces()
222 self.buffer.truncate(total_len - chars_too_many);
223 self.buffer.push_str("}");
224 self.block_indent = self.block_indent.block_unindent(self.config);
227 // Note that this only gets called for function definitions. Required methods
228 // on traits do not get handled here.
235 defaultness: ast::Defaultness,
236 inner_attrs: Option<&[ast::Attribute]>,
238 let indent = self.block_indent;
240 let rewrite = match fk {
241 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
253 mk_sp(s.lo(), b.span.lo()),
257 visit::FnKind::Method(ident, sig, vis, b) => {
268 vis.unwrap_or(&ast::Visibility::Inherited),
269 mk_sp(s.lo(), b.span.lo()),
273 visit::FnKind::Closure(_) => unreachable!(),
276 if let Some(fn_str) = rewrite {
277 self.format_missing_with_indent(source!(self, s).lo());
278 self.buffer.push_str(&fn_str);
279 if let Some(c) = fn_str.chars().last() {
281 self.last_pos = source!(self, block.span).hi();
286 self.format_missing(source!(self, block.span).lo());
289 self.last_pos = source!(self, block.span).lo();
290 self.visit_block(block, inner_attrs)
293 pub fn visit_item(&mut self, item: &ast::Item) {
294 skip_out_of_file_lines_range_visitor!(self, item.span);
296 // This is where we bail out if there is a skip attribute. This is only
297 // complex in the module case. It is complex because the module could be
298 // in a separate file and there might be attributes in both files, but
299 // the AST lumps them all together.
301 let mut attrs = &item.attrs;
303 ast::ItemKind::Mod(ref m) => {
304 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
305 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
306 if outer_file.name == inner_file.name {
307 // Module is inline, in this case we treat modules like any
309 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
310 self.push_rewrite(item.span, None);
313 } else if contains_skip(&item.attrs) {
314 // Module is not inline, but should be skipped.
317 // Module is not inline and should not be skipped. We want
318 // to process only the attributes in the current file.
319 filterd_attrs = item.attrs
322 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
323 if attr_file.name == outer_file.name {
329 .collect::<Vec<_>>();
330 // Assert because if we should skip it should be caught by
332 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
333 attrs = &filterd_attrs;
336 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
337 self.push_rewrite(item.span, None);
343 ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
344 ast::ItemKind::Impl(..) => {
345 let snippet = self.snippet(item.span);
346 let where_span_end = snippet
347 .find_uncommented("{")
348 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
349 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
350 self.push_rewrite(item.span, rw);
352 ast::ItemKind::Trait(..) => {
353 let rw = format_trait(&self.get_context(), item, self.block_indent);
354 self.push_rewrite(item.span, rw);
356 ast::ItemKind::ExternCrate(_) => {
357 let rw = rewrite_extern_crate(&self.get_context(), item);
358 self.push_rewrite(item.span, rw);
360 ast::ItemKind::Struct(ref def, ref generics) => {
361 let rewrite = format_struct(
371 ).map(|s| match *def {
372 ast::VariantData::Tuple(..) => s + ";",
375 self.push_rewrite(item.span, rewrite);
377 ast::ItemKind::Enum(ref def, ref generics) => {
378 self.format_missing_with_indent(source!(self, item.span).lo());
379 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
380 self.last_pos = source!(self, item.span).hi();
382 ast::ItemKind::Mod(ref module) => {
383 self.format_missing_with_indent(source!(self, item.span).lo());
384 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
386 ast::ItemKind::Mac(ref mac) => {
387 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
389 ast::ItemKind::ForeignMod(ref foreign_mod) => {
390 self.format_missing_with_indent(source!(self, item.span).lo());
391 self.format_foreign_mod(foreign_mod, item.span);
393 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
394 let rewrite = rewrite_static(
405 self.push_rewrite(item.span, rewrite);
407 ast::ItemKind::Const(ref ty, ref expr) => {
408 let rewrite = rewrite_static(
413 ast::Mutability::Immutable,
419 self.push_rewrite(item.span, rewrite);
421 ast::ItemKind::DefaultImpl(..) => {
422 // FIXME(#78): format impl definitions.
424 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
426 visit::FnKind::ItemFn(
438 ast::Defaultness::Final,
442 ast::ItemKind::Ty(ref ty, ref generics) => {
443 let rewrite = rewrite_type_alias(
452 self.push_rewrite(item.span, rewrite);
454 ast::ItemKind::Union(ref def, ref generics) => {
455 let rewrite = format_struct_struct(
466 self.push_rewrite(item.span, rewrite);
468 ast::ItemKind::GlobalAsm(..) => {
469 let snippet = Some(self.snippet(item.span));
470 self.push_rewrite(item.span, snippet);
472 ast::ItemKind::MacroDef(..) => {
473 // FIXME(#1539): macros 2.0
474 let mac_snippet = Some(self.snippet(item.span));
475 self.push_rewrite(item.span, mac_snippet);
480 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
481 skip_out_of_file_lines_range_visitor!(self, ti.span);
483 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
484 self.push_rewrite(ti.span, None);
489 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
490 let rewrite = rewrite_static(
492 &ast::Visibility::Inherited,
495 ast::Mutability::Immutable,
501 self.push_rewrite(ti.span, rewrite);
503 ast::TraitItemKind::Method(ref sig, None) => {
504 let indent = self.block_indent;
505 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
506 self.push_rewrite(ti.span, rewrite);
508 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
510 visit::FnKind::Method(ti.ident, sig, None, body),
514 ast::Defaultness::Final,
518 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
519 let rewrite = rewrite_associated_type(
521 type_default.as_ref(),
522 Some(type_param_bounds),
526 self.push_rewrite(ti.span, rewrite);
528 ast::TraitItemKind::Macro(ref mac) => {
529 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
534 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
535 skip_out_of_file_lines_range_visitor!(self, ii.span);
537 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
538 self.push_rewrite(ii.span, None);
543 ast::ImplItemKind::Method(ref sig, ref body) => {
545 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
553 ast::ImplItemKind::Const(ref ty, ref expr) => {
554 let rewrite = rewrite_static(
559 ast::Mutability::Immutable,
565 self.push_rewrite(ii.span, rewrite);
567 ast::ImplItemKind::Type(ref ty) => {
568 let rewrite = rewrite_associated_impl_type(
576 self.push_rewrite(ii.span, rewrite);
578 ast::ImplItemKind::Macro(ref mac) => {
579 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
584 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
585 skip_out_of_file_lines_range_visitor!(self, mac.span);
588 let shape = self.shape().sub_width(1).unwrap();
589 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
590 self.push_rewrite(mac.span, rewrite);
593 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
594 self.format_missing_with_indent(source!(self, span).lo());
595 let result = rewrite.unwrap_or_else(|| self.snippet(span));
596 self.buffer.push_str(&result);
597 self.last_pos = source!(self, span).hi();
600 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
602 parse_session: parse_session,
603 codemap: parse_session.codemap(),
604 buffer: StringBuffer::new(),
605 last_pos: BytePos(0),
606 block_indent: Indent::empty(),
608 is_if_else_block: false,
612 pub fn snippet(&self, span: Span) -> String {
613 match self.codemap.span_to_snippet(span) {
617 "Couldn't make snippet for span {:?}->{:?}",
618 self.codemap.lookup_char_pos(span.lo()),
619 self.codemap.lookup_char_pos(span.hi())
626 // Returns true if we should skip the following item.
627 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
628 if contains_skip(attrs) {
632 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
633 if attrs.is_empty() {
637 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
638 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
639 self.push_rewrite(span, rewrite);
644 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
646 F: Fn(&ast::Item) -> bool,
648 let mut last = self.codemap.lookup_line_range(items_left[0].span());
649 let item_length = items_left
652 is_item(&***ppi) && (!in_group || {
653 let current = self.codemap.lookup_line_range(ppi.span());
654 let in_same_group = current.lo < last.hi + 2;
660 let items = &items_left[..item_length];
662 let at_least_one_in_file_lines = items
664 .any(|item| !out_of_file_lines_range!(self, item.span));
666 if at_least_one_in_file_lines {
667 self.format_imports(items);
670 self.push_rewrite(item.span, None);
677 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
678 while !items_left.is_empty() {
679 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
680 // to be potentially reordered within `format_imports`. Otherwise, just format the
681 // next item for output.
682 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
683 let used_items_len = self.reorder_items(
686 self.config.reorder_imports_in_group(),
688 let (_, rest) = items_left.split_at(used_items_len);
690 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
691 let used_items_len = self.reorder_items(
694 self.config.reorder_extern_crates_in_group(),
696 let (_, rest) = items_left.split_at(used_items_len);
699 // `unwrap()` is safe here because we know `items_left`
700 // has elements from the loop condition
701 let (item, rest) = items_left.split_first().unwrap();
702 self.visit_item(item);
708 fn walk_mod_items(&mut self, m: &ast::Mod) {
709 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
712 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
713 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
715 ast::StmtKind::Item(ref item) => Some(&**item),
720 if stmts.is_empty() {
724 // Extract leading `use ...;`.
725 let items: Vec<_> = stmts
727 .take_while(|stmt| to_stmt_item(stmt).is_some())
728 .filter_map(|stmt| to_stmt_item(stmt))
729 .take_while(|item| is_use_item(item))
732 if items.is_empty() {
733 self.visit_stmt(&stmts[0]);
734 self.walk_stmts(&stmts[1..]);
736 self.walk_items(&items);
737 self.walk_stmts(&stmts[items.len()..]);
741 fn walk_block_stmts(&mut self, b: &ast::Block) {
742 self.walk_stmts(&b.stmts)
748 vis: &ast::Visibility,
751 attrs: &[ast::Attribute],
753 // Decide whether this is an inline mod or an external mod.
754 let local_file_name = self.codemap.span_to_filename(s);
755 let inner_span = source!(self, m.inner);
756 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
757 && local_file_name == self.codemap.span_to_filename(inner_span);
759 self.buffer.push_str(&*utils::format_visibility(vis));
760 self.buffer.push_str("mod ");
761 self.buffer.push_str(&ident.to_string());
764 match self.config.item_brace_style() {
765 BraceStyle::AlwaysNextLine => self.buffer
766 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
767 _ => self.buffer.push_str(" {"),
769 // Hackery to account for the closing }.
770 let mod_lo = self.codemap.span_after(source!(self, s), "{");
772 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
773 let body_snippet = body_snippet.trim();
774 if body_snippet.is_empty() {
775 self.buffer.push_str("}");
777 self.last_pos = mod_lo;
778 self.block_indent = self.block_indent.block_indent(self.config);
779 self.visit_attrs(attrs, ast::AttrStyle::Inner);
780 self.walk_mod_items(m);
781 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
782 self.close_block(false);
784 self.last_pos = source!(self, m.inner).hi();
786 self.buffer.push_str(";");
787 self.last_pos = source!(self, s).hi();
791 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
792 self.block_indent = Indent::empty();
793 self.walk_mod_items(m);
794 self.format_missing_with_indent(filemap.end_pos);
797 pub fn get_context(&self) -> RewriteContext {
799 parse_session: self.parse_session,
800 codemap: self.codemap,
804 is_if_else_block: false,
805 force_one_line_chain: false,
810 impl Rewrite for ast::NestedMetaItem {
811 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
813 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
814 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
819 impl Rewrite for ast::MetaItem {
820 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
821 Some(match self.node {
822 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
823 ast::MetaItemKind::List(ref list) => {
824 let name = self.name.as_str();
825 // 3 = `#[` and `(`, 2 = `]` and `)`
826 let item_shape = try_opt!(
828 .shrink_left(name.len() + 3)
829 .and_then(|s| s.sub_width(2))
831 let items = itemize_list(
835 |nested_meta_item| nested_meta_item.span.lo(),
836 |nested_meta_item| nested_meta_item.span.hi(),
837 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
842 let item_vec = items.collect::<Vec<_>>();
843 let fmt = ListFormatting {
844 tactic: DefinitiveListTactic::Mixed,
846 trailing_separator: SeparatorTactic::Never,
847 separator_place: SeparatorPlace::Back,
849 ends_with_newline: false,
850 preserve_newline: false,
851 config: context.config,
853 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
855 ast::MetaItemKind::NameValue(ref literal) => {
856 let name = self.name.as_str();
857 let value = context.snippet(literal.span);
858 if &*name == "doc" && contains_comment(&value) {
859 let doc_shape = Shape {
860 width: cmp::min(shape.width, context.config.comment_width())
861 .checked_sub(shape.indent.width())
865 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
867 format!("{} = {}", name, value)
874 impl Rewrite for ast::Attribute {
875 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
876 try_opt!(self.meta())
877 .rewrite(context, shape)
878 .map(|rw| if self.is_sugared_doc {
881 let original = context.snippet(self.span);
882 let prefix = match self.style {
883 ast::AttrStyle::Inner => "#!",
884 ast::AttrStyle::Outer => "#",
886 if contains_comment(&original) {
889 format!("{}[{}]", prefix, rw)
895 impl<'a> Rewrite for [ast::Attribute] {
896 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
898 return Some(String::new());
900 let mut result = String::with_capacity(128);
901 let indent = shape.indent.to_string(context.config);
903 let mut derive_args = Vec::new();
905 let mut iter = self.iter().enumerate().peekable();
906 let mut insert_new_line = true;
907 let mut is_prev_sugared_doc = false;
908 while let Some((i, a)) = iter.next() {
909 let a_str = try_opt!(a.rewrite(context, shape));
911 // Write comments and blank lines between attributes.
913 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
914 // This particular horror show is to preserve line breaks in between doc
915 // comments. An alternative would be to force such line breaks to start
916 // with the usual doc comment token.
917 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
918 || is_prev_sugared_doc
920 // Look at before and after comment and see if there are any empty lines.
921 let comment_begin = comment.chars().position(|c| c == '/');
922 let len = comment_begin.unwrap_or_else(|| comment.len());
923 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
924 let mla = if comment_begin.is_none() {
927 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
928 let len = comment_end.unwrap();
933 .filter(|c| *c == '\n')
941 let comment = try_opt!(recover_missing_comment_in_span(
942 mk_sp(self[i - 1].span.hi(), a.span.lo()),
943 shape.with_max_width(context.config),
948 if !comment.is_empty() {
949 if multi_line_before {
952 result.push_str(&comment);
954 if multi_line_after {
957 } else if insert_new_line {
959 if multi_line_after {
964 if derive_args.is_empty() {
965 result.push_str(&indent);
968 insert_new_line = true;
971 // Write the attribute itself.
972 if context.config.merge_derives() {
973 // If the attribute is `#[derive(...)]`, take the arguments.
974 if let Some(mut args) = get_derive_args(context, a) {
975 derive_args.append(&mut args);
977 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
978 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
979 // If not, rewrite the merged derives.
981 result.push_str(&try_opt!(format_derive(context, &derive_args, shape)));
986 result.push_str(&a_str);
989 result.push_str(&a_str);
992 is_prev_sugared_doc = a.is_sugared_doc;
998 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
999 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
1000 let mut result = String::with_capacity(128);
1001 result.push_str("#[derive(");
1002 // 11 = `#[derive()]`
1003 let initial_budget = try_opt!(shape.width.checked_sub(11));
1004 let mut budget = initial_budget;
1005 let num = derive_args.len();
1006 for (i, a) in derive_args.iter().enumerate() {
1008 let width = a.len() + 2;
1011 // Remove trailing whitespace.
1016 result.push_str(&(shape.indent + 9).to_string(context.config));
1017 budget = initial_budget;
1019 budget = budget.checked_sub(width).unwrap_or(0);
1023 result.push_str(", ")
1026 result.push_str(")]");
1030 fn is_derive(attr: &ast::Attribute) -> bool {
1032 Some(meta_item) => match meta_item.node {
1033 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1040 /// Returns the arguments of `#[derive(...)]`.
1041 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1042 attr.meta().and_then(|meta_item| match meta_item.node {
1043 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1044 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1047 .map(|a| context.snippet(a.span))
1048 .collect::<Vec<_>>(),
1055 // Rewrite `extern crate foo;` WITHOUT attributes.
1056 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1057 assert!(is_extern_crate(item));
1058 let new_str = context.snippet(item.span);
1059 Some(if contains_comment(&new_str) {
1062 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1063 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))