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 syntax::{ast, visit};
14 use syntax::attr::{self, HasAttrs};
15 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
16 use syntax::parse::ParseSess;
18 use codemap::{LineRangeUtils, SpanUtils};
19 use comment::{combine_strs_with_missing_comments, contains_comment, CodeCharKind,
20 CommentCodeSlices, FindUncommented};
21 use comment::rewrite_comment;
22 use config::{BraceStyle, Config};
23 use expr::rewrite_literal;
24 use items::{format_impl, format_trait, format_trait_alias, rewrite_associated_impl_type,
25 rewrite_associated_type, rewrite_type_alias, FnSig, StaticParts, StructParts};
26 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
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 contains_macro_use_attr(attrs: &[ast::Attribute], span: Span) -> bool {
53 attr::contains_name(&filter_inline_attrs(attrs, span), "macro_use")
56 /// Returns true for `mod foo;` without any inline attributes.
57 /// We cannot reorder modules with attributes because doing so can break the code.
58 /// e.g. `#[macro_use]`.
59 fn is_mod_decl_without_attr(item: &ast::Item) -> bool {
60 is_mod_decl(item) && !contains_macro_use_attr(&item.attrs, item.span())
63 fn is_use_item(item: &ast::Item) -> bool {
65 ast::ItemKind::Use(_) => true,
70 fn is_use_item_without_attr(item: &ast::Item) -> bool {
71 is_use_item(item) && !contains_macro_use_attr(&item.attrs, item.span())
74 fn is_extern_crate(item: &ast::Item) -> bool {
76 ast::ItemKind::ExternCrate(..) => true,
81 fn is_extern_crate_without_attr(item: &ast::Item) -> bool {
82 is_extern_crate(item) && !contains_macro_use_attr(&item.attrs, item.span())
85 /// Creates a string slice corresponding to the specified span.
86 pub struct SnippetProvider<'a> {
87 /// A pointer to the content of the file we are formatting.
89 /// A position of the start of `big_snippet`, used as an offset.
93 impl<'a> SnippetProvider<'a> {
94 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
95 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
96 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
97 Some(&self.big_snippet[start_index..end_index])
100 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
101 let start_pos = start_pos.to_usize();
109 pub struct FmtVisitor<'a> {
110 pub parse_session: &'a ParseSess,
111 pub codemap: &'a CodeMap,
113 pub last_pos: BytePos,
114 // FIXME: use an RAII util or closure for indenting
115 pub block_indent: Indent,
116 pub config: &'a Config,
117 pub is_if_else_block: bool,
118 pub snippet_provider: &'a SnippetProvider<'a>,
119 pub line_number: usize,
120 pub skipped_range: Vec<(usize, usize)>,
123 impl<'b, 'a: 'b> FmtVisitor<'a> {
124 pub fn shape(&self) -> Shape {
125 Shape::indented(self.block_indent, self.config)
128 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
130 "visit_stmt: {:?} {:?}",
131 self.codemap.lookup_char_pos(stmt.span.lo()),
132 self.codemap.lookup_char_pos(stmt.span.hi())
136 ast::StmtKind::Item(ref item) => {
137 self.visit_item(item);
139 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
140 if contains_skip(get_attrs_from_stmt(stmt)) {
141 self.push_skipped_with_span(stmt.span());
143 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
144 self.push_rewrite(stmt.span(), rewrite)
147 ast::StmtKind::Mac(ref mac) => {
148 let (ref mac, _macro_style, ref attrs) = **mac;
149 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
150 self.push_skipped_with_span(stmt.span());
152 self.visit_mac(mac, None, MacroPosition::Statement);
154 self.format_missing(stmt.span.hi());
162 inner_attrs: Option<&[ast::Attribute]>,
166 "visit_block: {:?} {:?}",
167 self.codemap.lookup_char_pos(b.span.lo()),
168 self.codemap.lookup_char_pos(b.span.hi())
171 // Check if this block has braces.
172 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
174 self.last_pos = self.last_pos + brace_compensation;
175 self.block_indent = self.block_indent.block_indent(self.config);
178 if self.config.remove_blank_lines_at_start_or_end_of_block() {
179 if let Some(first_stmt) = b.stmts.first() {
180 let attr_lo = inner_attrs
181 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
183 // Attributes for an item in a statement position
184 // do not belong to the statement. (rust-lang/rust#34459)
185 if let ast::StmtKind::Item(ref item) = first_stmt.node {
188 first_stmt.attrs().first()
190 // Some stmts can have embedded attributes.
191 // e.g. `match { #![attr] ... }`
192 let attr_lo = attr.span.lo();
193 if attr_lo < first_stmt.span.lo() {
201 let snippet = self.snippet(mk_sp(
203 attr_lo.unwrap_or(first_stmt.span.lo()),
205 let len = CommentCodeSlices::new(snippet)
207 .and_then(|(kind, _, s)| {
208 if kind == CodeCharKind::Normal {
214 if let Some(len) = len {
215 self.last_pos = self.last_pos + BytePos::from_usize(len);
220 // Format inner attributes if available.
221 let skip_rewrite = if let Some(attrs) = inner_attrs {
222 self.visit_attrs(attrs, ast::AttrStyle::Inner)
228 self.push_rewrite(b.span, None);
229 self.close_block(false);
230 self.last_pos = source!(self, b.span).hi();
234 self.walk_block_stmts(b);
236 if !b.stmts.is_empty() {
237 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
238 if utils::semicolon_for_expr(&self.get_context(), expr) {
244 let mut remove_len = BytePos(0);
245 if self.config.remove_blank_lines_at_start_or_end_of_block() {
246 if let Some(stmt) = b.stmts.last() {
247 let snippet = self.snippet(mk_sp(
249 source!(self, b.span).hi() - brace_compensation,
251 let len = CommentCodeSlices::new(snippet)
253 .and_then(|(kind, _, s)| {
254 if kind == CodeCharKind::Normal && s.trim().is_empty() {
260 if let Some(len) = len {
261 remove_len = BytePos::from_usize(len);
266 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
267 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
268 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
269 snippet.contains("//") || snippet.contains("/*")
271 // FIXME: we should compress any newlines here to just one
272 if unindent_comment {
273 self.block_indent = self.block_indent.block_unindent(self.config);
275 self.format_missing_with_indent(
276 source!(self, b.span).hi() - brace_compensation - remove_len,
278 if unindent_comment {
279 self.block_indent = self.block_indent.block_indent(self.config);
281 self.close_block(unindent_comment);
282 self.last_pos = source!(self, b.span).hi();
285 // FIXME: this is a terrible hack to indent the comments between the last
286 // item in the block and the closing brace to the block's level.
287 // The closing brace itself, however, should be indented at a shallower
289 fn close_block(&mut self, unindent_comment: bool) {
290 let total_len = self.buffer.len();
291 let chars_too_many = if unindent_comment {
293 } else if self.config.hard_tabs() {
296 self.config.tab_spaces()
298 self.buffer.truncate(total_len - chars_too_many);
300 self.block_indent = self.block_indent.block_unindent(self.config);
303 // Note that this only gets called for function definitions. Required methods
304 // on traits do not get handled here.
308 generics: &ast::Generics,
311 defaultness: ast::Defaultness,
312 inner_attrs: Option<&[ast::Attribute]>,
314 let indent = self.block_indent;
316 let rewrite = match fk {
317 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
322 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
323 mk_sp(s.lo(), b.span.lo()),
327 visit::FnKind::Closure(_) => unreachable!(),
330 if let Some(fn_str) = rewrite {
331 self.format_missing_with_indent(source!(self, s).lo());
332 self.push_str(&fn_str);
333 if let Some(c) = fn_str.chars().last() {
335 self.last_pos = source!(self, block.span).hi();
340 self.format_missing(source!(self, block.span).lo());
343 self.last_pos = source!(self, block.span).lo();
344 self.visit_block(block, inner_attrs, true)
347 pub fn visit_item(&mut self, item: &ast::Item) {
348 skip_out_of_file_lines_range_visitor!(self, item.span);
350 // This is where we bail out if there is a skip attribute. This is only
351 // complex in the module case. It is complex because the module could be
352 // in a separate file and there might be attributes in both files, but
353 // the AST lumps them all together.
355 let mut attrs = &item.attrs;
357 // Module is inline, in this case we treat it like any other item.
358 _ if !is_mod_decl(item) => {
359 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
360 self.push_skipped_with_span(item.span());
364 // Module is not inline, but should be skipped.
365 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
368 // Module is not inline and should not be skipped. We want
369 // to process only the attributes in the current file.
370 ast::ItemKind::Mod(..) => {
371 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
372 // Assert because if we should skip it should be caught by
374 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
375 attrs = &filtered_attrs;
378 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
379 self.push_skipped_with_span(item.span());
386 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
387 ast::ItemKind::Impl(..) => {
388 let snippet = self.snippet(item.span);
389 let where_span_end = snippet
390 .find_uncommented("{")
391 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
392 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
393 self.push_rewrite(item.span, rw);
395 ast::ItemKind::Trait(..) => {
396 let rw = format_trait(&self.get_context(), item, self.block_indent);
397 self.push_rewrite(item.span, rw);
399 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
400 let shape = Shape::indented(self.block_indent, self.config);
401 let rw = format_trait_alias(
408 self.push_rewrite(item.span, rw);
410 ast::ItemKind::ExternCrate(_) => {
411 let rw = rewrite_extern_crate(&self.get_context(), item);
412 self.push_rewrite(item.span, rw);
414 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
415 self.visit_struct(&StructParts::from_item(item));
417 ast::ItemKind::Enum(ref def, ref generics) => {
418 self.format_missing_with_indent(source!(self, item.span).lo());
419 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
420 self.last_pos = source!(self, item.span).hi();
422 ast::ItemKind::Mod(ref module) => {
423 let is_inline = !is_mod_decl(item);
424 self.format_missing_with_indent(source!(self, item.span).lo());
425 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
427 ast::ItemKind::Mac(ref mac) => {
428 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
430 ast::ItemKind::ForeignMod(ref foreign_mod) => {
431 self.format_missing_with_indent(source!(self, item.span).lo());
432 self.format_foreign_mod(foreign_mod, item.span);
434 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
435 self.visit_static(&StaticParts::from_item(item));
437 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
439 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
443 ast::Defaultness::Final,
447 ast::ItemKind::Ty(ref ty, ref generics) => {
448 let rewrite = rewrite_type_alias(
457 self.push_rewrite(item.span, rewrite);
459 ast::ItemKind::GlobalAsm(..) => {
460 let snippet = Some(self.snippet(item.span).to_owned());
461 self.push_rewrite(item.span, snippet);
463 ast::ItemKind::MacroDef(ref def) => {
464 let rewrite = rewrite_macro_def(
473 self.push_rewrite(item.span, rewrite);
478 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
479 skip_out_of_file_lines_range_visitor!(self, ti.span);
481 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
482 self.push_skipped_with_span(ti.span());
487 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
488 ast::TraitItemKind::Method(ref sig, None) => {
489 let indent = self.block_indent;
491 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
492 self.push_rewrite(ti.span, rewrite);
494 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
496 visit::FnKind::Method(ti.ident, sig, None, body),
500 ast::Defaultness::Final,
504 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
505 let rewrite = rewrite_associated_type(
507 type_default.as_ref(),
508 Some(type_param_bounds),
512 self.push_rewrite(ti.span, rewrite);
514 ast::TraitItemKind::Macro(ref mac) => {
515 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
520 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
521 skip_out_of_file_lines_range_visitor!(self, ii.span);
523 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
524 self.push_skipped_with_span(ii.span());
529 ast::ImplItemKind::Method(ref sig, ref body) => {
531 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
539 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
540 ast::ImplItemKind::Type(ref ty) => {
541 let rewrite = rewrite_associated_impl_type(
549 self.push_rewrite(ii.span, rewrite);
551 ast::ImplItemKind::Macro(ref mac) => {
552 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
557 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
558 skip_out_of_file_lines_range_visitor!(self, mac.span);
561 let shape = self.shape().sub_width(1).unwrap();
562 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
563 self.push_rewrite(mac.span, rewrite);
566 pub fn push_str(&mut self, s: &str) {
567 self.line_number += count_newlines(s);
568 self.buffer.push_str(s);
571 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
572 if let Some(ref s) = rewrite {
575 let snippet = self.snippet(span);
576 self.push_str(snippet);
578 self.last_pos = source!(self, span).hi();
581 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
582 self.format_missing_with_indent(source!(self, span).lo());
583 self.push_rewrite_inner(span, rewrite);
586 pub fn push_skipped_with_span(&mut self, span: Span) {
587 self.format_missing_with_indent(source!(self, span).lo());
588 let lo = self.line_number + 1;
589 self.push_rewrite_inner(span, None);
590 let hi = self.line_number + 1;
591 self.skipped_range.push((lo, hi));
594 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
595 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
599 parse_session: &'a ParseSess,
601 snippet_provider: &'a SnippetProvider,
602 ) -> FmtVisitor<'a> {
605 codemap: parse_session.codemap(),
606 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
607 last_pos: BytePos(0),
608 block_indent: Indent::empty(),
610 is_if_else_block: false,
613 skipped_range: vec![],
617 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
618 self.snippet_provider.span_to_snippet(span)
621 pub fn snippet(&'b self, span: Span) -> &'a str {
622 self.opt_snippet(span).unwrap()
625 // Returns true if we should skip the following item.
626 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
627 if contains_skip(attrs) {
631 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
632 if attrs.is_empty() {
636 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
637 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
638 self.push_rewrite(span, rewrite);
643 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
645 F: Fn(&ast::Item) -> bool,
647 let mut last = self.codemap.lookup_line_range(items_left[0].span());
648 let item_length = items_left
651 is_item(&***ppi) && (!in_group || {
652 let current = self.codemap.lookup_line_range(ppi.span());
653 let in_same_group = current.lo < last.hi + 2;
659 let items = &items_left[..item_length];
661 let at_least_one_in_file_lines = items
663 .any(|item| !out_of_file_lines_range!(self, item.span));
665 if at_least_one_in_file_lines {
666 self.format_imports(items);
669 self.push_rewrite(item.span, None);
676 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
677 macro try_reorder_items_with($reorder: ident, $in_group: ident, $pred: ident) {
678 if self.config.$reorder() && $pred(&*items_left[0]) {
680 self.reorder_items(items_left, &$pred, self.config.$in_group());
681 let (_, rest) = items_left.split_at(used_items_len);
687 while !items_left.is_empty() {
688 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
689 // subsequent items that have the same item kind to be reordered within
690 // `format_imports`. Otherwise, just format the next item for output.
692 try_reorder_items_with!(
694 reorder_imports_in_group,
695 is_use_item_without_attr
697 try_reorder_items_with!(
698 reorder_extern_crates,
699 reorder_extern_crates_in_group,
700 is_extern_crate_without_attr
702 try_reorder_items_with!(reorder_modules, reorder_modules, is_mod_decl_without_attr);
704 // Reaching here means items were not reordered. There must be at least
705 // one item left in `items_left`, so calling `unwrap()` here is safe.
706 let (item, rest) = items_left.split_first().unwrap();
707 self.visit_item(item);
712 fn walk_mod_items(&mut self, m: &ast::Mod) {
713 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
716 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
717 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
719 ast::StmtKind::Item(ref item) => Some(&**item),
724 if stmts.is_empty() {
728 // Extract leading `use ...;`.
729 let items: Vec<_> = stmts
731 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
732 .filter_map(|stmt| to_stmt_item(stmt))
735 if items.is_empty() {
736 self.visit_stmt(&stmts[0]);
737 self.walk_stmts(&stmts[1..]);
739 self.walk_items(&items);
740 self.walk_stmts(&stmts[items.len()..]);
744 fn walk_block_stmts(&mut self, b: &ast::Block) {
745 self.walk_stmts(&b.stmts)
751 vis: &ast::Visibility,
754 attrs: &[ast::Attribute],
757 self.push_str(&*utils::format_visibility(vis));
758 self.push_str("mod ");
759 self.push_str(&ident.to_string());
762 match self.config.brace_style() {
763 BraceStyle::AlwaysNextLine => {
764 let sep_str = format!("\n{}{{", self.block_indent.to_string(self.config));
765 self.push_str(&sep_str);
767 _ => self.push_str(" {"),
769 // Hackery to account for the closing }.
770 let mod_lo = self.codemap.span_after(source!(self, s), "{");
772 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
773 let body_snippet = body_snippet.trim();
774 if body_snippet.is_empty() {
777 self.last_pos = mod_lo;
778 self.block_indent = self.block_indent.block_indent(self.config);
779 self.visit_attrs(attrs, ast::AttrStyle::Inner);
780 self.walk_mod_items(m);
781 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
782 self.close_block(false);
784 self.last_pos = source!(self, m.inner).hi();
787 self.last_pos = source!(self, s).hi();
791 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
792 self.block_indent = Indent::empty();
793 self.walk_mod_items(m);
794 self.format_missing_with_indent(filemap.end_pos);
797 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
798 while let Some(pos) = self.codemap
799 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
801 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
802 if snippet.trim().is_empty() {
811 pub fn get_context(&self) -> RewriteContext {
813 parse_session: self.parse_session,
814 codemap: self.codemap,
818 is_if_else_block: false,
819 force_one_line_chain: false,
820 snippet_provider: self.snippet_provider,
825 impl Rewrite for ast::NestedMetaItem {
826 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
828 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
829 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
834 impl Rewrite for ast::MetaItem {
835 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
836 Some(match self.node {
837 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
838 ast::MetaItemKind::List(ref list) => {
839 let name = self.name.as_str();
840 // 1 = `(`, 2 = `]` and `)`
841 let item_shape = shape
843 .shrink_left(name.len() + 1)
844 .and_then(|s| s.sub_width(2))?;
845 let items = itemize_list(
850 |nested_meta_item| nested_meta_item.span.lo(),
851 |nested_meta_item| nested_meta_item.span.hi(),
852 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
857 let item_vec = items.collect::<Vec<_>>();
858 let fmt = ListFormatting {
859 tactic: DefinitiveListTactic::Mixed,
861 trailing_separator: SeparatorTactic::Never,
862 separator_place: SeparatorPlace::Back,
864 ends_with_newline: false,
865 preserve_newline: false,
866 config: context.config,
868 format!("{}({})", name, write_list(&item_vec, &fmt)?)
870 ast::MetaItemKind::NameValue(ref literal) => {
871 let name = self.name.as_str();
873 let lit_shape = shape.shrink_left(name.len() + 3)?;
874 let value = rewrite_literal(context, literal, lit_shape)?;
875 format!("{} = {}", name, value)
881 impl Rewrite for ast::Attribute {
882 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
883 let prefix = match self.style {
884 ast::AttrStyle::Inner => "#!",
885 ast::AttrStyle::Outer => "#",
887 let snippet = context.snippet(self.span);
888 if self.is_sugared_doc {
889 let doc_shape = Shape {
890 width: cmp::min(shape.width, context.config.comment_width())
891 .checked_sub(shape.indent.width())
895 rewrite_comment(snippet, false, doc_shape, context.config)
897 if contains_comment(snippet) {
898 return Some(snippet.to_owned());
901 let shape = shape.offset_left(prefix.len() + 1)?;
903 .rewrite(context, shape)
904 .map(|rw| format!("{}[{}]", prefix, rw))
909 /// Returns the first group of attributes that fills the given predicate.
910 /// We consider two doc comments are in different group if they are separated by normal comments.
911 fn take_while_with_pred<'a, P>(
912 context: &RewriteContext,
913 attrs: &'a [ast::Attribute],
915 ) -> &'a [ast::Attribute]
917 P: Fn(&ast::Attribute) -> bool,
919 let mut last_index = 0;
920 let mut iter = attrs.iter().enumerate().peekable();
921 while let Some((i, attr)) = iter.next() {
925 if let Some(&(_, next_attr)) = iter.peek() {
926 // Extract comments between two attributes.
927 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
928 let snippet = context.snippet(span_between_attr);
929 if count_newlines(snippet) >= 2 || snippet.contains('/') {
938 &attrs[..last_index + 1]
942 fn rewrite_first_group_attrs(
943 context: &RewriteContext,
944 attrs: &[ast::Attribute],
946 ) -> Option<(usize, String)> {
947 if attrs.is_empty() {
948 return Some((0, String::new()));
950 // Rewrite doc comments
951 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
952 if !sugared_docs.is_empty() {
953 let snippet = sugared_docs
955 .map(|a| context.snippet(a.span))
960 rewrite_comment(&snippet, false, shape, context.config)?,
963 // Rewrite `#[derive(..)]`s.
964 if context.config.merge_derives() {
965 let derives = take_while_with_pred(context, attrs, is_derive);
966 if !derives.is_empty() {
967 let mut derive_args = vec![];
968 for derive in derives {
969 derive_args.append(&mut get_derive_args(context, derive)?);
971 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
974 // Rewrite the first attribute.
975 Some((1, attrs[0].rewrite(context, shape)?))
978 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
979 // Look at before and after comment and see if there are any empty lines.
980 let comment_begin = comment.chars().position(|c| c == '/');
981 let len = comment_begin.unwrap_or_else(|| comment.len());
982 let mlb = count_newlines(&comment[..len]) > 1;
983 let mla = if comment_begin.is_none() {
986 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
987 let len = comment_end.unwrap();
992 .filter(|c| *c == '\n')
995 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
998 impl<'a> Rewrite for [ast::Attribute] {
999 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1000 if self.is_empty() {
1001 return Some(String::new());
1003 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
1004 if self.len() == 1 || first_group_len == self.len() {
1005 Some(first_group_str)
1007 let rest_str = self[first_group_len..].rewrite(context, shape)?;
1008 let missing_span = mk_sp(
1009 self[first_group_len - 1].span.hi(),
1010 self[first_group_len].span.lo(),
1012 // Preserve an empty line before/after doc comments.
1013 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
1014 let snippet = context.snippet(missing_span);
1015 let (mla, mlb) = has_newlines_before_after_comment(snippet);
1016 let comment = ::comment::recover_missing_comment_in_span(
1018 shape.with_max_width(context.config),
1022 let comment = if comment.is_empty() {
1023 format!("\n{}", mlb)
1025 format!("{}{}\n{}", mla, comment, mlb)
1031 shape.indent.to_string(context.config),
1035 combine_strs_with_missing_comments(
1048 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
1049 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
1050 let mut result = String::with_capacity(128);
1051 result.push_str("#[derive(");
1052 // 11 = `#[derive()]`
1053 let initial_budget = shape.width.checked_sub(11)?;
1054 let mut budget = initial_budget;
1055 let num = derive_args.len();
1056 for (i, a) in derive_args.iter().enumerate() {
1058 let width = a.len() + 2;
1061 // Remove trailing whitespace.
1066 result.push_str(&(shape.indent + 9).to_string(context.config));
1067 budget = initial_budget;
1069 budget = budget.checked_sub(width).unwrap_or(0);
1073 result.push_str(", ")
1076 result.push_str(")]");
1080 fn is_derive(attr: &ast::Attribute) -> bool {
1081 attr.check_name("derive")
1084 /// Returns the arguments of `#[derive(...)]`.
1085 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
1086 attr.meta_item_list().map(|meta_item_list| {
1089 .map(|nested_meta_item| context.snippet(nested_meta_item.span))
1094 // Rewrite `extern crate foo;` WITHOUT attributes.
1095 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1096 assert!(is_extern_crate(item));
1097 let new_str = context.snippet(item.span);
1098 Some(if contains_comment(new_str) {
1101 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1102 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1106 fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
1108 ast::StmtKind::Local(ref local) => &local.attrs,
1109 ast::StmtKind::Item(ref item) => &item.attrs,
1110 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
1111 ast::StmtKind::Mac(ref mac) => &mac.2,