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.
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 codemap::{LineRangeUtils, SpanUtils};
20 use comment::{combine_strs_with_missing_comments, contains_comment, CodeCharKind,
21 CommentCodeSlices, FindUncommented};
22 use comment::rewrite_doc_comment;
23 use config::{BraceStyle, Config};
24 use expr::rewrite_literal;
25 use items::{format_impl, format_trait, format_trait_alias, rewrite_associated_impl_type,
26 rewrite_associated_type, rewrite_type_alias, FnSig, StaticParts, StructParts};
27 use lists::{itemize_list, write_list, ListFormatting};
28 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
33 use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
35 /// Returns attributes that are within `outer_span`.
36 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
39 .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
44 /// Returns true for `mod foo;`, false for `mod foo { .. }`.
45 fn is_mod_decl(item: &ast::Item) -> bool {
47 ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(),
52 fn is_use_item(item: &ast::Item) -> bool {
54 ast::ItemKind::Use(_) => true,
59 fn is_extern_crate(item: &ast::Item) -> bool {
61 ast::ItemKind::ExternCrate(..) => true,
66 /// Creates a string slice corresponding to the specified span.
67 pub struct SnippetProvider<'a> {
68 /// A pointer to the content of the file we are formatting.
70 /// A position of the start of `big_snippet`, used as an offset.
74 impl<'a> SnippetProvider<'a> {
75 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
76 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
77 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
78 Some(&self.big_snippet[start_index..end_index])
81 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
82 let start_pos = start_pos.to_usize();
90 pub struct FmtVisitor<'a> {
91 pub parse_session: &'a ParseSess,
92 pub codemap: &'a CodeMap,
94 pub last_pos: BytePos,
95 // FIXME: use an RAII util or closure for indenting
96 pub block_indent: Indent,
97 pub config: &'a Config,
98 pub is_if_else_block: bool,
99 pub snippet_provider: &'a SnippetProvider<'a>,
100 pub line_number: usize,
101 pub skipped_range: Vec<(usize, usize)>,
104 impl<'b, 'a: 'b> FmtVisitor<'a> {
105 pub fn shape(&self) -> Shape {
106 Shape::indented(self.block_indent, self.config)
109 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
111 "visit_stmt: {:?} {:?}",
112 self.codemap.lookup_char_pos(stmt.span.lo()),
113 self.codemap.lookup_char_pos(stmt.span.hi())
117 ast::StmtKind::Item(ref item) => {
118 self.visit_item(item);
120 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
121 if contains_skip(get_attrs_from_stmt(stmt)) {
122 self.push_skipped_with_span(stmt.span());
124 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
125 self.push_rewrite(stmt.span(), rewrite)
128 ast::StmtKind::Mac(ref mac) => {
129 let (ref mac, _macro_style, ref attrs) = **mac;
130 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
131 self.push_skipped_with_span(stmt.span());
133 self.visit_mac(mac, None, MacroPosition::Statement);
135 self.format_missing(stmt.span.hi());
143 inner_attrs: Option<&[ast::Attribute]>,
147 "visit_block: {:?} {:?}",
148 self.codemap.lookup_char_pos(b.span.lo()),
149 self.codemap.lookup_char_pos(b.span.hi())
152 // Check if this block has braces.
153 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
155 self.last_pos = self.last_pos + brace_compensation;
156 self.block_indent = self.block_indent.block_indent(self.config);
159 if self.config.remove_blank_lines_at_start_or_end_of_block() {
160 if let Some(first_stmt) = b.stmts.first() {
161 let attr_lo = inner_attrs
162 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
164 // Attributes for an item in a statement position
165 // do not belong to the statement. (rust-lang/rust#34459)
166 if let ast::StmtKind::Item(ref item) = first_stmt.node {
169 first_stmt.attrs().first()
171 // Some stmts can have embedded attributes.
172 // e.g. `match { #![attr] ... }`
173 let attr_lo = attr.span.lo();
174 if attr_lo < first_stmt.span.lo() {
182 let snippet = self.snippet(mk_sp(
184 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
186 let len = CommentCodeSlices::new(snippet)
188 .and_then(|(kind, _, s)| {
189 if kind == CodeCharKind::Normal {
195 if let Some(len) = len {
196 self.last_pos = self.last_pos + BytePos::from_usize(len);
201 // Format inner attributes if available.
202 let skip_rewrite = if let Some(attrs) = inner_attrs {
203 self.visit_attrs(attrs, ast::AttrStyle::Inner)
209 self.push_rewrite(b.span, None);
210 self.close_block(false);
211 self.last_pos = source!(self, b.span).hi();
215 self.walk_block_stmts(b);
217 if !b.stmts.is_empty() {
218 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
219 if utils::semicolon_for_expr(&self.get_context(), expr) {
225 let mut remove_len = BytePos(0);
226 if self.config.remove_blank_lines_at_start_or_end_of_block() {
227 if let Some(stmt) = b.stmts.last() {
228 let snippet = self.snippet(mk_sp(
230 source!(self, b.span).hi() - brace_compensation,
232 let len = CommentCodeSlices::new(snippet)
234 .and_then(|(kind, _, s)| {
235 if kind == CodeCharKind::Normal && s.trim().is_empty() {
241 if let Some(len) = len {
242 remove_len = BytePos::from_usize(len);
247 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
248 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
249 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
250 snippet.contains("//") || snippet.contains("/*")
252 // FIXME: we should compress any newlines here to just one
253 if unindent_comment {
254 self.block_indent = self.block_indent.block_unindent(self.config);
256 self.format_missing_with_indent(
257 source!(self, b.span).hi() - brace_compensation - remove_len,
259 if unindent_comment {
260 self.block_indent = self.block_indent.block_indent(self.config);
262 self.close_block(unindent_comment);
263 self.last_pos = source!(self, b.span).hi();
266 // FIXME: this is a terrible hack to indent the comments between the last
267 // item in the block and the closing brace to the block's level.
268 // The closing brace itself, however, should be indented at a shallower
270 fn close_block(&mut self, unindent_comment: bool) {
271 let total_len = self.buffer.len();
272 let chars_too_many = if unindent_comment {
274 } else if self.config.hard_tabs() {
277 self.config.tab_spaces()
279 self.buffer.truncate(total_len - chars_too_many);
281 self.block_indent = self.block_indent.block_unindent(self.config);
284 // Note that this only gets called for function definitions. Required methods
285 // on traits do not get handled here.
289 generics: &ast::Generics,
292 defaultness: ast::Defaultness,
293 inner_attrs: Option<&[ast::Attribute]>,
295 let indent = self.block_indent;
297 let rewrite = match fk {
298 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
303 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
304 mk_sp(s.lo(), b.span.lo()),
308 visit::FnKind::Closure(_) => unreachable!(),
311 if let Some(fn_str) = rewrite {
312 self.format_missing_with_indent(source!(self, s).lo());
313 self.push_str(&fn_str);
314 if let Some(c) = fn_str.chars().last() {
316 self.last_pos = source!(self, block.span).hi();
321 self.format_missing(source!(self, block.span).lo());
324 self.last_pos = source!(self, block.span).lo();
325 self.visit_block(block, inner_attrs, true)
328 pub fn visit_item(&mut self, item: &ast::Item) {
329 skip_out_of_file_lines_range_visitor!(self, item.span);
331 // This is where we bail out if there is a skip attribute. This is only
332 // complex in the module case. It is complex because the module could be
333 // in a separate file and there might be attributes in both files, but
334 // the AST lumps them all together.
336 let mut attrs = &item.attrs;
338 // Module is inline, in this case we treat it like any other item.
339 _ if !is_mod_decl(item) => {
340 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
341 self.push_skipped_with_span(item.span());
345 // Module is not inline, but should be skipped.
346 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
349 // Module is not inline and should not be skipped. We want
350 // to process only the attributes in the current file.
351 ast::ItemKind::Mod(..) => {
352 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
353 // Assert because if we should skip it should be caught by
355 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
356 attrs = &filtered_attrs;
359 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
360 self.push_skipped_with_span(item.span());
367 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
368 ast::ItemKind::Impl(..) => {
369 let snippet = self.snippet(item.span);
370 let where_span_end = snippet
371 .find_uncommented("{")
372 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
373 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
374 self.push_rewrite(item.span, rw);
376 ast::ItemKind::Trait(..) => {
377 let rw = format_trait(&self.get_context(), item, self.block_indent);
378 self.push_rewrite(item.span, rw);
380 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
381 let shape = Shape::indented(self.block_indent, self.config);
382 let rw = format_trait_alias(
389 self.push_rewrite(item.span, rw);
391 ast::ItemKind::ExternCrate(_) => {
392 let rw = rewrite_extern_crate(&self.get_context(), item);
393 self.push_rewrite(item.span, rw);
395 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
396 self.visit_struct(&StructParts::from_item(item));
398 ast::ItemKind::Enum(ref def, ref generics) => {
399 self.format_missing_with_indent(source!(self, item.span).lo());
400 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
401 self.last_pos = source!(self, item.span).hi();
403 ast::ItemKind::Mod(ref module) => {
404 let is_inline = !is_mod_decl(item);
405 self.format_missing_with_indent(source!(self, item.span).lo());
406 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
408 ast::ItemKind::Mac(ref mac) => {
409 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
411 ast::ItemKind::ForeignMod(ref foreign_mod) => {
412 self.format_missing_with_indent(source!(self, item.span).lo());
413 self.format_foreign_mod(foreign_mod, item.span);
415 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
416 self.visit_static(&StaticParts::from_item(item));
418 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
420 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
424 ast::Defaultness::Final,
428 ast::ItemKind::Ty(ref ty, ref generics) => {
429 let rewrite = rewrite_type_alias(
438 self.push_rewrite(item.span, rewrite);
440 ast::ItemKind::GlobalAsm(..) => {
441 let snippet = Some(self.snippet(item.span).to_owned());
442 self.push_rewrite(item.span, snippet);
444 ast::ItemKind::MacroDef(ref def) => {
445 let rewrite = rewrite_macro_def(
454 self.push_rewrite(item.span, rewrite);
459 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
460 skip_out_of_file_lines_range_visitor!(self, ti.span);
462 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
463 self.push_skipped_with_span(ti.span());
468 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
469 ast::TraitItemKind::Method(ref sig, None) => {
470 let indent = self.block_indent;
472 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
473 self.push_rewrite(ti.span, rewrite);
475 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
477 visit::FnKind::Method(ti.ident, sig, None, body),
481 ast::Defaultness::Final,
485 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
486 let rewrite = rewrite_associated_type(
488 type_default.as_ref(),
489 Some(type_param_bounds),
493 self.push_rewrite(ti.span, rewrite);
495 ast::TraitItemKind::Macro(ref mac) => {
496 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
501 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
502 skip_out_of_file_lines_range_visitor!(self, ii.span);
504 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
505 self.push_skipped_with_span(ii.span());
510 ast::ImplItemKind::Method(ref sig, ref body) => {
512 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
520 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
521 ast::ImplItemKind::Type(ref ty) => {
522 let rewrite = rewrite_associated_impl_type(
530 self.push_rewrite(ii.span, rewrite);
532 ast::ImplItemKind::Macro(ref mac) => {
533 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
538 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
539 skip_out_of_file_lines_range_visitor!(self, mac.span);
542 let shape = self.shape().sub_width(1).unwrap();
543 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
544 self.push_rewrite(mac.span, rewrite);
547 pub fn push_str(&mut self, s: &str) {
548 self.line_number += count_newlines(s);
549 self.buffer.push_str(s);
552 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
553 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
554 if let Some(ref s) = rewrite {
557 let snippet = self.snippet(span);
558 self.push_str(snippet);
560 self.last_pos = source!(self, span).hi();
563 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
564 self.format_missing_with_indent(source!(self, span).lo());
565 self.push_rewrite_inner(span, rewrite);
568 pub fn push_skipped_with_span(&mut self, span: Span) {
569 self.format_missing_with_indent(source!(self, span).lo());
570 let lo = self.line_number + 1;
571 self.push_rewrite_inner(span, None);
572 let hi = self.line_number + 1;
573 self.skipped_range.push((lo, hi));
576 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
577 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
581 parse_session: &'a ParseSess,
583 snippet_provider: &'a SnippetProvider,
584 ) -> FmtVisitor<'a> {
587 codemap: parse_session.codemap(),
588 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
589 last_pos: BytePos(0),
590 block_indent: Indent::empty(),
592 is_if_else_block: false,
595 skipped_range: vec![],
599 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
600 self.snippet_provider.span_to_snippet(span)
603 pub fn snippet(&'b self, span: Span) -> &'a str {
604 self.opt_snippet(span).unwrap()
607 // Returns true if we should skip the following item.
608 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
609 if contains_skip(attrs) {
613 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
614 if attrs.is_empty() {
618 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
619 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
620 self.push_rewrite(span, rewrite);
625 fn walk_mod_items(&mut self, m: &ast::Mod) {
626 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
629 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
630 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
632 ast::StmtKind::Item(ref item) => Some(&**item),
637 if stmts.is_empty() {
641 // Extract leading `use ...;`.
642 let items: Vec<_> = stmts
644 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
645 .filter_map(|stmt| to_stmt_item(stmt))
648 if items.is_empty() {
649 self.visit_stmt(&stmts[0]);
650 self.walk_stmts(&stmts[1..]);
652 self.visit_items_with_reordering(&items);
653 self.walk_stmts(&stmts[items.len()..]);
657 fn walk_block_stmts(&mut self, b: &ast::Block) {
658 self.walk_stmts(&b.stmts)
664 vis: &ast::Visibility,
667 attrs: &[ast::Attribute],
670 self.push_str(&*utils::format_visibility(vis));
671 self.push_str("mod ");
672 self.push_str(&ident.to_string());
675 match self.config.brace_style() {
676 BraceStyle::AlwaysNextLine => {
677 let sep_str = format!("\n{}{{", self.block_indent.to_string(self.config));
678 self.push_str(&sep_str);
680 _ => self.push_str(" {"),
682 // Hackery to account for the closing }.
683 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
685 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
686 let body_snippet = body_snippet.trim();
687 if body_snippet.is_empty() {
690 self.last_pos = mod_lo;
691 self.block_indent = self.block_indent.block_indent(self.config);
692 self.visit_attrs(attrs, ast::AttrStyle::Inner);
693 self.walk_mod_items(m);
694 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
695 self.close_block(false);
697 self.last_pos = source!(self, m.inner).hi();
700 self.last_pos = source!(self, s).hi();
704 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
705 self.block_indent = Indent::empty();
706 self.walk_mod_items(m);
707 self.format_missing_with_indent(filemap.end_pos);
710 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
711 while let Some(pos) = self.snippet_provider
712 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
714 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
715 if snippet.trim().is_empty() {
724 pub fn get_context(&self) -> RewriteContext {
726 parse_session: self.parse_session,
727 codemap: self.codemap,
731 is_if_else_block: false,
732 force_one_line_chain: false,
733 snippet_provider: self.snippet_provider,
738 impl Rewrite for ast::NestedMetaItem {
739 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
741 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
742 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
747 impl Rewrite for ast::MetaItem {
748 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
749 Some(match self.node {
750 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
751 ast::MetaItemKind::List(ref list) => {
752 let name = self.name.as_str();
753 // 1 = `(`, 2 = `]` and `)`
754 let item_shape = shape
756 .shrink_left(name.len() + 1)
757 .and_then(|s| s.sub_width(2))?;
758 let items = itemize_list(
759 context.snippet_provider,
763 |nested_meta_item| nested_meta_item.span.lo(),
764 |nested_meta_item| nested_meta_item.span.hi(),
765 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
770 let item_vec = items.collect::<Vec<_>>();
771 let fmt = ListFormatting {
772 tactic: DefinitiveListTactic::Mixed,
774 trailing_separator: SeparatorTactic::Never,
775 separator_place: SeparatorPlace::Back,
777 ends_with_newline: false,
778 preserve_newline: false,
779 config: context.config,
781 format!("{}({})", name, write_list(&item_vec, &fmt)?)
783 ast::MetaItemKind::NameValue(ref literal) => {
784 let name = self.name.as_str();
786 let lit_shape = shape.shrink_left(name.len() + 3)?;
787 let value = rewrite_literal(context, literal, lit_shape)?;
788 format!("{} = {}", name, value)
794 impl Rewrite for ast::Attribute {
795 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
796 let prefix = match self.style {
797 ast::AttrStyle::Inner => "#!",
798 ast::AttrStyle::Outer => "#",
800 let snippet = context.snippet(self.span);
801 if self.is_sugared_doc {
802 let doc_shape = Shape {
803 width: cmp::min(shape.width, context.config.comment_width())
804 .checked_sub(shape.indent.width())
808 rewrite_doc_comment(snippet, doc_shape, context.config)
810 if contains_comment(snippet) {
811 return Some(snippet.to_owned());
814 let shape = shape.offset_left(prefix.len() + 1)?;
816 .rewrite(context, shape)
817 .map(|rw| format!("{}[{}]", prefix, rw))
822 /// Returns the first group of attributes that fills the given predicate.
823 /// We consider two doc comments are in different group if they are separated by normal comments.
824 fn take_while_with_pred<'a, P>(
825 context: &RewriteContext,
826 attrs: &'a [ast::Attribute],
828 ) -> &'a [ast::Attribute]
830 P: Fn(&ast::Attribute) -> bool,
832 let mut last_index = 0;
833 let mut iter = attrs.iter().enumerate().peekable();
834 while let Some((i, attr)) = iter.next() {
838 if let Some(&(_, next_attr)) = iter.peek() {
839 // Extract comments between two attributes.
840 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
841 let snippet = context.snippet(span_between_attr);
842 if count_newlines(snippet) >= 2 || snippet.contains('/') {
851 &attrs[..last_index + 1]
855 fn rewrite_first_group_attrs(
856 context: &RewriteContext,
857 attrs: &[ast::Attribute],
859 ) -> Option<(usize, String)> {
860 if attrs.is_empty() {
861 return Some((0, String::new()));
863 // Rewrite doc comments
864 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
865 if !sugared_docs.is_empty() {
866 let snippet = sugared_docs
868 .map(|a| context.snippet(a.span))
873 rewrite_doc_comment(&snippet, shape, context.config)?,
876 // Rewrite `#[derive(..)]`s.
877 if context.config.merge_derives() {
878 let derives = take_while_with_pred(context, attrs, is_derive);
879 if !derives.is_empty() {
880 let mut derive_args = vec![];
881 for derive in derives {
882 derive_args.append(&mut get_derive_args(context, derive)?);
884 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
887 // Rewrite the first attribute.
888 Some((1, attrs[0].rewrite(context, shape)?))
891 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
892 // Look at before and after comment and see if there are any empty lines.
893 let comment_begin = comment.chars().position(|c| c == '/');
894 let len = comment_begin.unwrap_or_else(|| comment.len());
895 let mlb = count_newlines(&comment[..len]) > 1;
896 let mla = if comment_begin.is_none() {
899 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
900 let len = comment_end.unwrap();
905 .filter(|c| *c == '\n')
908 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
911 impl<'a> Rewrite for [ast::Attribute] {
912 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
914 return Some(String::new());
916 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
917 if self.len() == 1 || first_group_len == self.len() {
918 Some(first_group_str)
920 let rest_str = self[first_group_len..].rewrite(context, shape)?;
921 let missing_span = mk_sp(
922 self[first_group_len - 1].span.hi(),
923 self[first_group_len].span.lo(),
925 // Preserve an empty line before/after doc comments.
926 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
927 let snippet = context.snippet(missing_span);
928 let (mla, mlb) = has_newlines_before_after_comment(snippet);
929 let comment = ::comment::recover_missing_comment_in_span(
931 shape.with_max_width(context.config),
935 let comment = if comment.is_empty() {
938 format!("{}{}\n{}", mla, comment, mlb)
944 shape.indent.to_string(context.config),
948 combine_strs_with_missing_comments(
961 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
962 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
963 let mut result = String::with_capacity(128);
964 result.push_str("#[derive(");
965 // 11 = `#[derive()]`
966 let initial_budget = shape.width.checked_sub(11)?;
967 let mut budget = initial_budget;
968 let num = derive_args.len();
969 for (i, a) in derive_args.iter().enumerate() {
971 let width = a.len() + 2;
974 // Remove trailing whitespace.
979 result.push_str(&(shape.indent + 9).to_string(context.config));
980 budget = initial_budget;
982 budget = budget.checked_sub(width).unwrap_or(0);
986 result.push_str(", ")
989 result.push_str(")]");
993 fn is_derive(attr: &ast::Attribute) -> bool {
994 attr.check_name("derive")
997 /// Returns the arguments of `#[derive(...)]`.
998 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
999 attr.meta_item_list().map(|meta_item_list| {
1002 .map(|nested_meta_item| context.snippet(nested_meta_item.span))
1007 // Rewrite `extern crate foo;` WITHOUT attributes.
1008 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1009 assert!(is_extern_crate(item));
1010 let new_str = context.snippet(item.span);
1011 Some(if contains_comment(new_str) {
1014 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1015 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1019 fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
1021 ast::StmtKind::Local(ref local) => &local.attrs,
1022 ast::StmtKind::Item(ref item) => &item.attrs,
1023 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
1024 ast::StmtKind::Mac(ref mac) => &mac.2,