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(
472 self.push_rewrite(item.span, rewrite);
477 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
478 skip_out_of_file_lines_range_visitor!(self, ti.span);
480 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
481 self.push_skipped_with_span(ti.span());
486 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
487 ast::TraitItemKind::Method(ref sig, None) => {
488 let indent = self.block_indent;
490 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
491 self.push_rewrite(ti.span, rewrite);
493 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
495 visit::FnKind::Method(ti.ident, sig, None, body),
499 ast::Defaultness::Final,
503 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
504 let rewrite = rewrite_associated_type(
506 type_default.as_ref(),
507 Some(type_param_bounds),
511 self.push_rewrite(ti.span, rewrite);
513 ast::TraitItemKind::Macro(ref mac) => {
514 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
519 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
520 skip_out_of_file_lines_range_visitor!(self, ii.span);
522 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
523 self.push_skipped_with_span(ii.span());
528 ast::ImplItemKind::Method(ref sig, ref body) => {
530 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
538 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
539 ast::ImplItemKind::Type(ref ty) => {
540 let rewrite = rewrite_associated_impl_type(
548 self.push_rewrite(ii.span, rewrite);
550 ast::ImplItemKind::Macro(ref mac) => {
551 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
556 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
557 skip_out_of_file_lines_range_visitor!(self, mac.span);
560 let shape = self.shape().sub_width(1).unwrap();
561 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
562 self.push_rewrite(mac.span, rewrite);
565 pub fn push_str(&mut self, s: &str) {
566 self.line_number += count_newlines(s);
567 self.buffer.push_str(s);
570 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
571 if let Some(ref s) = rewrite {
574 let snippet = self.snippet(span);
575 self.push_str(snippet);
577 self.last_pos = source!(self, span).hi();
580 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
581 self.format_missing_with_indent(source!(self, span).lo());
582 self.push_rewrite_inner(span, rewrite);
585 pub fn push_skipped_with_span(&mut self, span: Span) {
586 self.format_missing_with_indent(source!(self, span).lo());
587 let lo = self.line_number + 1;
588 self.push_rewrite_inner(span, None);
589 let hi = self.line_number + 1;
590 self.skipped_range.push((lo, hi));
593 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
594 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
598 parse_session: &'a ParseSess,
600 snippet_provider: &'a SnippetProvider,
601 ) -> FmtVisitor<'a> {
604 codemap: parse_session.codemap(),
605 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
606 last_pos: BytePos(0),
607 block_indent: Indent::empty(),
609 is_if_else_block: false,
612 skipped_range: vec![],
616 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
617 self.snippet_provider.span_to_snippet(span)
620 pub fn snippet(&'b self, span: Span) -> &'a str {
621 self.opt_snippet(span).unwrap()
624 // Returns true if we should skip the following item.
625 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
626 if contains_skip(attrs) {
630 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
631 if attrs.is_empty() {
635 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
636 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
637 self.push_rewrite(span, rewrite);
642 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
644 F: Fn(&ast::Item) -> bool,
646 let mut last = self.codemap.lookup_line_range(items_left[0].span());
647 let item_length = items_left
650 is_item(&***ppi) && (!in_group || {
651 let current = self.codemap.lookup_line_range(ppi.span());
652 let in_same_group = current.lo < last.hi + 2;
658 let items = &items_left[..item_length];
660 let at_least_one_in_file_lines = items
662 .any(|item| !out_of_file_lines_range!(self, item.span));
664 if at_least_one_in_file_lines {
665 self.format_imports(items);
668 self.push_rewrite(item.span, None);
675 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
676 macro try_reorder_items_with($reorder: ident, $in_group: ident, $pred: ident) {
677 if self.config.$reorder() && $pred(&*items_left[0]) {
679 self.reorder_items(items_left, &$pred, self.config.$in_group());
680 let (_, rest) = items_left.split_at(used_items_len);
686 while !items_left.is_empty() {
687 // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
688 // subsequent items that have the same item kind to be reordered within
689 // `format_imports`. Otherwise, just format the next item for output.
691 try_reorder_items_with!(
693 reorder_imports_in_group,
694 is_use_item_without_attr
696 try_reorder_items_with!(
697 reorder_extern_crates,
698 reorder_extern_crates_in_group,
699 is_extern_crate_without_attr
701 try_reorder_items_with!(reorder_modules, reorder_modules, is_mod_decl_without_attr);
703 // Reaching here means items were not reordered. There must be at least
704 // one item left in `items_left`, so calling `unwrap()` here is safe.
705 let (item, rest) = items_left.split_first().unwrap();
706 self.visit_item(item);
711 fn walk_mod_items(&mut self, m: &ast::Mod) {
712 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
715 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
716 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
718 ast::StmtKind::Item(ref item) => Some(&**item),
723 if stmts.is_empty() {
727 // Extract leading `use ...;`.
728 let items: Vec<_> = stmts
730 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
731 .filter_map(|stmt| to_stmt_item(stmt))
734 if items.is_empty() {
735 self.visit_stmt(&stmts[0]);
736 self.walk_stmts(&stmts[1..]);
738 self.walk_items(&items);
739 self.walk_stmts(&stmts[items.len()..]);
743 fn walk_block_stmts(&mut self, b: &ast::Block) {
744 self.walk_stmts(&b.stmts)
750 vis: &ast::Visibility,
753 attrs: &[ast::Attribute],
756 self.push_str(&*utils::format_visibility(vis));
757 self.push_str("mod ");
758 self.push_str(&ident.to_string());
761 match self.config.brace_style() {
762 BraceStyle::AlwaysNextLine => {
763 let sep_str = format!("\n{}{{", self.block_indent.to_string(self.config));
764 self.push_str(&sep_str);
766 _ => self.push_str(" {"),
768 // Hackery to account for the closing }.
769 let mod_lo = self.codemap.span_after(source!(self, s), "{");
771 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
772 let body_snippet = body_snippet.trim();
773 if body_snippet.is_empty() {
776 self.last_pos = mod_lo;
777 self.block_indent = self.block_indent.block_indent(self.config);
778 self.visit_attrs(attrs, ast::AttrStyle::Inner);
779 self.walk_mod_items(m);
780 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
781 self.close_block(false);
783 self.last_pos = source!(self, m.inner).hi();
786 self.last_pos = source!(self, s).hi();
790 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
791 self.block_indent = Indent::empty();
792 self.walk_mod_items(m);
793 self.format_missing_with_indent(filemap.end_pos);
796 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
797 while let Some(pos) = self.codemap
798 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
800 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
801 if snippet.trim().is_empty() {
810 pub fn get_context(&self) -> RewriteContext {
812 parse_session: self.parse_session,
813 codemap: self.codemap,
817 is_if_else_block: false,
818 force_one_line_chain: false,
819 snippet_provider: self.snippet_provider,
824 impl Rewrite for ast::NestedMetaItem {
825 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
827 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
828 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
833 impl Rewrite for ast::MetaItem {
834 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
835 Some(match self.node {
836 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
837 ast::MetaItemKind::List(ref list) => {
838 let name = self.name.as_str();
839 // 1 = `(`, 2 = `]` and `)`
840 let item_shape = shape
842 .shrink_left(name.len() + 1)
843 .and_then(|s| s.sub_width(2))?;
844 let items = itemize_list(
849 |nested_meta_item| nested_meta_item.span.lo(),
850 |nested_meta_item| nested_meta_item.span.hi(),
851 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
856 let item_vec = items.collect::<Vec<_>>();
857 let fmt = ListFormatting {
858 tactic: DefinitiveListTactic::Mixed,
860 trailing_separator: SeparatorTactic::Never,
861 separator_place: SeparatorPlace::Back,
863 ends_with_newline: false,
864 preserve_newline: false,
865 config: context.config,
867 format!("{}({})", name, write_list(&item_vec, &fmt)?)
869 ast::MetaItemKind::NameValue(ref literal) => {
870 let name = self.name.as_str();
872 let lit_shape = shape.shrink_left(name.len() + 3)?;
873 let value = rewrite_literal(context, literal, lit_shape)?;
874 format!("{} = {}", name, value)
880 impl Rewrite for ast::Attribute {
881 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
882 let prefix = match self.style {
883 ast::AttrStyle::Inner => "#!",
884 ast::AttrStyle::Outer => "#",
886 let snippet = context.snippet(self.span);
887 if self.is_sugared_doc {
888 let doc_shape = Shape {
889 width: cmp::min(shape.width, context.config.comment_width())
890 .checked_sub(shape.indent.width())
894 rewrite_comment(snippet, false, doc_shape, context.config)
896 if contains_comment(snippet) {
897 return Some(snippet.to_owned());
900 let shape = shape.offset_left(prefix.len() + 1)?;
902 .rewrite(context, shape)
903 .map(|rw| format!("{}[{}]", prefix, rw))
908 /// Returns the first group of attributes that fills the given predicate.
909 /// We consider two doc comments are in different group if they are separated by normal comments.
910 fn take_while_with_pred<'a, P>(
911 context: &RewriteContext,
912 attrs: &'a [ast::Attribute],
914 ) -> &'a [ast::Attribute]
916 P: Fn(&ast::Attribute) -> bool,
918 let mut last_index = 0;
919 let mut iter = attrs.iter().enumerate().peekable();
920 while let Some((i, attr)) = iter.next() {
924 if let Some(&(_, next_attr)) = iter.peek() {
925 // Extract comments between two attributes.
926 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
927 let snippet = context.snippet(span_between_attr);
928 if count_newlines(snippet) >= 2 || snippet.contains('/') {
937 &attrs[..last_index + 1]
941 fn rewrite_first_group_attrs(
942 context: &RewriteContext,
943 attrs: &[ast::Attribute],
945 ) -> Option<(usize, String)> {
946 if attrs.is_empty() {
947 return Some((0, String::new()));
949 // Rewrite doc comments
950 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
951 if !sugared_docs.is_empty() {
952 let snippet = sugared_docs
954 .map(|a| context.snippet(a.span))
959 rewrite_comment(&snippet, false, shape, context.config)?,
962 // Rewrite `#[derive(..)]`s.
963 if context.config.merge_derives() {
964 let derives = take_while_with_pred(context, attrs, is_derive);
965 if !derives.is_empty() {
966 let mut derive_args = vec![];
967 for derive in derives {
968 derive_args.append(&mut get_derive_args(context, derive)?);
970 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
973 // Rewrite the first attribute.
974 Some((1, attrs[0].rewrite(context, shape)?))
977 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
978 // Look at before and after comment and see if there are any empty lines.
979 let comment_begin = comment.chars().position(|c| c == '/');
980 let len = comment_begin.unwrap_or_else(|| comment.len());
981 let mlb = count_newlines(&comment[..len]) > 1;
982 let mla = if comment_begin.is_none() {
985 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
986 let len = comment_end.unwrap();
991 .filter(|c| *c == '\n')
994 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
997 impl<'a> Rewrite for [ast::Attribute] {
998 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1000 return Some(String::new());
1002 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
1003 if self.len() == 1 || first_group_len == self.len() {
1004 Some(first_group_str)
1006 let rest_str = self[first_group_len..].rewrite(context, shape)?;
1007 let missing_span = mk_sp(
1008 self[first_group_len - 1].span.hi(),
1009 self[first_group_len].span.lo(),
1011 // Preserve an empty line before/after doc comments.
1012 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
1013 let snippet = context.snippet(missing_span);
1014 let (mla, mlb) = has_newlines_before_after_comment(snippet);
1015 let comment = ::comment::recover_missing_comment_in_span(
1017 shape.with_max_width(context.config),
1021 let comment = if comment.is_empty() {
1022 format!("\n{}", mlb)
1024 format!("{}{}\n{}", mla, comment, mlb)
1030 shape.indent.to_string(context.config),
1034 combine_strs_with_missing_comments(
1047 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
1048 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
1049 let mut result = String::with_capacity(128);
1050 result.push_str("#[derive(");
1051 // 11 = `#[derive()]`
1052 let initial_budget = shape.width.checked_sub(11)?;
1053 let mut budget = initial_budget;
1054 let num = derive_args.len();
1055 for (i, a) in derive_args.iter().enumerate() {
1057 let width = a.len() + 2;
1060 // Remove trailing whitespace.
1065 result.push_str(&(shape.indent + 9).to_string(context.config));
1066 budget = initial_budget;
1068 budget = budget.checked_sub(width).unwrap_or(0);
1072 result.push_str(", ")
1075 result.push_str(")]");
1079 fn is_derive(attr: &ast::Attribute) -> bool {
1080 attr.check_name("derive")
1083 /// Returns the arguments of `#[derive(...)]`.
1084 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
1085 attr.meta_item_list().map(|meta_item_list| {
1088 .map(|nested_meta_item| context.snippet(nested_meta_item.span))
1093 // Rewrite `extern crate foo;` WITHOUT attributes.
1094 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1095 assert!(is_extern_crate(item));
1096 let new_str = context.snippet(item.span);
1097 Some(if contains_comment(new_str) {
1100 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1101 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1105 fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
1107 ast::StmtKind::Local(ref local) => &local.attrs,
1108 ast::StmtKind::Item(ref item) => &item.attrs,
1109 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
1110 ast::StmtKind::Mac(ref mac) => &mac.2,