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, remove_trailing_white_spaces,
23 CodeCharKind, CommentCodeSlices, FindUncommented};
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,
28 rewrite_type_alias, FnSig};
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 let skip_rewrite = if let Some(attrs) = inner_attrs {
154 self.visit_attrs(attrs, ast::AttrStyle::Inner)
160 self.push_rewrite(b.span, None);
161 self.close_block(false);
162 self.last_pos = source!(self, b.span).hi();
166 self.walk_block_stmts(b);
168 if !b.stmts.is_empty() {
169 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
170 if utils::semicolon_for_expr(&self.get_context(), expr) {
171 self.buffer.push_str(";");
176 let mut remove_len = BytePos(0);
177 if self.config.remove_blank_lines_at_start_or_end_of_block() {
178 if let Some(stmt) = b.stmts.last() {
179 let snippet = self.snippet(mk_sp(
181 source!(self, b.span).hi() - brace_compensation,
183 let len = CommentCodeSlices::new(&snippet)
185 .and_then(|(kind, _, s)| {
186 if kind == CodeCharKind::Normal && s.trim().is_empty() {
192 if let Some(len) = len {
193 remove_len = BytePos::from_usize(len);
198 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
199 if unindent_comment {
200 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
201 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
202 unindent_comment = snippet.contains("//") || snippet.contains("/*");
204 // FIXME: we should compress any newlines here to just one
205 if unindent_comment {
206 self.block_indent = self.block_indent.block_unindent(self.config);
208 self.format_missing_with_indent(
209 source!(self, b.span).hi() - brace_compensation - remove_len,
211 if unindent_comment {
212 self.block_indent = self.block_indent.block_indent(self.config);
214 self.close_block(unindent_comment);
215 self.last_pos = source!(self, b.span).hi();
218 // FIXME: this is a terrible hack to indent the comments between the last
219 // item in the block and the closing brace to the block's level.
220 // The closing brace itself, however, should be indented at a shallower
222 fn close_block(&mut self, unindent_comment: bool) {
223 let total_len = self.buffer.len;
224 let chars_too_many = if unindent_comment {
226 } else if self.config.hard_tabs() {
229 self.config.tab_spaces()
231 self.buffer.truncate(total_len - chars_too_many);
232 self.buffer.push_str("}");
233 self.block_indent = self.block_indent.block_unindent(self.config);
236 // Note that this only gets called for function definitions. Required methods
237 // on traits do not get handled here.
241 generics: &ast::Generics,
245 defaultness: ast::Defaultness,
246 inner_attrs: Option<&[ast::Attribute]>,
248 let indent = self.block_indent;
250 let rewrite = match fk {
251 visit::FnKind::ItemFn(ident, _, _, _, _, b) => {
256 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
257 mk_sp(s.lo(), b.span.lo()),
261 visit::FnKind::Method(ident, _, _, b) => {
266 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
267 mk_sp(s.lo(), b.span.lo()),
271 visit::FnKind::Closure(_) => unreachable!(),
274 if let Some(fn_str) = rewrite {
275 self.format_missing_with_indent(source!(self, s).lo());
276 self.buffer.push_str(&fn_str);
277 if let Some(c) = fn_str.chars().last() {
279 self.last_pos = source!(self, block.span).hi();
284 self.format_missing(source!(self, block.span).lo());
287 self.last_pos = source!(self, block.span).lo();
288 self.visit_block(block, inner_attrs)
291 pub fn visit_item(&mut self, item: &ast::Item) {
292 skip_out_of_file_lines_range_visitor!(self, item.span);
294 // This is where we bail out if there is a skip attribute. This is only
295 // complex in the module case. It is complex because the module could be
296 // in a separate file and there might be attributes in both files, but
297 // the AST lumps them all together.
299 let mut attrs = &item.attrs;
301 ast::ItemKind::Mod(ref m) => {
302 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
303 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
304 if outer_file.name == inner_file.name {
305 // Module is inline, in this case we treat modules like any
307 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
308 self.push_rewrite(item.span, None);
311 } else if contains_skip(&item.attrs) {
312 // Module is not inline, but should be skipped.
315 // Module is not inline and should not be skipped. We want
316 // to process only the attributes in the current file.
317 filtered_attrs = item.attrs
320 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
321 if attr_file.name == outer_file.name {
327 .collect::<Vec<_>>();
328 // Assert because if we should skip it should be caught by
330 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
331 attrs = &filtered_attrs;
334 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
335 self.push_rewrite(item.span, None);
341 ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
342 ast::ItemKind::Impl(..) => {
343 let snippet = self.snippet(item.span);
344 let where_span_end = snippet
345 .find_uncommented("{")
346 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
347 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
348 self.push_rewrite(item.span, rw);
350 ast::ItemKind::Trait(..) => {
351 let rw = format_trait(&self.get_context(), item, self.block_indent);
352 self.push_rewrite(item.span, rw);
354 ast::ItemKind::ExternCrate(_) => {
355 let rw = rewrite_extern_crate(&self.get_context(), item);
356 self.push_rewrite(item.span, rw);
358 ast::ItemKind::Struct(ref def, ref generics) => {
359 let rewrite = format_struct(
369 ).map(|s| match *def {
370 ast::VariantData::Tuple(..) => s + ";",
373 self.push_rewrite(item.span, rewrite);
375 ast::ItemKind::Enum(ref def, ref generics) => {
376 self.format_missing_with_indent(source!(self, item.span).lo());
377 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
378 self.last_pos = source!(self, item.span).hi();
380 ast::ItemKind::Mod(ref module) => {
381 self.format_missing_with_indent(source!(self, item.span).lo());
382 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
384 ast::ItemKind::Mac(ref mac) => {
385 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
387 ast::ItemKind::ForeignMod(ref foreign_mod) => {
388 self.format_missing_with_indent(source!(self, item.span).lo());
389 self.format_foreign_mod(foreign_mod, item.span);
391 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
392 let rewrite = rewrite_static(
403 self.push_rewrite(item.span, rewrite);
405 ast::ItemKind::Const(ref ty, ref expr) => {
406 let rewrite = rewrite_static(
411 ast::Mutability::Immutable,
417 self.push_rewrite(item.span, rewrite);
419 ast::ItemKind::DefaultImpl(..) => {
420 // FIXME(#78): format impl definitions.
422 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
424 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
429 ast::Defaultness::Final,
433 ast::ItemKind::Ty(ref ty, ref generics) => {
434 let rewrite = rewrite_type_alias(
443 self.push_rewrite(item.span, rewrite);
445 ast::ItemKind::Union(ref def, ref generics) => {
446 let rewrite = format_struct_struct(
457 self.push_rewrite(item.span, rewrite);
459 ast::ItemKind::GlobalAsm(..) => {
460 let snippet = Some(self.snippet(item.span));
461 self.push_rewrite(item.span, snippet);
463 ast::ItemKind::MacroDef(..) => {
464 // FIXME(#1539): macros 2.0
465 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
466 self.push_rewrite(item.span, mac_snippet);
471 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
472 skip_out_of_file_lines_range_visitor!(self, ti.span);
474 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
475 self.push_rewrite(ti.span, None);
480 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
481 let rewrite = rewrite_static(
483 &ast::Visibility::Inherited,
486 ast::Mutability::Immutable,
492 self.push_rewrite(ti.span, rewrite);
494 ast::TraitItemKind::Method(ref sig, None) => {
495 let indent = self.block_indent;
497 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
498 self.push_rewrite(ti.span, rewrite);
500 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
502 visit::FnKind::Method(ti.ident, sig, None, body),
507 ast::Defaultness::Final,
511 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
512 let rewrite = rewrite_associated_type(
514 type_default.as_ref(),
515 Some(type_param_bounds),
519 self.push_rewrite(ti.span, rewrite);
521 ast::TraitItemKind::Macro(ref mac) => {
522 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
527 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
528 skip_out_of_file_lines_range_visitor!(self, ii.span);
530 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
531 self.push_rewrite(ii.span, None);
536 ast::ImplItemKind::Method(ref sig, ref body) => {
538 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
547 ast::ImplItemKind::Const(ref ty, ref expr) => {
548 let rewrite = rewrite_static(
553 ast::Mutability::Immutable,
559 self.push_rewrite(ii.span, rewrite);
561 ast::ImplItemKind::Type(ref ty) => {
562 let rewrite = rewrite_associated_impl_type(
570 self.push_rewrite(ii.span, rewrite);
572 ast::ImplItemKind::Macro(ref mac) => {
573 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
578 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
579 skip_out_of_file_lines_range_visitor!(self, mac.span);
582 let shape = self.shape().sub_width(1).unwrap();
583 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
584 self.push_rewrite(mac.span, rewrite);
587 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
588 self.format_missing_with_indent(source!(self, span).lo());
589 let result = rewrite.unwrap_or_else(|| self.snippet(span));
590 self.buffer.push_str(&result);
591 self.last_pos = source!(self, span).hi();
594 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
596 parse_session: parse_session,
597 codemap: parse_session.codemap(),
598 buffer: StringBuffer::new(),
599 last_pos: BytePos(0),
600 block_indent: Indent::empty(),
602 is_if_else_block: false,
606 pub fn snippet(&self, span: Span) -> String {
607 match self.codemap.span_to_snippet(span) {
611 "Couldn't make snippet for span {:?}->{:?}",
612 self.codemap.lookup_char_pos(span.lo()),
613 self.codemap.lookup_char_pos(span.hi())
620 // Returns true if we should skip the following item.
621 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
622 if contains_skip(attrs) {
626 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
627 if attrs.is_empty() {
631 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
632 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
633 self.push_rewrite(span, rewrite);
638 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
640 F: Fn(&ast::Item) -> bool,
642 let mut last = self.codemap.lookup_line_range(items_left[0].span());
643 let item_length = items_left
646 is_item(&***ppi) && (!in_group || {
647 let current = self.codemap.lookup_line_range(ppi.span());
648 let in_same_group = current.lo < last.hi + 2;
654 let items = &items_left[..item_length];
656 let at_least_one_in_file_lines = items
658 .any(|item| !out_of_file_lines_range!(self, item.span));
660 if at_least_one_in_file_lines {
661 self.format_imports(items);
664 self.push_rewrite(item.span, None);
671 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
672 while !items_left.is_empty() {
673 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
674 // to be potentially reordered within `format_imports`. Otherwise, just format the
675 // next item for output.
676 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
677 let used_items_len = self.reorder_items(
680 self.config.reorder_imports_in_group(),
682 let (_, rest) = items_left.split_at(used_items_len);
684 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
685 let used_items_len = self.reorder_items(
688 self.config.reorder_extern_crates_in_group(),
690 let (_, rest) = items_left.split_at(used_items_len);
693 // `unwrap()` is safe here because we know `items_left`
694 // has elements from the loop condition
695 let (item, rest) = items_left.split_first().unwrap();
696 self.visit_item(item);
702 fn walk_mod_items(&mut self, m: &ast::Mod) {
703 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
706 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
707 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
709 ast::StmtKind::Item(ref item) => Some(&**item),
714 if stmts.is_empty() {
718 // Extract leading `use ...;`.
719 let items: Vec<_> = stmts
721 .take_while(|stmt| to_stmt_item(stmt).is_some())
722 .filter_map(|stmt| to_stmt_item(stmt))
723 .take_while(|item| is_use_item(item))
726 if items.is_empty() {
727 self.visit_stmt(&stmts[0]);
728 self.walk_stmts(&stmts[1..]);
730 self.walk_items(&items);
731 self.walk_stmts(&stmts[items.len()..]);
735 fn walk_block_stmts(&mut self, b: &ast::Block) {
736 self.walk_stmts(&b.stmts)
742 vis: &ast::Visibility,
745 attrs: &[ast::Attribute],
747 // Decide whether this is an inline mod or an external mod.
748 let local_file_name = self.codemap.span_to_filename(s);
749 let inner_span = source!(self, m.inner);
750 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
751 && local_file_name == self.codemap.span_to_filename(inner_span);
753 self.buffer.push_str(&*utils::format_visibility(vis));
754 self.buffer.push_str("mod ");
755 self.buffer.push_str(&ident.to_string());
758 match self.config.item_brace_style() {
759 BraceStyle::AlwaysNextLine => self.buffer
760 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
761 _ => self.buffer.push_str(" {"),
763 // Hackery to account for the closing }.
764 let mod_lo = self.codemap.span_after(source!(self, s), "{");
766 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
767 let body_snippet = body_snippet.trim();
768 if body_snippet.is_empty() {
769 self.buffer.push_str("}");
771 self.last_pos = mod_lo;
772 self.block_indent = self.block_indent.block_indent(self.config);
773 self.visit_attrs(attrs, ast::AttrStyle::Inner);
774 self.walk_mod_items(m);
775 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
776 self.close_block(false);
778 self.last_pos = source!(self, m.inner).hi();
780 self.buffer.push_str(";");
781 self.last_pos = source!(self, s).hi();
785 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
786 self.block_indent = Indent::empty();
787 self.walk_mod_items(m);
788 self.format_missing_with_indent(filemap.end_pos);
791 pub fn get_context(&self) -> RewriteContext {
793 parse_session: self.parse_session,
794 codemap: self.codemap,
798 is_if_else_block: false,
799 force_one_line_chain: false,
804 impl Rewrite for ast::NestedMetaItem {
805 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
807 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
808 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
813 impl Rewrite for ast::MetaItem {
814 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
815 Some(match self.node {
816 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
817 ast::MetaItemKind::List(ref list) => {
818 let name = self.name.as_str();
819 // 1 = `(`, 2 = `]` and `)`
820 let item_shape = shape
822 .shrink_left(name.len() + 1)
823 .and_then(|s| s.sub_width(2))?;
824 let items = itemize_list(
828 |nested_meta_item| nested_meta_item.span.lo(),
829 |nested_meta_item| nested_meta_item.span.hi(),
830 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
835 let item_vec = items.collect::<Vec<_>>();
836 let fmt = ListFormatting {
837 tactic: DefinitiveListTactic::Mixed,
839 trailing_separator: SeparatorTactic::Never,
840 separator_place: SeparatorPlace::Back,
842 ends_with_newline: false,
843 preserve_newline: false,
844 config: context.config,
846 format!("{}({})", name, write_list(&item_vec, &fmt)?)
848 ast::MetaItemKind::NameValue(ref literal) => {
849 let name = self.name.as_str();
851 let lit_shape = shape.shrink_left(name.len() + 3)?;
852 let value = rewrite_literal(context, literal, lit_shape)?;
853 format!("{} = {}", name, value)
859 impl Rewrite for ast::Attribute {
860 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
861 let prefix = match self.style {
862 ast::AttrStyle::Inner => "#!",
863 ast::AttrStyle::Outer => "#",
865 let snippet = context.snippet(self.span);
866 if self.is_sugared_doc {
867 let doc_shape = Shape {
868 width: cmp::min(shape.width, context.config.comment_width())
869 .checked_sub(shape.indent.width())
873 rewrite_comment(&snippet, false, doc_shape, context.config)
875 if contains_comment(&snippet) {
876 return Some(snippet);
879 let shape = shape.offset_left(prefix.len() + 1)?;
881 .rewrite(context, shape)
882 .map(|rw| format!("{}[{}]", prefix, rw))
887 impl<'a> Rewrite for [ast::Attribute] {
888 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
890 return Some(String::new());
892 let mut result = String::with_capacity(128);
893 let indent = shape.indent.to_string(context.config);
895 let mut derive_args = Vec::new();
897 let mut iter = self.iter().enumerate().peekable();
898 let mut insert_new_line = true;
899 let mut is_prev_sugared_doc = false;
900 while let Some((i, a)) = iter.next() {
901 let a_str = a.rewrite(context, shape)?;
903 // Write comments and blank lines between attributes.
905 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
906 // This particular horror show is to preserve line breaks in between doc
907 // comments. An alternative would be to force such line breaks to start
908 // with the usual doc comment token.
909 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
910 || is_prev_sugared_doc
912 // Look at before and after comment and see if there are any empty lines.
913 let comment_begin = comment.chars().position(|c| c == '/');
914 let len = comment_begin.unwrap_or_else(|| comment.len());
915 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
916 let mla = if comment_begin.is_none() {
919 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
920 let len = comment_end.unwrap();
925 .filter(|c| *c == '\n')
933 let comment = recover_missing_comment_in_span(
934 mk_sp(self[i - 1].span.hi(), a.span.lo()),
935 shape.with_max_width(context.config),
940 if !comment.is_empty() {
941 if multi_line_before {
944 result.push_str(&comment);
946 if multi_line_after {
949 } else if insert_new_line {
951 if multi_line_after {
956 if derive_args.is_empty() {
957 result.push_str(&indent);
960 insert_new_line = true;
963 // Write the attribute itself.
964 if context.config.merge_derives() {
965 // If the attribute is `#[derive(...)]`, take the arguments.
966 if let Some(mut args) = get_derive_args(context, a) {
967 derive_args.append(&mut args);
969 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
970 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
971 // If not, rewrite the merged derives.
973 result.push_str(&format_derive(context, &derive_args, shape)?);
978 result.push_str(&a_str);
981 result.push_str(&a_str);
984 is_prev_sugared_doc = a.is_sugared_doc;
990 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
991 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
992 let mut result = String::with_capacity(128);
993 result.push_str("#[derive(");
994 // 11 = `#[derive()]`
995 let initial_budget = shape.width.checked_sub(11)?;
996 let mut budget = initial_budget;
997 let num = derive_args.len();
998 for (i, a) in derive_args.iter().enumerate() {
1000 let width = a.len() + 2;
1003 // Remove trailing whitespace.
1008 result.push_str(&(shape.indent + 9).to_string(context.config));
1009 budget = initial_budget;
1011 budget = budget.checked_sub(width).unwrap_or(0);
1015 result.push_str(", ")
1018 result.push_str(")]");
1022 fn is_derive(attr: &ast::Attribute) -> bool {
1024 Some(meta_item) => match meta_item.node {
1025 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1032 /// Returns the arguments of `#[derive(...)]`.
1033 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1034 attr.meta().and_then(|meta_item| match meta_item.node {
1035 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1036 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1039 .map(|a| context.snippet(a.span))
1040 .collect::<Vec<_>>(),
1047 // Rewrite `extern crate foo;` WITHOUT attributes.
1048 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1049 assert!(is_extern_crate(item));
1050 let new_str = context.snippet(item.span);
1051 Some(if contains_comment(&new_str) {
1054 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1055 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))