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::HasAttrs;
15 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
16 use syntax::parse::ParseSess;
18 use expr::rewrite_literal;
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{combine_strs_with_missing_comments, contains_comment, remove_trailing_white_spaces,
22 CodeCharKind, CommentCodeSlices, FindUncommented};
23 use comment::rewrite_comment;
24 use config::{BraceStyle, Config};
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, DefinitiveListTactic, ListFormatting, SeparatorPlace,
29 use macros::{rewrite_macro, MacroPosition};
31 use rewrite::{Rewrite, RewriteContext};
32 use shape::{Indent, Shape};
33 use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
35 fn is_use_item(item: &ast::Item) -> bool {
37 ast::ItemKind::Use(_) => true,
42 fn is_extern_crate(item: &ast::Item) -> bool {
44 ast::ItemKind::ExternCrate(..) => true,
49 /// Creates a string slice corresponding to the specified span.
50 pub struct SnippetProvider<'a> {
51 /// A pointer to the content of the file we are formatting.
53 /// A position of the start of `big_snippet`, used as an offset.
57 impl<'a> SnippetProvider<'a> {
58 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
59 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
60 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
61 Some(&self.big_snippet[start_index..end_index])
64 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
65 let start_pos = start_pos.to_usize();
73 pub struct FmtVisitor<'a> {
74 pub parse_session: &'a ParseSess,
75 pub codemap: &'a CodeMap,
77 pub last_pos: BytePos,
78 // FIXME: use an RAII util or closure for indenting
79 pub block_indent: Indent,
80 pub config: &'a Config,
81 pub is_if_else_block: bool,
82 pub snippet_provider: &'a SnippetProvider<'a>,
83 pub line_number: usize,
84 pub skipped_range: Vec<(usize, usize)>,
87 impl<'b, 'a: 'b> FmtVisitor<'a> {
88 pub fn shape(&self) -> Shape {
89 Shape::indented(self.block_indent, self.config)
92 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
94 "visit_stmt: {:?} {:?}",
95 self.codemap.lookup_char_pos(stmt.span.lo()),
96 self.codemap.lookup_char_pos(stmt.span.hi())
100 ast::StmtKind::Item(ref item) => {
101 self.visit_item(item);
103 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
104 if contains_skip(get_attrs_from_stmt(stmt)) {
105 self.push_skipped_with_span(stmt.span());
107 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
108 self.push_rewrite(stmt.span(), rewrite)
111 ast::StmtKind::Mac(ref mac) => {
112 let (ref mac, _macro_style, ref attrs) = **mac;
113 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
114 self.push_skipped_with_span(stmt.span());
116 self.visit_mac(mac, None, MacroPosition::Statement);
118 self.format_missing(stmt.span.hi());
126 inner_attrs: Option<&[ast::Attribute]>,
130 "visit_block: {:?} {:?}",
131 self.codemap.lookup_char_pos(b.span.lo()),
132 self.codemap.lookup_char_pos(b.span.hi())
135 // Check if this block has braces.
136 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
138 self.last_pos = self.last_pos + brace_compensation;
139 self.block_indent = self.block_indent.block_indent(self.config);
142 if self.config.remove_blank_lines_at_start_or_end_of_block() {
143 if let Some(first_stmt) = b.stmts.first() {
144 let attr_lo = inner_attrs
145 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
147 // Attributes for an item in a statement position
148 // do not belong to the statement. (rust-lang/rust#34459)
149 if let ast::StmtKind::Item(ref item) = first_stmt.node {
152 first_stmt.attrs().first()
154 // Some stmts can have embedded attributes.
155 // e.g. `match { #![attr] ... }`
156 let attr_lo = attr.span.lo();
157 if attr_lo < first_stmt.span.lo() {
165 let snippet = self.snippet(mk_sp(
167 attr_lo.unwrap_or(first_stmt.span.lo()),
169 let len = CommentCodeSlices::new(snippet)
171 .and_then(|(kind, _, s)| {
172 if kind == CodeCharKind::Normal {
178 if let Some(len) = len {
179 self.last_pos = self.last_pos + BytePos::from_usize(len);
184 // Format inner attributes if available.
185 let skip_rewrite = if let Some(attrs) = inner_attrs {
186 self.visit_attrs(attrs, ast::AttrStyle::Inner)
192 self.push_rewrite(b.span, None);
193 self.close_block(false);
194 self.last_pos = source!(self, b.span).hi();
198 self.walk_block_stmts(b);
200 if !b.stmts.is_empty() {
201 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
202 if utils::semicolon_for_expr(&self.get_context(), expr) {
208 let mut remove_len = BytePos(0);
209 if self.config.remove_blank_lines_at_start_or_end_of_block() {
210 if let Some(stmt) = b.stmts.last() {
211 let snippet = self.snippet(mk_sp(
213 source!(self, b.span).hi() - brace_compensation,
215 let len = CommentCodeSlices::new(snippet)
217 .and_then(|(kind, _, s)| {
218 if kind == CodeCharKind::Normal && s.trim().is_empty() {
224 if let Some(len) = len {
225 remove_len = BytePos::from_usize(len);
230 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
231 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
232 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
233 snippet.contains("//") || snippet.contains("/*")
235 // FIXME: we should compress any newlines here to just one
236 if unindent_comment {
237 self.block_indent = self.block_indent.block_unindent(self.config);
239 self.format_missing_with_indent(
240 source!(self, b.span).hi() - brace_compensation - remove_len,
242 if unindent_comment {
243 self.block_indent = self.block_indent.block_indent(self.config);
245 self.close_block(unindent_comment);
246 self.last_pos = source!(self, b.span).hi();
249 // FIXME: this is a terrible hack to indent the comments between the last
250 // item in the block and the closing brace to the block's level.
251 // The closing brace itself, however, should be indented at a shallower
253 fn close_block(&mut self, unindent_comment: bool) {
254 let total_len = self.buffer.len();
255 let chars_too_many = if unindent_comment {
257 } else if self.config.hard_tabs() {
260 self.config.tab_spaces()
262 self.buffer.truncate(total_len - chars_too_many);
264 self.block_indent = self.block_indent.block_unindent(self.config);
267 // Note that this only gets called for function definitions. Required methods
268 // on traits do not get handled here.
272 generics: &ast::Generics,
275 defaultness: ast::Defaultness,
276 inner_attrs: Option<&[ast::Attribute]>,
278 let indent = self.block_indent;
280 let rewrite = match fk {
281 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
286 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
287 mk_sp(s.lo(), b.span.lo()),
291 visit::FnKind::Closure(_) => unreachable!(),
294 if let Some(fn_str) = rewrite {
295 self.format_missing_with_indent(source!(self, s).lo());
296 self.push_str(&fn_str);
297 if let Some(c) = fn_str.chars().last() {
299 self.last_pos = source!(self, block.span).hi();
304 self.format_missing(source!(self, block.span).lo());
307 self.last_pos = source!(self, block.span).lo();
308 self.visit_block(block, inner_attrs, true)
311 pub fn visit_item(&mut self, item: &ast::Item) {
312 skip_out_of_file_lines_range_visitor!(self, item.span);
314 // This is where we bail out if there is a skip attribute. This is only
315 // complex in the module case. It is complex because the module could be
316 // in a separate file and there might be attributes in both files, but
317 // the AST lumps them all together.
319 let mut attrs = &item.attrs;
321 ast::ItemKind::Mod(ref m) => {
322 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
323 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
324 if outer_file.name == inner_file.name {
325 // Module is inline, in this case we treat modules like any
327 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
328 self.push_skipped_with_span(item.span());
331 } else if contains_skip(&item.attrs) {
332 // Module is not inline, but should be skipped.
335 // Module is not inline and should not be skipped. We want
336 // to process only the attributes in the current file.
337 filtered_attrs = item.attrs
340 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
341 if attr_file.name == outer_file.name {
347 .collect::<Vec<_>>();
348 // Assert because if we should skip it should be caught by
350 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
351 attrs = &filtered_attrs;
355 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
356 self.push_skipped_with_span(item.span());
363 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
364 ast::ItemKind::Impl(..) => {
365 let snippet = self.snippet(item.span);
366 let where_span_end = snippet
367 .find_uncommented("{")
368 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
369 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
370 self.push_rewrite(item.span, rw);
372 ast::ItemKind::Trait(..) => {
373 let rw = format_trait(&self.get_context(), item, self.block_indent);
374 self.push_rewrite(item.span, rw);
376 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
377 let shape = Shape::indented(self.block_indent, self.config);
378 let rw = format_trait_alias(
385 self.push_rewrite(item.span, rw);
387 ast::ItemKind::ExternCrate(_) => {
388 let rw = rewrite_extern_crate(&self.get_context(), item);
389 self.push_rewrite(item.span, rw);
391 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
392 self.visit_struct(&StructParts::from_item(item));
394 ast::ItemKind::Enum(ref def, ref generics) => {
395 self.format_missing_with_indent(source!(self, item.span).lo());
396 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
397 self.last_pos = source!(self, item.span).hi();
399 ast::ItemKind::Mod(ref module) => {
400 self.format_missing_with_indent(source!(self, item.span).lo());
401 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
403 ast::ItemKind::Mac(ref mac) => {
404 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
406 ast::ItemKind::ForeignMod(ref foreign_mod) => {
407 self.format_missing_with_indent(source!(self, item.span).lo());
408 self.format_foreign_mod(foreign_mod, item.span);
410 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
411 self.visit_static(&StaticParts::from_item(item));
413 ast::ItemKind::AutoImpl(..) => {
414 // FIXME(#78): format impl definitions.
416 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
418 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
422 ast::Defaultness::Final,
426 ast::ItemKind::Ty(ref ty, ref generics) => {
427 let rewrite = rewrite_type_alias(
436 self.push_rewrite(item.span, rewrite);
438 ast::ItemKind::GlobalAsm(..) => {
439 let snippet = Some(self.snippet(item.span).to_owned());
440 self.push_rewrite(item.span, snippet);
442 ast::ItemKind::MacroDef(..) => {
443 // FIXME(#1539): macros 2.0
444 let mac_snippet = Some(remove_trailing_white_spaces(self.snippet(item.span)));
445 self.push_rewrite(item.span, mac_snippet);
450 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
451 skip_out_of_file_lines_range_visitor!(self, ti.span);
453 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
454 self.push_skipped_with_span(ti.span());
459 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
460 ast::TraitItemKind::Method(ref sig, None) => {
461 let indent = self.block_indent;
463 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
464 self.push_rewrite(ti.span, rewrite);
466 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
468 visit::FnKind::Method(ti.ident, sig, None, body),
472 ast::Defaultness::Final,
476 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
477 let rewrite = rewrite_associated_type(
479 type_default.as_ref(),
480 Some(type_param_bounds),
484 self.push_rewrite(ti.span, rewrite);
486 ast::TraitItemKind::Macro(ref mac) => {
487 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
492 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
493 skip_out_of_file_lines_range_visitor!(self, ii.span);
495 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
496 self.push_skipped_with_span(ii.span());
501 ast::ImplItemKind::Method(ref sig, ref body) => {
503 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
511 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
512 ast::ImplItemKind::Type(ref ty) => {
513 let rewrite = rewrite_associated_impl_type(
521 self.push_rewrite(ii.span, rewrite);
523 ast::ImplItemKind::Macro(ref mac) => {
524 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
529 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
530 skip_out_of_file_lines_range_visitor!(self, mac.span);
533 let shape = self.shape().sub_width(1).unwrap();
534 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
535 self.push_rewrite(mac.span, rewrite);
538 pub fn push_str(&mut self, s: &str) {
539 self.line_number += count_newlines(s);
540 self.buffer.push_str(s);
543 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
544 if let Some(ref s) = rewrite {
547 let snippet = self.snippet(span);
548 self.push_str(snippet);
550 self.last_pos = source!(self, span).hi();
553 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
554 self.format_missing_with_indent(source!(self, span).lo());
555 self.push_rewrite_inner(span, rewrite);
558 pub fn push_skipped_with_span(&mut self, span: Span) {
559 self.format_missing_with_indent(source!(self, span).lo());
560 let lo = self.line_number + 1;
561 self.push_rewrite_inner(span, None);
562 let hi = self.line_number + 1;
563 self.skipped_range.push((lo, hi));
566 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
567 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
571 parse_session: &'a ParseSess,
573 snippet_provider: &'a SnippetProvider,
574 ) -> FmtVisitor<'a> {
576 parse_session: parse_session,
577 codemap: parse_session.codemap(),
578 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
579 last_pos: BytePos(0),
580 block_indent: Indent::empty(),
582 is_if_else_block: false,
583 snippet_provider: snippet_provider,
585 skipped_range: vec![],
589 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
590 self.snippet_provider.span_to_snippet(span)
593 pub fn snippet(&'b self, span: Span) -> &'a str {
594 self.opt_snippet(span).unwrap()
597 // Returns true if we should skip the following item.
598 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
599 if contains_skip(attrs) {
603 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
604 if attrs.is_empty() {
608 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
609 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
610 self.push_rewrite(span, rewrite);
615 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
617 F: Fn(&ast::Item) -> bool,
619 let mut last = self.codemap.lookup_line_range(items_left[0].span());
620 let item_length = items_left
623 is_item(&***ppi) && (!in_group || {
624 let current = self.codemap.lookup_line_range(ppi.span());
625 let in_same_group = current.lo < last.hi + 2;
631 let items = &items_left[..item_length];
633 let at_least_one_in_file_lines = items
635 .any(|item| !out_of_file_lines_range!(self, item.span));
637 if at_least_one_in_file_lines {
638 self.format_imports(items);
641 self.push_rewrite(item.span, None);
648 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
649 while !items_left.is_empty() {
650 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
651 // to be potentially reordered within `format_imports`. Otherwise, just format the
652 // next item for output.
653 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
654 let used_items_len = self.reorder_items(
657 self.config.reorder_imports_in_group(),
659 let (_, rest) = items_left.split_at(used_items_len);
661 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
662 let used_items_len = self.reorder_items(
665 self.config.reorder_extern_crates_in_group(),
667 let (_, rest) = items_left.split_at(used_items_len);
670 // `unwrap()` is safe here because we know `items_left`
671 // has elements from the loop condition
672 let (item, rest) = items_left.split_first().unwrap();
673 self.visit_item(item);
679 fn walk_mod_items(&mut self, m: &ast::Mod) {
680 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
683 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
684 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
686 ast::StmtKind::Item(ref item) => Some(&**item),
691 if stmts.is_empty() {
695 // Extract leading `use ...;`.
696 let items: Vec<_> = stmts
698 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
699 .filter_map(|stmt| to_stmt_item(stmt))
702 if items.is_empty() {
703 self.visit_stmt(&stmts[0]);
704 self.walk_stmts(&stmts[1..]);
706 self.walk_items(&items);
707 self.walk_stmts(&stmts[items.len()..]);
711 fn walk_block_stmts(&mut self, b: &ast::Block) {
712 self.walk_stmts(&b.stmts)
718 vis: &ast::Visibility,
721 attrs: &[ast::Attribute],
723 // Decide whether this is an inline mod or an external mod.
724 let local_file_name = self.codemap.span_to_filename(s);
725 let inner_span = source!(self, m.inner);
726 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
727 && local_file_name == self.codemap.span_to_filename(inner_span);
729 self.push_str(&*utils::format_visibility(vis));
730 self.push_str("mod ");
731 self.push_str(&ident.to_string());
734 match self.config.brace_style() {
735 BraceStyle::AlwaysNextLine => {
736 let sep_str = format!("\n{}{{", self.block_indent.to_string(self.config));
737 self.push_str(&sep_str);
739 _ => self.push_str(" {"),
741 // Hackery to account for the closing }.
742 let mod_lo = self.codemap.span_after(source!(self, s), "{");
744 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
745 let body_snippet = body_snippet.trim();
746 if body_snippet.is_empty() {
749 self.last_pos = mod_lo;
750 self.block_indent = self.block_indent.block_indent(self.config);
751 self.visit_attrs(attrs, ast::AttrStyle::Inner);
752 self.walk_mod_items(m);
753 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
754 self.close_block(false);
756 self.last_pos = source!(self, m.inner).hi();
759 self.last_pos = source!(self, s).hi();
763 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
764 self.block_indent = Indent::empty();
765 self.walk_mod_items(m);
766 self.format_missing_with_indent(filemap.end_pos);
769 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
770 while let Some(pos) = self.codemap
771 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
773 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
774 if snippet.trim().is_empty() {
783 pub fn get_context(&self) -> RewriteContext {
785 parse_session: self.parse_session,
786 codemap: self.codemap,
790 is_if_else_block: false,
791 force_one_line_chain: false,
792 snippet_provider: self.snippet_provider,
797 impl Rewrite for ast::NestedMetaItem {
798 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
800 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
801 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
806 impl Rewrite for ast::MetaItem {
807 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
808 Some(match self.node {
809 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
810 ast::MetaItemKind::List(ref list) => {
811 let name = self.name.as_str();
812 // 1 = `(`, 2 = `]` and `)`
813 let item_shape = shape
815 .shrink_left(name.len() + 1)
816 .and_then(|s| s.sub_width(2))?;
817 let items = itemize_list(
822 |nested_meta_item| nested_meta_item.span.lo(),
823 |nested_meta_item| nested_meta_item.span.hi(),
824 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
829 let item_vec = items.collect::<Vec<_>>();
830 let fmt = ListFormatting {
831 tactic: DefinitiveListTactic::Mixed,
833 trailing_separator: SeparatorTactic::Never,
834 separator_place: SeparatorPlace::Back,
836 ends_with_newline: false,
837 preserve_newline: false,
838 config: context.config,
840 format!("{}({})", name, write_list(&item_vec, &fmt)?)
842 ast::MetaItemKind::NameValue(ref literal) => {
843 let name = self.name.as_str();
845 let lit_shape = shape.shrink_left(name.len() + 3)?;
846 let value = rewrite_literal(context, literal, lit_shape)?;
847 format!("{} = {}", name, value)
853 impl Rewrite for ast::Attribute {
854 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
855 let prefix = match self.style {
856 ast::AttrStyle::Inner => "#!",
857 ast::AttrStyle::Outer => "#",
859 let snippet = context.snippet(self.span);
860 if self.is_sugared_doc {
861 let doc_shape = Shape {
862 width: cmp::min(shape.width, context.config.comment_width())
863 .checked_sub(shape.indent.width())
867 rewrite_comment(snippet, false, doc_shape, context.config)
869 if contains_comment(snippet) {
870 return Some(snippet.to_owned());
873 let shape = shape.offset_left(prefix.len() + 1)?;
875 .rewrite(context, shape)
876 .map(|rw| format!("{}[{}]", prefix, rw))
881 /// Returns the first group of attributes that fills the given predicate.
882 /// We consider two doc comments are in different group if they are separated by normal comments.
883 fn take_while_with_pred<'a, P>(
884 context: &RewriteContext,
885 attrs: &'a [ast::Attribute],
887 ) -> &'a [ast::Attribute]
889 P: Fn(&ast::Attribute) -> bool,
891 let mut last_index = 0;
892 let mut iter = attrs.iter().enumerate().peekable();
893 while let Some((i, attr)) = iter.next() {
897 if let Some(&(_, next_attr)) = iter.peek() {
898 // Extract comments between two attributes.
899 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
900 let snippet = context.snippet(span_between_attr);
901 if count_newlines(snippet) >= 2 || snippet.contains('/') {
910 &attrs[..last_index + 1]
914 fn rewrite_first_group_attrs(
915 context: &RewriteContext,
916 attrs: &[ast::Attribute],
918 ) -> Option<(usize, String)> {
919 if attrs.is_empty() {
920 return Some((0, String::new()));
922 // Rewrite doc comments
923 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
924 if !sugared_docs.is_empty() {
925 let snippet = sugared_docs
927 .map(|a| context.snippet(a.span))
932 rewrite_comment(&snippet, false, shape, context.config)?,
935 // Rewrite `#[derive(..)]`s.
936 if context.config.merge_derives() {
937 let derives = take_while_with_pred(context, attrs, is_derive);
938 if !derives.is_empty() {
939 let mut derive_args = vec![];
940 for derive in derives {
941 derive_args.append(&mut get_derive_args(context, derive)?);
943 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
946 // Rewrite the first attribute.
947 Some((1, attrs[0].rewrite(context, shape)?))
950 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
951 // Look at before and after comment and see if there are any empty lines.
952 let comment_begin = comment.chars().position(|c| c == '/');
953 let len = comment_begin.unwrap_or_else(|| comment.len());
954 let mlb = count_newlines(&comment[..len]) > 1;
955 let mla = if comment_begin.is_none() {
958 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
959 let len = comment_end.unwrap();
964 .filter(|c| *c == '\n')
967 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
970 impl<'a> Rewrite for [ast::Attribute] {
971 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
973 return Some(String::new());
975 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
976 if self.len() == 1 || first_group_len == self.len() {
977 Some(first_group_str)
979 let rest_str = self[first_group_len..].rewrite(context, shape)?;
980 let missing_span = mk_sp(
981 self[first_group_len - 1].span.hi(),
982 self[first_group_len].span.lo(),
984 // Preserve an empty line before/after doc comments.
985 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
986 let snippet = context.snippet(missing_span);
987 let (mla, mlb) = has_newlines_before_after_comment(snippet);
988 let comment = ::comment::recover_missing_comment_in_span(
990 shape.with_max_width(context.config),
994 let comment = if comment.is_empty() {
997 format!("{}{}\n{}", mla, comment, mlb)
1003 shape.indent.to_string(context.config),
1007 combine_strs_with_missing_comments(
1020 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
1021 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
1022 let mut result = String::with_capacity(128);
1023 result.push_str("#[derive(");
1024 // 11 = `#[derive()]`
1025 let initial_budget = shape.width.checked_sub(11)?;
1026 let mut budget = initial_budget;
1027 let num = derive_args.len();
1028 for (i, a) in derive_args.iter().enumerate() {
1030 let width = a.len() + 2;
1033 // Remove trailing whitespace.
1038 result.push_str(&(shape.indent + 9).to_string(context.config));
1039 budget = initial_budget;
1041 budget = budget.checked_sub(width).unwrap_or(0);
1045 result.push_str(", ")
1048 result.push_str(")]");
1052 fn is_derive(attr: &ast::Attribute) -> bool {
1054 Some(meta_item) => match meta_item.node {
1055 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1062 /// Returns the arguments of `#[derive(...)]`.
1063 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
1064 attr.meta().and_then(|meta_item| match meta_item.node {
1065 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1066 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1069 .map(|a| context.snippet(a.span))
1070 .collect::<Vec<_>>(),
1077 // Rewrite `extern crate foo;` WITHOUT attributes.
1078 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1079 assert!(is_extern_crate(item));
1080 let new_str = context.snippet(item.span);
1081 Some(if contains_comment(new_str) {
1084 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1085 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1089 fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
1091 ast::StmtKind::Local(ref local) => &local.attrs,
1092 ast::StmtKind::Item(ref item) => &item.attrs,
1093 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
1094 ast::StmtKind::Mac(ref mac) => &mac.2,