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)
141 .and_then(|(kind, _, s)| {
142 if kind == CodeCharKind::Normal {
148 if let Some(len) = len {
149 self.last_pos = self.last_pos + BytePos::from_usize(len);
154 // Format inner attributes if available.
155 let skip_rewrite = if let Some(attrs) = inner_attrs {
156 self.visit_attrs(attrs, ast::AttrStyle::Inner)
162 self.push_rewrite(b.span, None);
163 self.close_block(false);
164 self.last_pos = source!(self, b.span).hi();
168 self.walk_block_stmts(b);
170 if !b.stmts.is_empty() {
171 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
172 if utils::semicolon_for_expr(&self.get_context(), expr) {
173 self.buffer.push_str(";");
178 let mut remove_len = BytePos(0);
179 if self.config.remove_blank_lines_at_start_or_end_of_block() {
180 if let Some(stmt) = b.stmts.last() {
181 let snippet = self.snippet(mk_sp(
183 source!(self, b.span).hi() - brace_compensation,
185 let len = CommentCodeSlices::new(&snippet)
187 .and_then(|(kind, _, s)| {
188 if kind == CodeCharKind::Normal && s.trim().is_empty() {
194 if let Some(len) = len {
195 remove_len = BytePos::from_usize(len);
200 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
201 if unindent_comment {
202 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
203 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
204 unindent_comment = snippet.contains("//") || snippet.contains("/*");
206 // FIXME: we should compress any newlines here to just one
207 if unindent_comment {
208 self.block_indent = self.block_indent.block_unindent(self.config);
210 self.format_missing_with_indent(
211 source!(self, b.span).hi() - brace_compensation - remove_len,
213 if unindent_comment {
214 self.block_indent = self.block_indent.block_indent(self.config);
216 self.close_block(unindent_comment);
217 self.last_pos = source!(self, b.span).hi();
220 // FIXME: this is a terrible hack to indent the comments between the last
221 // item in the block and the closing brace to the block's level.
222 // The closing brace itself, however, should be indented at a shallower
224 fn close_block(&mut self, unindent_comment: bool) {
225 let total_len = self.buffer.len;
226 let chars_too_many = if unindent_comment {
228 } else if self.config.hard_tabs() {
231 self.config.tab_spaces()
233 self.buffer.truncate(total_len - chars_too_many);
234 self.buffer.push_str("}");
235 self.block_indent = self.block_indent.block_unindent(self.config);
238 // Note that this only gets called for function definitions. Required methods
239 // on traits do not get handled here.
243 generics: &ast::Generics,
247 defaultness: ast::Defaultness,
248 inner_attrs: Option<&[ast::Attribute]>,
250 let indent = self.block_indent;
252 let rewrite = match fk {
253 visit::FnKind::ItemFn(ident, _, _, _, _, b) => {
258 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
259 mk_sp(s.lo(), b.span.lo()),
263 visit::FnKind::Method(ident, _, _, b) => {
268 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
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 filtered_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(&filtered_attrs, ast::AttrStyle::Outer));
333 attrs = &filtered_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::AutoImpl(..) => {
422 // FIXME(#78): format impl definitions.
424 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
426 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
431 ast::Defaultness::Final,
435 ast::ItemKind::Ty(ref ty, ref generics) => {
436 let rewrite = rewrite_type_alias(
445 self.push_rewrite(item.span, rewrite);
447 ast::ItemKind::Union(ref def, ref generics) => {
448 let rewrite = format_struct_struct(
459 self.push_rewrite(item.span, rewrite);
461 ast::ItemKind::GlobalAsm(..) => {
462 let snippet = Some(self.snippet(item.span));
463 self.push_rewrite(item.span, snippet);
465 ast::ItemKind::MacroDef(..) => {
466 // FIXME(#1539): macros 2.0
467 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
468 self.push_rewrite(item.span, mac_snippet);
473 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
474 skip_out_of_file_lines_range_visitor!(self, ti.span);
476 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
477 self.push_rewrite(ti.span, None);
482 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
483 let rewrite = rewrite_static(
485 &ast::Visibility::Inherited,
488 ast::Mutability::Immutable,
494 self.push_rewrite(ti.span, rewrite);
496 ast::TraitItemKind::Method(ref sig, None) => {
497 let indent = self.block_indent;
499 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
500 self.push_rewrite(ti.span, rewrite);
502 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
504 visit::FnKind::Method(ti.ident, sig, None, body),
509 ast::Defaultness::Final,
513 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
514 let rewrite = rewrite_associated_type(
516 type_default.as_ref(),
517 Some(type_param_bounds),
521 self.push_rewrite(ti.span, rewrite);
523 ast::TraitItemKind::Macro(ref mac) => {
524 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
529 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
530 skip_out_of_file_lines_range_visitor!(self, ii.span);
532 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
533 self.push_rewrite(ii.span, None);
538 ast::ImplItemKind::Method(ref sig, ref body) => {
540 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
549 ast::ImplItemKind::Const(ref ty, ref expr) => {
550 let rewrite = rewrite_static(
555 ast::Mutability::Immutable,
561 self.push_rewrite(ii.span, rewrite);
563 ast::ImplItemKind::Type(ref ty) => {
564 let rewrite = rewrite_associated_impl_type(
572 self.push_rewrite(ii.span, rewrite);
574 ast::ImplItemKind::Macro(ref mac) => {
575 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
580 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
581 skip_out_of_file_lines_range_visitor!(self, mac.span);
584 let shape = self.shape().sub_width(1).unwrap();
585 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
586 self.push_rewrite(mac.span, rewrite);
589 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
590 self.format_missing_with_indent(source!(self, span).lo());
591 let result = rewrite.unwrap_or_else(|| self.snippet(span));
592 self.buffer.push_str(&result);
593 self.last_pos = source!(self, span).hi();
596 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
598 parse_session: parse_session,
599 codemap: parse_session.codemap(),
600 buffer: StringBuffer::new(),
601 last_pos: BytePos(0),
602 block_indent: Indent::empty(),
604 is_if_else_block: false,
608 pub fn snippet(&self, span: Span) -> String {
609 match self.codemap.span_to_snippet(span) {
613 "Couldn't make snippet for span {:?}->{:?}",
614 self.codemap.lookup_char_pos(span.lo()),
615 self.codemap.lookup_char_pos(span.hi())
622 // Returns true if we should skip the following item.
623 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
624 if contains_skip(attrs) {
628 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
629 if attrs.is_empty() {
633 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
634 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
635 self.push_rewrite(span, rewrite);
640 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
642 F: Fn(&ast::Item) -> bool,
644 let mut last = self.codemap.lookup_line_range(items_left[0].span());
645 let item_length = items_left
648 is_item(&***ppi) && (!in_group || {
649 let current = self.codemap.lookup_line_range(ppi.span());
650 let in_same_group = current.lo < last.hi + 2;
656 let items = &items_left[..item_length];
658 let at_least_one_in_file_lines = items
660 .any(|item| !out_of_file_lines_range!(self, item.span));
662 if at_least_one_in_file_lines {
663 self.format_imports(items);
666 self.push_rewrite(item.span, None);
673 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
674 while !items_left.is_empty() {
675 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
676 // to be potentially reordered within `format_imports`. Otherwise, just format the
677 // next item for output.
678 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
679 let used_items_len = self.reorder_items(
682 self.config.reorder_imports_in_group(),
684 let (_, rest) = items_left.split_at(used_items_len);
686 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
687 let used_items_len = self.reorder_items(
690 self.config.reorder_extern_crates_in_group(),
692 let (_, rest) = items_left.split_at(used_items_len);
695 // `unwrap()` is safe here because we know `items_left`
696 // has elements from the loop condition
697 let (item, rest) = items_left.split_first().unwrap();
698 self.visit_item(item);
704 fn walk_mod_items(&mut self, m: &ast::Mod) {
705 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
708 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
709 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
711 ast::StmtKind::Item(ref item) => Some(&**item),
716 if stmts.is_empty() {
720 // Extract leading `use ...;`.
721 let items: Vec<_> = stmts
723 .take_while(|stmt| to_stmt_item(stmt).is_some())
724 .filter_map(|stmt| to_stmt_item(stmt))
725 .take_while(|item| is_use_item(item))
728 if items.is_empty() {
729 self.visit_stmt(&stmts[0]);
730 self.walk_stmts(&stmts[1..]);
732 self.walk_items(&items);
733 self.walk_stmts(&stmts[items.len()..]);
737 fn walk_block_stmts(&mut self, b: &ast::Block) {
738 self.walk_stmts(&b.stmts)
744 vis: &ast::Visibility,
747 attrs: &[ast::Attribute],
749 // Decide whether this is an inline mod or an external mod.
750 let local_file_name = self.codemap.span_to_filename(s);
751 let inner_span = source!(self, m.inner);
752 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
753 && local_file_name == self.codemap.span_to_filename(inner_span);
755 self.buffer.push_str(&*utils::format_visibility(vis));
756 self.buffer.push_str("mod ");
757 self.buffer.push_str(&ident.to_string());
760 match self.config.item_brace_style() {
761 BraceStyle::AlwaysNextLine => self.buffer
762 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
763 _ => self.buffer.push_str(" {"),
765 // Hackery to account for the closing }.
766 let mod_lo = self.codemap.span_after(source!(self, s), "{");
768 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
769 let body_snippet = body_snippet.trim();
770 if body_snippet.is_empty() {
771 self.buffer.push_str("}");
773 self.last_pos = mod_lo;
774 self.block_indent = self.block_indent.block_indent(self.config);
775 self.visit_attrs(attrs, ast::AttrStyle::Inner);
776 self.walk_mod_items(m);
777 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
778 self.close_block(false);
780 self.last_pos = source!(self, m.inner).hi();
782 self.buffer.push_str(";");
783 self.last_pos = source!(self, s).hi();
787 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
788 self.block_indent = Indent::empty();
789 self.walk_mod_items(m);
790 self.format_missing_with_indent(filemap.end_pos);
793 pub fn get_context(&self) -> RewriteContext {
795 parse_session: self.parse_session,
796 codemap: self.codemap,
800 is_if_else_block: false,
801 force_one_line_chain: false,
806 impl Rewrite for ast::NestedMetaItem {
807 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
809 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
810 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
815 impl Rewrite for ast::MetaItem {
816 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
817 Some(match self.node {
818 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
819 ast::MetaItemKind::List(ref list) => {
820 let name = self.name.as_str();
821 // 1 = `(`, 2 = `]` and `)`
822 let item_shape = shape
824 .shrink_left(name.len() + 1)
825 .and_then(|s| s.sub_width(2))?;
826 let items = itemize_list(
830 |nested_meta_item| nested_meta_item.span.lo(),
831 |nested_meta_item| nested_meta_item.span.hi(),
832 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
837 let item_vec = items.collect::<Vec<_>>();
838 let fmt = ListFormatting {
839 tactic: DefinitiveListTactic::Mixed,
841 trailing_separator: SeparatorTactic::Never,
842 separator_place: SeparatorPlace::Back,
844 ends_with_newline: false,
845 preserve_newline: false,
846 config: context.config,
848 format!("{}({})", name, write_list(&item_vec, &fmt)?)
850 ast::MetaItemKind::NameValue(ref literal) => {
851 let name = self.name.as_str();
853 let lit_shape = shape.shrink_left(name.len() + 3)?;
854 let value = rewrite_literal(context, literal, lit_shape)?;
855 format!("{} = {}", name, value)
861 impl Rewrite for ast::Attribute {
862 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
863 let prefix = match self.style {
864 ast::AttrStyle::Inner => "#!",
865 ast::AttrStyle::Outer => "#",
867 let snippet = context.snippet(self.span);
868 if self.is_sugared_doc {
869 let doc_shape = Shape {
870 width: cmp::min(shape.width, context.config.comment_width())
871 .checked_sub(shape.indent.width())
875 rewrite_comment(&snippet, false, doc_shape, context.config)
877 if contains_comment(&snippet) {
878 return Some(snippet);
881 let shape = shape.offset_left(prefix.len() + 1)?;
883 .rewrite(context, shape)
884 .map(|rw| format!("{}[{}]", prefix, rw))
889 impl<'a> Rewrite for [ast::Attribute] {
890 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
892 return Some(String::new());
894 let mut result = String::with_capacity(128);
895 let indent = shape.indent.to_string(context.config);
897 let mut derive_args = Vec::new();
899 let mut iter = self.iter().enumerate().peekable();
900 let mut insert_new_line = true;
901 let mut is_prev_sugared_doc = false;
902 while let Some((i, a)) = iter.next() {
903 let a_str = a.rewrite(context, shape)?;
905 // Write comments and blank lines between attributes.
907 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
908 // This particular horror show is to preserve line breaks in between doc
909 // comments. An alternative would be to force such line breaks to start
910 // with the usual doc comment token.
911 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
912 || is_prev_sugared_doc
914 // Look at before and after comment and see if there are any empty lines.
915 let comment_begin = comment.chars().position(|c| c == '/');
916 let len = comment_begin.unwrap_or_else(|| comment.len());
917 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
918 let mla = if comment_begin.is_none() {
921 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
922 let len = comment_end.unwrap();
927 .filter(|c| *c == '\n')
935 let comment = recover_missing_comment_in_span(
936 mk_sp(self[i - 1].span.hi(), a.span.lo()),
937 shape.with_max_width(context.config),
942 if !comment.is_empty() {
943 if multi_line_before {
946 result.push_str(&comment);
948 if multi_line_after {
951 } else if insert_new_line {
953 if multi_line_after {
958 if derive_args.is_empty() {
959 result.push_str(&indent);
962 insert_new_line = true;
965 // Write the attribute itself.
966 if context.config.merge_derives() {
967 // If the attribute is `#[derive(...)]`, take the arguments.
968 if let Some(mut args) = get_derive_args(context, a) {
969 derive_args.append(&mut args);
971 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
972 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
973 // If not, rewrite the merged derives.
975 result.push_str(&format_derive(context, &derive_args, shape)?);
980 result.push_str(&a_str);
983 result.push_str(&a_str);
986 is_prev_sugared_doc = a.is_sugared_doc;
992 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
993 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
994 let mut result = String::with_capacity(128);
995 result.push_str("#[derive(");
996 // 11 = `#[derive()]`
997 let initial_budget = shape.width.checked_sub(11)?;
998 let mut budget = initial_budget;
999 let num = derive_args.len();
1000 for (i, a) in derive_args.iter().enumerate() {
1002 let width = a.len() + 2;
1005 // Remove trailing whitespace.
1010 result.push_str(&(shape.indent + 9).to_string(context.config));
1011 budget = initial_budget;
1013 budget = budget.checked_sub(width).unwrap_or(0);
1017 result.push_str(", ")
1020 result.push_str(")]");
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<_>>(),
1049 // Rewrite `extern crate foo;` WITHOUT attributes.
1050 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1051 assert!(is_extern_crate(item));
1052 let new_str = context.snippet(item.span);
1053 Some(if contains_comment(&new_str) {
1056 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1057 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))