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::{combine_strs_with_missing_comments, contains_comment, remove_trailing_white_spaces,
23 CodeCharKind, CommentCodeSlices, FindUncommented};
24 use comment::rewrite_comment;
25 use config::{BraceStyle, Config};
26 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
27 rewrite_type_alias, FnSig, StaticParts, StructParts};
28 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
30 use macros::{rewrite_macro, MacroPosition};
32 use rewrite::{Rewrite, RewriteContext};
33 use shape::{Indent, Shape};
34 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
36 fn is_use_item(item: &ast::Item) -> bool {
38 ast::ItemKind::Use(_) => true,
43 fn is_extern_crate(item: &ast::Item) -> bool {
45 ast::ItemKind::ExternCrate(..) => true,
50 pub struct FmtVisitor<'a> {
51 pub parse_session: &'a ParseSess,
52 pub codemap: &'a CodeMap,
53 pub buffer: StringBuffer,
54 pub last_pos: BytePos,
55 // FIXME: use an RAII util or closure for indenting
56 pub block_indent: Indent,
57 pub config: &'a Config,
58 pub is_if_else_block: bool,
61 impl<'a> FmtVisitor<'a> {
62 pub fn shape(&self) -> Shape {
63 Shape::indented(self.block_indent, self.config)
66 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
68 "visit_stmt: {:?} {:?}",
69 self.codemap.lookup_char_pos(stmt.span.lo()),
70 self.codemap.lookup_char_pos(stmt.span.hi())
74 ast::StmtKind::Item(ref item) => {
75 self.visit_item(item);
77 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
78 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
79 self.push_rewrite(stmt.span(), rewrite)
81 ast::StmtKind::Mac(ref mac) => {
82 let (ref mac, _macro_style, ref attrs) = **mac;
83 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
84 self.push_rewrite(stmt.span(), None);
86 self.visit_mac(mac, None, MacroPosition::Statement);
88 self.format_missing(stmt.span.hi());
96 inner_attrs: Option<&[ast::Attribute]>,
100 "visit_block: {:?} {:?}",
101 self.codemap.lookup_char_pos(b.span.lo()),
102 self.codemap.lookup_char_pos(b.span.hi())
105 // Check if this block has braces.
106 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
108 self.last_pos = self.last_pos + brace_compensation;
109 self.block_indent = self.block_indent.block_indent(self.config);
110 self.buffer.push_str("{");
112 if self.config.remove_blank_lines_at_start_or_end_of_block() {
113 if let Some(first_stmt) = b.stmts.first() {
114 let attr_lo = inner_attrs
115 .and_then(|attrs| 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 unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
201 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
202 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
203 snippet.contains("//") || snippet.contains("/*")
205 // FIXME: we should compress any newlines here to just one
206 if unindent_comment {
207 self.block_indent = self.block_indent.block_unindent(self.config);
209 self.format_missing_with_indent(
210 source!(self, b.span).hi() - brace_compensation - remove_len,
212 if unindent_comment {
213 self.block_indent = self.block_indent.block_indent(self.config);
215 self.close_block(unindent_comment);
216 self.last_pos = source!(self, b.span).hi();
219 // FIXME: this is a terrible hack to indent the comments between the last
220 // item in the block and the closing brace to the block's level.
221 // The closing brace itself, however, should be indented at a shallower
223 fn close_block(&mut self, unindent_comment: bool) {
224 let total_len = self.buffer.len;
225 let chars_too_many = if unindent_comment {
227 } else if self.config.hard_tabs() {
230 self.config.tab_spaces()
232 self.buffer.truncate(total_len - chars_too_many);
233 self.buffer.push_str("}");
234 self.block_indent = self.block_indent.block_unindent(self.config);
237 // Note that this only gets called for function definitions. Required methods
238 // on traits do not get handled here.
242 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) | visit::FnKind::Method(ident, _, _, b) => {
256 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
257 mk_sp(s.lo(), b.span.lo()),
261 visit::FnKind::Closure(_) => unreachable!(),
264 if let Some(fn_str) = rewrite {
265 self.format_missing_with_indent(source!(self, s).lo());
266 self.buffer.push_str(&fn_str);
267 if let Some(c) = fn_str.chars().last() {
269 self.last_pos = source!(self, block.span).hi();
274 self.format_missing(source!(self, block.span).lo());
277 self.last_pos = source!(self, block.span).lo();
278 self.visit_block(block, inner_attrs, true)
281 pub fn visit_item(&mut self, item: &ast::Item) {
282 skip_out_of_file_lines_range_visitor!(self, item.span);
284 // This is where we bail out if there is a skip attribute. This is only
285 // complex in the module case. It is complex because the module could be
286 // in a separate file and there might be attributes in both files, but
287 // the AST lumps them all together.
289 let mut attrs = &item.attrs;
291 ast::ItemKind::Mod(ref m) => {
292 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
293 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
294 if outer_file.name == inner_file.name {
295 // Module is inline, in this case we treat modules like any
297 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
298 self.push_rewrite(item.span, None);
301 } else if contains_skip(&item.attrs) {
302 // Module is not inline, but should be skipped.
305 // Module is not inline and should not be skipped. We want
306 // to process only the attributes in the current file.
307 filtered_attrs = item.attrs
310 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
311 if attr_file.name == outer_file.name {
317 .collect::<Vec<_>>();
318 // Assert because if we should skip it should be caught by
320 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
321 attrs = &filtered_attrs;
324 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
325 self.push_rewrite(item.span, None);
331 ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
332 ast::ItemKind::Impl(..) => {
333 let snippet = self.snippet(item.span);
334 let where_span_end = snippet
335 .find_uncommented("{")
336 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
337 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
338 self.push_rewrite(item.span, rw);
340 ast::ItemKind::Trait(..) => {
341 let rw = format_trait(&self.get_context(), item, self.block_indent);
342 self.push_rewrite(item.span, rw);
344 ast::ItemKind::ExternCrate(_) => {
345 let rw = rewrite_extern_crate(&self.get_context(), item);
346 self.push_rewrite(item.span, rw);
348 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
349 self.visit_struct(&StructParts::from_item(item));
351 ast::ItemKind::Enum(ref def, ref generics) => {
352 self.format_missing_with_indent(source!(self, item.span).lo());
353 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
354 self.last_pos = source!(self, item.span).hi();
356 ast::ItemKind::Mod(ref module) => {
357 self.format_missing_with_indent(source!(self, item.span).lo());
358 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
360 ast::ItemKind::Mac(ref mac) => {
361 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
363 ast::ItemKind::ForeignMod(ref foreign_mod) => {
364 self.format_missing_with_indent(source!(self, item.span).lo());
365 self.format_foreign_mod(foreign_mod, item.span);
367 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
368 self.visit_static(&StaticParts::from_item(item));
370 ast::ItemKind::AutoImpl(..) => {
371 // FIXME(#78): format impl definitions.
373 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
375 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
379 ast::Defaultness::Final,
383 ast::ItemKind::Ty(ref ty, ref generics) => {
384 let rewrite = rewrite_type_alias(
393 self.push_rewrite(item.span, rewrite);
395 ast::ItemKind::GlobalAsm(..) => {
396 let snippet = Some(self.snippet(item.span));
397 self.push_rewrite(item.span, snippet);
399 ast::ItemKind::MacroDef(..) => {
400 // FIXME(#1539): macros 2.0
401 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
402 self.push_rewrite(item.span, mac_snippet);
407 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
408 skip_out_of_file_lines_range_visitor!(self, ti.span);
410 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
411 self.push_rewrite(ti.span, None);
416 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
417 ast::TraitItemKind::Method(ref sig, None) => {
418 let indent = self.block_indent;
420 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
421 self.push_rewrite(ti.span, rewrite);
423 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
425 visit::FnKind::Method(ti.ident, sig, None, body),
429 ast::Defaultness::Final,
433 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
434 let rewrite = rewrite_associated_type(
436 type_default.as_ref(),
437 Some(type_param_bounds),
441 self.push_rewrite(ti.span, rewrite);
443 ast::TraitItemKind::Macro(ref mac) => {
444 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
449 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
450 skip_out_of_file_lines_range_visitor!(self, ii.span);
452 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
453 self.push_rewrite(ii.span, None);
458 ast::ImplItemKind::Method(ref sig, ref body) => {
460 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
468 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
469 ast::ImplItemKind::Type(ref ty) => {
470 let rewrite = rewrite_associated_impl_type(
478 self.push_rewrite(ii.span, rewrite);
480 ast::ImplItemKind::Macro(ref mac) => {
481 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
486 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
487 skip_out_of_file_lines_range_visitor!(self, mac.span);
490 let shape = self.shape().sub_width(1).unwrap();
491 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
492 self.push_rewrite(mac.span, rewrite);
495 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
496 self.format_missing_with_indent(source!(self, span).lo());
497 let result = rewrite.unwrap_or_else(|| self.snippet(span));
498 self.buffer.push_str(&result);
499 self.last_pos = source!(self, span).hi();
502 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
504 parse_session: parse_session,
505 codemap: parse_session.codemap(),
506 buffer: StringBuffer::new(),
507 last_pos: BytePos(0),
508 block_indent: Indent::empty(),
510 is_if_else_block: false,
514 pub fn opt_snippet(&self, span: Span) -> Option<String> {
515 self.codemap.span_to_snippet(span).ok()
518 pub fn snippet(&self, span: Span) -> String {
519 match self.codemap.span_to_snippet(span) {
523 "Couldn't make snippet for span {:?}->{:?}",
524 self.codemap.lookup_char_pos(span.lo()),
525 self.codemap.lookup_char_pos(span.hi())
532 // Returns true if we should skip the following item.
533 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
534 if contains_skip(attrs) {
538 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
539 if attrs.is_empty() {
543 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
544 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
545 self.push_rewrite(span, rewrite);
550 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
552 F: Fn(&ast::Item) -> bool,
554 let mut last = self.codemap.lookup_line_range(items_left[0].span());
555 let item_length = items_left
558 is_item(&***ppi) && (!in_group || {
559 let current = self.codemap.lookup_line_range(ppi.span());
560 let in_same_group = current.lo < last.hi + 2;
566 let items = &items_left[..item_length];
568 let at_least_one_in_file_lines = items
570 .any(|item| !out_of_file_lines_range!(self, item.span));
572 if at_least_one_in_file_lines {
573 self.format_imports(items);
576 self.push_rewrite(item.span, None);
583 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
584 while !items_left.is_empty() {
585 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
586 // to be potentially reordered within `format_imports`. Otherwise, just format the
587 // next item for output.
588 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
589 let used_items_len = self.reorder_items(
592 self.config.reorder_imports_in_group(),
594 let (_, rest) = items_left.split_at(used_items_len);
596 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
597 let used_items_len = self.reorder_items(
600 self.config.reorder_extern_crates_in_group(),
602 let (_, rest) = items_left.split_at(used_items_len);
605 // `unwrap()` is safe here because we know `items_left`
606 // has elements from the loop condition
607 let (item, rest) = items_left.split_first().unwrap();
608 self.visit_item(item);
614 fn walk_mod_items(&mut self, m: &ast::Mod) {
615 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
618 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
619 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
621 ast::StmtKind::Item(ref item) => Some(&**item),
626 if stmts.is_empty() {
630 // Extract leading `use ...;`.
631 let items: Vec<_> = stmts
633 .take_while(|stmt| to_stmt_item(stmt).is_some())
634 .filter_map(|stmt| to_stmt_item(stmt))
635 .take_while(|item| is_use_item(item))
638 if items.is_empty() {
639 self.visit_stmt(&stmts[0]);
640 self.walk_stmts(&stmts[1..]);
642 self.walk_items(&items);
643 self.walk_stmts(&stmts[items.len()..]);
647 fn walk_block_stmts(&mut self, b: &ast::Block) {
648 self.walk_stmts(&b.stmts)
654 vis: &ast::Visibility,
657 attrs: &[ast::Attribute],
659 // Decide whether this is an inline mod or an external mod.
660 let local_file_name = self.codemap.span_to_filename(s);
661 let inner_span = source!(self, m.inner);
662 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
663 && local_file_name == self.codemap.span_to_filename(inner_span);
665 self.buffer.push_str(&*utils::format_visibility(vis));
666 self.buffer.push_str("mod ");
667 self.buffer.push_str(&ident.to_string());
670 match self.config.brace_style() {
671 BraceStyle::AlwaysNextLine => self.buffer
672 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
673 _ => self.buffer.push_str(" {"),
675 // Hackery to account for the closing }.
676 let mod_lo = self.codemap.span_after(source!(self, s), "{");
678 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
679 let body_snippet = body_snippet.trim();
680 if body_snippet.is_empty() {
681 self.buffer.push_str("}");
683 self.last_pos = mod_lo;
684 self.block_indent = self.block_indent.block_indent(self.config);
685 self.visit_attrs(attrs, ast::AttrStyle::Inner);
686 self.walk_mod_items(m);
687 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
688 self.close_block(false);
690 self.last_pos = source!(self, m.inner).hi();
692 self.buffer.push_str(";");
693 self.last_pos = source!(self, s).hi();
697 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
698 self.block_indent = Indent::empty();
699 self.walk_mod_items(m);
700 self.format_missing_with_indent(filemap.end_pos);
703 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
704 while let Some(pos) = self.codemap
705 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
707 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
708 if snippet.trim().is_empty() {
717 pub fn get_context(&self) -> RewriteContext {
719 parse_session: self.parse_session,
720 codemap: self.codemap,
724 is_if_else_block: false,
725 force_one_line_chain: false,
730 impl Rewrite for ast::NestedMetaItem {
731 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
733 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
734 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
739 impl Rewrite for ast::MetaItem {
740 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
741 Some(match self.node {
742 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
743 ast::MetaItemKind::List(ref list) => {
744 let name = self.name.as_str();
745 // 1 = `(`, 2 = `]` and `)`
746 let item_shape = shape
748 .shrink_left(name.len() + 1)
749 .and_then(|s| s.sub_width(2))?;
750 let items = itemize_list(
755 |nested_meta_item| nested_meta_item.span.lo(),
756 |nested_meta_item| nested_meta_item.span.hi(),
757 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
762 let item_vec = items.collect::<Vec<_>>();
763 let fmt = ListFormatting {
764 tactic: DefinitiveListTactic::Mixed,
766 trailing_separator: SeparatorTactic::Never,
767 separator_place: SeparatorPlace::Back,
769 ends_with_newline: false,
770 preserve_newline: false,
771 config: context.config,
773 format!("{}({})", name, write_list(&item_vec, &fmt)?)
775 ast::MetaItemKind::NameValue(ref literal) => {
776 let name = self.name.as_str();
778 let lit_shape = shape.shrink_left(name.len() + 3)?;
779 let value = rewrite_literal(context, literal, lit_shape)?;
780 format!("{} = {}", name, value)
786 impl Rewrite for ast::Attribute {
787 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
788 let prefix = match self.style {
789 ast::AttrStyle::Inner => "#!",
790 ast::AttrStyle::Outer => "#",
792 let snippet = context.snippet(self.span);
793 if self.is_sugared_doc {
794 let doc_shape = Shape {
795 width: cmp::min(shape.width, context.config.comment_width())
796 .checked_sub(shape.indent.width())
800 rewrite_comment(&snippet, false, doc_shape, context.config)
802 if contains_comment(&snippet) {
803 return Some(snippet);
806 let shape = shape.offset_left(prefix.len() + 1)?;
808 .rewrite(context, shape)
809 .map(|rw| format!("{}[{}]", prefix, rw))
814 /// Returns the first group of attributes that fills the given predicate.
815 /// We consider two doc comments are in different group if they are separated by normal comments.
816 fn take_while_with_pred<'a, P>(
817 context: &RewriteContext,
818 attrs: &'a [ast::Attribute],
820 ) -> &'a [ast::Attribute]
822 P: Fn(&ast::Attribute) -> bool,
824 let mut last_index = 0;
825 let mut iter = attrs.iter().enumerate().peekable();
826 while let Some((i, attr)) = iter.next() {
830 if let Some(&(_, next_attr)) = iter.peek() {
831 // Extract comments between two attributes.
832 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
833 let snippet = context.snippet(span_between_attr);
834 if snippet.chars().filter(|c| *c == '\n').count() >= 2 || snippet.contains('/') {
843 &attrs[..last_index + 1]
847 fn rewrite_first_group_attrs(
848 context: &RewriteContext,
849 attrs: &[ast::Attribute],
851 ) -> Option<(usize, String)> {
852 if attrs.is_empty() {
853 return Some((0, String::new()));
855 // Rewrite doc comments
856 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
857 if !sugared_docs.is_empty() {
858 let snippet = sugared_docs
860 .map(|a| context.snippet(a.span))
865 rewrite_comment(&snippet, false, shape, context.config)?,
868 // Rewrite `#[derive(..)]`s.
869 if context.config.merge_derives() {
870 let derives = take_while_with_pred(context, attrs, is_derive);
871 if !derives.is_empty() {
872 let mut derive_args = vec![];
873 for derive in derives {
874 derive_args.append(&mut get_derive_args(context, derive)?);
876 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
879 // Rewrite the first attribute.
880 Some((1, attrs[0].rewrite(context, shape)?))
883 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
884 // Look at before and after comment and see if there are any empty lines.
885 let comment_begin = comment.chars().position(|c| c == '/');
886 let len = comment_begin.unwrap_or_else(|| comment.len());
887 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
888 let mla = if comment_begin.is_none() {
891 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
892 let len = comment_end.unwrap();
897 .filter(|c| *c == '\n')
900 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
903 impl<'a> Rewrite for [ast::Attribute] {
904 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
906 return Some(String::new());
908 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
909 if self.len() == 1 || first_group_len == self.len() {
910 Some(first_group_str)
912 let rest_str = self[first_group_len..].rewrite(context, shape)?;
913 let missing_span = mk_sp(
914 self[first_group_len - 1].span.hi(),
915 self[first_group_len].span.lo(),
917 // Preserve an empty line before/after doc comments.
918 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
919 let snippet = context.snippet(missing_span);
920 let (mla, mlb) = has_newlines_before_after_comment(&snippet);
921 let comment = ::comment::recover_missing_comment_in_span(
923 shape.with_max_width(context.config),
927 let comment = if comment.is_empty() {
930 format!("{}{}\n{}", mla, comment, mlb)
936 shape.indent.to_string(context.config),
940 combine_strs_with_missing_comments(
953 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
954 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
955 let mut result = String::with_capacity(128);
956 result.push_str("#[derive(");
957 // 11 = `#[derive()]`
958 let initial_budget = shape.width.checked_sub(11)?;
959 let mut budget = initial_budget;
960 let num = derive_args.len();
961 for (i, a) in derive_args.iter().enumerate() {
963 let width = a.len() + 2;
966 // Remove trailing whitespace.
971 result.push_str(&(shape.indent + 9).to_string(context.config));
972 budget = initial_budget;
974 budget = budget.checked_sub(width).unwrap_or(0);
978 result.push_str(", ")
981 result.push_str(")]");
985 fn is_derive(attr: &ast::Attribute) -> bool {
987 Some(meta_item) => match meta_item.node {
988 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
995 /// Returns the arguments of `#[derive(...)]`.
996 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
997 attr.meta().and_then(|meta_item| match meta_item.node {
998 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
999 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1002 .map(|a| context.snippet(a.span))
1003 .collect::<Vec<_>>(),
1010 // Rewrite `extern crate foo;` WITHOUT attributes.
1011 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1012 assert!(is_extern_crate(item));
1013 let new_str = context.snippet(item.span);
1014 Some(if contains_comment(&new_str) {
1017 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1018 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))