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 strings::string_buffer::StringBuffer;
15 use syntax::{ast, visit};
16 use syntax::attr::HasAttrs;
17 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
18 use syntax::parse::ParseSess;
20 use expr::rewrite_literal;
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, remove_trailing_white_spaces,
24 CodeCharKind, CommentCodeSlices, FindUncommented};
25 use comment::rewrite_comment;
26 use config::{BraceStyle, Config};
27 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
28 rewrite_type_alias, FnSig, StaticParts, StructParts};
29 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
31 use macros::{rewrite_macro, MacroPosition};
33 use rewrite::{Rewrite, RewriteContext};
34 use shape::{Indent, Shape};
35 use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
37 fn is_use_item(item: &ast::Item) -> bool {
39 ast::ItemKind::Use(_) => true,
44 fn is_extern_crate(item: &ast::Item) -> bool {
46 ast::ItemKind::ExternCrate(..) => true,
51 /// Creates a string slice corresponding to the specified span.
52 pub struct SnippetProvider<'a> {
53 /// A pointer to the content of the file we are formatting.
54 big_snippet: &'a Rc<String>,
55 /// A position of the start of `big_snippet`, used as an offset.
59 impl<'b, 'a: 'b> SnippetProvider<'a> {
60 pub fn span_to_snippet(&'b self, span: Span) -> Option<&'a str> {
61 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
62 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
63 Some(&self.big_snippet[start_index..end_index])
66 pub fn new(start_pos: BytePos, big_snippet: &'a Rc<String>) -> Self {
67 let start_pos = start_pos.to_usize();
75 pub struct FmtVisitor<'a> {
76 pub parse_session: &'a ParseSess,
77 pub codemap: &'a CodeMap,
78 pub buffer: StringBuffer,
79 pub last_pos: BytePos,
80 // FIXME: use an RAII util or closure for indenting
81 pub block_indent: Indent,
82 pub config: &'a Config,
83 pub is_if_else_block: bool,
84 pub snippet_provider: &'a SnippetProvider<'a>,
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 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
105 self.push_rewrite(stmt.span(), rewrite)
107 ast::StmtKind::Mac(ref mac) => {
108 let (ref mac, _macro_style, ref attrs) = **mac;
109 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
110 self.push_rewrite(stmt.span(), None);
112 self.visit_mac(mac, None, MacroPosition::Statement);
114 self.format_missing(stmt.span.hi());
122 inner_attrs: Option<&[ast::Attribute]>,
126 "visit_block: {:?} {:?}",
127 self.codemap.lookup_char_pos(b.span.lo()),
128 self.codemap.lookup_char_pos(b.span.hi())
131 // Check if this block has braces.
132 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
134 self.last_pos = self.last_pos + brace_compensation;
135 self.block_indent = self.block_indent.block_indent(self.config);
136 self.buffer.push_str("{");
138 if self.config.remove_blank_lines_at_start_or_end_of_block() {
139 if let Some(first_stmt) = b.stmts.first() {
140 let attr_lo = inner_attrs
141 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
143 // Attributes for an item in a statement position
144 // do not belong to the statement. (rust-lang/rust#34459)
145 if let ast::StmtKind::Item(ref item) = first_stmt.node {
148 first_stmt.attrs().first()
150 // Some stmts can have embedded attributes.
151 // e.g. `match { #![attr] ... }`
152 let attr_lo = attr.span.lo();
153 if attr_lo < first_stmt.span.lo() {
161 let snippet = self.snippet(mk_sp(
163 attr_lo.unwrap_or(first_stmt.span.lo()),
165 let len = CommentCodeSlices::new(&snippet)
167 .and_then(|(kind, _, s)| {
168 if kind == CodeCharKind::Normal {
174 if let Some(len) = len {
175 self.last_pos = self.last_pos + BytePos::from_usize(len);
180 // Format inner attributes if available.
181 let skip_rewrite = if let Some(attrs) = inner_attrs {
182 self.visit_attrs(attrs, ast::AttrStyle::Inner)
188 self.push_rewrite(b.span, None);
189 self.close_block(false);
190 self.last_pos = source!(self, b.span).hi();
194 self.walk_block_stmts(b);
196 if !b.stmts.is_empty() {
197 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
198 if utils::semicolon_for_expr(&self.get_context(), expr) {
199 self.buffer.push_str(";");
204 let mut remove_len = BytePos(0);
205 if self.config.remove_blank_lines_at_start_or_end_of_block() {
206 if let Some(stmt) = b.stmts.last() {
207 let snippet = self.snippet(mk_sp(
209 source!(self, b.span).hi() - brace_compensation,
211 let len = CommentCodeSlices::new(&snippet)
213 .and_then(|(kind, _, s)| {
214 if kind == CodeCharKind::Normal && s.trim().is_empty() {
220 if let Some(len) = len {
221 remove_len = BytePos::from_usize(len);
226 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
227 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
228 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
229 snippet.contains("//") || snippet.contains("/*")
231 // FIXME: we should compress any newlines here to just one
232 if unindent_comment {
233 self.block_indent = self.block_indent.block_unindent(self.config);
235 self.format_missing_with_indent(
236 source!(self, b.span).hi() - brace_compensation - remove_len,
238 if unindent_comment {
239 self.block_indent = self.block_indent.block_indent(self.config);
241 self.close_block(unindent_comment);
242 self.last_pos = source!(self, b.span).hi();
245 // FIXME: this is a terrible hack to indent the comments between the last
246 // item in the block and the closing brace to the block's level.
247 // The closing brace itself, however, should be indented at a shallower
249 fn close_block(&mut self, unindent_comment: bool) {
250 let total_len = self.buffer.len;
251 let chars_too_many = if unindent_comment {
253 } else if self.config.hard_tabs() {
256 self.config.tab_spaces()
258 self.buffer.truncate(total_len - chars_too_many);
259 self.buffer.push_str("}");
260 self.block_indent = self.block_indent.block_unindent(self.config);
263 // Note that this only gets called for function definitions. Required methods
264 // on traits do not get handled here.
268 generics: &ast::Generics,
271 defaultness: ast::Defaultness,
272 inner_attrs: Option<&[ast::Attribute]>,
274 let indent = self.block_indent;
276 let rewrite = match fk {
277 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
282 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
283 mk_sp(s.lo(), b.span.lo()),
287 visit::FnKind::Closure(_) => unreachable!(),
290 if let Some(fn_str) = rewrite {
291 self.format_missing_with_indent(source!(self, s).lo());
292 self.buffer.push_str(&fn_str);
293 if let Some(c) = fn_str.chars().last() {
295 self.last_pos = source!(self, block.span).hi();
300 self.format_missing(source!(self, block.span).lo());
303 self.last_pos = source!(self, block.span).lo();
304 self.visit_block(block, inner_attrs, true)
307 pub fn visit_item(&mut self, item: &ast::Item) {
308 skip_out_of_file_lines_range_visitor!(self, item.span);
310 // This is where we bail out if there is a skip attribute. This is only
311 // complex in the module case. It is complex because the module could be
312 // in a separate file and there might be attributes in both files, but
313 // the AST lumps them all together.
315 let mut attrs = &item.attrs;
317 ast::ItemKind::Mod(ref m) => {
318 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
319 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
320 if outer_file.name == inner_file.name {
321 // Module is inline, in this case we treat modules like any
323 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
324 self.push_rewrite(item.span, None);
327 } else if contains_skip(&item.attrs) {
328 // Module is not inline, but should be skipped.
331 // Module is not inline and should not be skipped. We want
332 // to process only the attributes in the current file.
333 filtered_attrs = item.attrs
336 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
337 if attr_file.name == outer_file.name {
343 .collect::<Vec<_>>();
344 // Assert because if we should skip it should be caught by
346 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
347 attrs = &filtered_attrs;
351 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
352 self.push_rewrite(item.span, None);
359 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
360 ast::ItemKind::Impl(..) => {
361 let snippet = self.snippet(item.span);
362 let where_span_end = snippet
363 .find_uncommented("{")
364 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
365 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
366 self.push_rewrite(item.span, rw);
368 ast::ItemKind::Trait(..) => {
369 let rw = format_trait(&self.get_context(), item, self.block_indent);
370 self.push_rewrite(item.span, rw);
372 ast::ItemKind::ExternCrate(_) => {
373 let rw = rewrite_extern_crate(&self.get_context(), item);
374 self.push_rewrite(item.span, rw);
376 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
377 self.visit_struct(&StructParts::from_item(item));
379 ast::ItemKind::Enum(ref def, ref generics) => {
380 self.format_missing_with_indent(source!(self, item.span).lo());
381 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
382 self.last_pos = source!(self, item.span).hi();
384 ast::ItemKind::Mod(ref module) => {
385 self.format_missing_with_indent(source!(self, item.span).lo());
386 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
388 ast::ItemKind::Mac(ref mac) => {
389 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
391 ast::ItemKind::ForeignMod(ref foreign_mod) => {
392 self.format_missing_with_indent(source!(self, item.span).lo());
393 self.format_foreign_mod(foreign_mod, item.span);
395 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
396 self.visit_static(&StaticParts::from_item(item));
398 ast::ItemKind::AutoImpl(..) => {
399 // FIXME(#78): format impl definitions.
401 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
403 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
407 ast::Defaultness::Final,
411 ast::ItemKind::Ty(ref ty, ref generics) => {
412 let rewrite = rewrite_type_alias(
421 self.push_rewrite(item.span, rewrite);
423 ast::ItemKind::GlobalAsm(..) => {
424 let snippet = Some(self.snippet(item.span).into());
425 self.push_rewrite(item.span, snippet);
427 ast::ItemKind::MacroDef(..) => {
428 // FIXME(#1539): macros 2.0
429 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
430 self.push_rewrite(item.span, mac_snippet);
435 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
436 skip_out_of_file_lines_range_visitor!(self, ti.span);
438 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
439 self.push_rewrite(ti.span, None);
444 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
445 ast::TraitItemKind::Method(ref sig, None) => {
446 let indent = self.block_indent;
448 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
449 self.push_rewrite(ti.span, rewrite);
451 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
453 visit::FnKind::Method(ti.ident, sig, None, body),
457 ast::Defaultness::Final,
461 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
462 let rewrite = rewrite_associated_type(
464 type_default.as_ref(),
465 Some(type_param_bounds),
469 self.push_rewrite(ti.span, rewrite);
471 ast::TraitItemKind::Macro(ref mac) => {
472 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
477 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
478 skip_out_of_file_lines_range_visitor!(self, ii.span);
480 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
481 self.push_rewrite(ii.span, None);
486 ast::ImplItemKind::Method(ref sig, ref body) => {
488 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
496 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
497 ast::ImplItemKind::Type(ref ty) => {
498 let rewrite = rewrite_associated_impl_type(
506 self.push_rewrite(ii.span, rewrite);
508 ast::ImplItemKind::Macro(ref mac) => {
509 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
514 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
515 skip_out_of_file_lines_range_visitor!(self, mac.span);
518 let shape = self.shape().sub_width(1).unwrap();
519 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
520 self.push_rewrite(mac.span, rewrite);
523 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
524 self.format_missing_with_indent(source!(self, span).lo());
525 if let Some(ref s) = rewrite {
526 self.buffer.push_str(s);
528 let snippet = self.snippet(span);
529 self.buffer.push_str(snippet);
531 self.last_pos = source!(self, span).hi();
534 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
535 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
539 parse_session: &'a ParseSess,
541 snippet_provider: &'a SnippetProvider,
542 ) -> FmtVisitor<'a> {
544 parse_session: parse_session,
545 codemap: parse_session.codemap(),
546 buffer: StringBuffer::new(),
547 last_pos: BytePos(0),
548 block_indent: Indent::empty(),
550 is_if_else_block: false,
551 snippet_provider: snippet_provider,
555 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
556 self.snippet_provider.span_to_snippet(span)
559 pub fn snippet(&'b self, span: Span) -> &'a str {
560 self.opt_snippet(span).unwrap()
563 // Returns true if we should skip the following item.
564 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
565 if contains_skip(attrs) {
569 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
570 if attrs.is_empty() {
574 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
575 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
576 self.push_rewrite(span, rewrite);
581 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
583 F: Fn(&ast::Item) -> bool,
585 let mut last = self.codemap.lookup_line_range(items_left[0].span());
586 let item_length = items_left
589 is_item(&***ppi) && (!in_group || {
590 let current = self.codemap.lookup_line_range(ppi.span());
591 let in_same_group = current.lo < last.hi + 2;
597 let items = &items_left[..item_length];
599 let at_least_one_in_file_lines = items
601 .any(|item| !out_of_file_lines_range!(self, item.span));
603 if at_least_one_in_file_lines {
604 self.format_imports(items);
607 self.push_rewrite(item.span, None);
614 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
615 while !items_left.is_empty() {
616 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
617 // to be potentially reordered within `format_imports`. Otherwise, just format the
618 // next item for output.
619 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
620 let used_items_len = self.reorder_items(
623 self.config.reorder_imports_in_group(),
625 let (_, rest) = items_left.split_at(used_items_len);
627 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
628 let used_items_len = self.reorder_items(
631 self.config.reorder_extern_crates_in_group(),
633 let (_, rest) = items_left.split_at(used_items_len);
636 // `unwrap()` is safe here because we know `items_left`
637 // has elements from the loop condition
638 let (item, rest) = items_left.split_first().unwrap();
639 self.visit_item(item);
645 fn walk_mod_items(&mut self, m: &ast::Mod) {
646 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
649 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
650 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
652 ast::StmtKind::Item(ref item) => Some(&**item),
657 if stmts.is_empty() {
661 // Extract leading `use ...;`.
662 let items: Vec<_> = stmts
664 .take_while(|stmt| to_stmt_item(stmt).is_some())
665 .filter_map(|stmt| to_stmt_item(stmt))
666 .take_while(|item| is_use_item(item))
669 if items.is_empty() {
670 self.visit_stmt(&stmts[0]);
671 self.walk_stmts(&stmts[1..]);
673 self.walk_items(&items);
674 self.walk_stmts(&stmts[items.len()..]);
678 fn walk_block_stmts(&mut self, b: &ast::Block) {
679 self.walk_stmts(&b.stmts)
685 vis: &ast::Visibility,
688 attrs: &[ast::Attribute],
690 // Decide whether this is an inline mod or an external mod.
691 let local_file_name = self.codemap.span_to_filename(s);
692 let inner_span = source!(self, m.inner);
693 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
694 && local_file_name == self.codemap.span_to_filename(inner_span);
696 self.buffer.push_str(&*utils::format_visibility(vis));
697 self.buffer.push_str("mod ");
698 self.buffer.push_str(&ident.to_string());
701 match self.config.brace_style() {
702 BraceStyle::AlwaysNextLine => self.buffer
703 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
704 _ => self.buffer.push_str(" {"),
706 // Hackery to account for the closing }.
707 let mod_lo = self.codemap.span_after(source!(self, s), "{");
709 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
710 let body_snippet = body_snippet.trim();
711 if body_snippet.is_empty() {
712 self.buffer.push_str("}");
714 self.last_pos = mod_lo;
715 self.block_indent = self.block_indent.block_indent(self.config);
716 self.visit_attrs(attrs, ast::AttrStyle::Inner);
717 self.walk_mod_items(m);
718 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
719 self.close_block(false);
721 self.last_pos = source!(self, m.inner).hi();
723 self.buffer.push_str(";");
724 self.last_pos = source!(self, s).hi();
728 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
729 self.block_indent = Indent::empty();
730 self.walk_mod_items(m);
731 self.format_missing_with_indent(filemap.end_pos);
734 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
735 while let Some(pos) = self.codemap
736 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
738 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
739 if snippet.trim().is_empty() {
748 pub fn get_context(&self) -> RewriteContext {
750 parse_session: self.parse_session,
751 codemap: self.codemap,
755 is_if_else_block: false,
756 force_one_line_chain: false,
757 snippet_provider: &self.snippet_provider,
762 impl Rewrite for ast::NestedMetaItem {
763 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
765 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
766 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
771 impl Rewrite for ast::MetaItem {
772 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
773 Some(match self.node {
774 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
775 ast::MetaItemKind::List(ref list) => {
776 let name = self.name.as_str();
777 // 1 = `(`, 2 = `]` and `)`
778 let item_shape = shape
780 .shrink_left(name.len() + 1)
781 .and_then(|s| s.sub_width(2))?;
782 let items = itemize_list(
787 |nested_meta_item| nested_meta_item.span.lo(),
788 |nested_meta_item| nested_meta_item.span.hi(),
789 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
794 let item_vec = items.collect::<Vec<_>>();
795 let fmt = ListFormatting {
796 tactic: DefinitiveListTactic::Mixed,
798 trailing_separator: SeparatorTactic::Never,
799 separator_place: SeparatorPlace::Back,
801 ends_with_newline: false,
802 preserve_newline: false,
803 config: context.config,
805 format!("{}({})", name, write_list(&item_vec, &fmt)?)
807 ast::MetaItemKind::NameValue(ref literal) => {
808 let name = self.name.as_str();
810 let lit_shape = shape.shrink_left(name.len() + 3)?;
811 let value = rewrite_literal(context, literal, lit_shape)?;
812 format!("{} = {}", name, value)
818 impl Rewrite for ast::Attribute {
819 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
820 let prefix = match self.style {
821 ast::AttrStyle::Inner => "#!",
822 ast::AttrStyle::Outer => "#",
824 let snippet = context.snippet(self.span);
825 if self.is_sugared_doc {
826 let doc_shape = Shape {
827 width: cmp::min(shape.width, context.config.comment_width())
828 .checked_sub(shape.indent.width())
832 rewrite_comment(snippet, false, doc_shape, context.config)
834 if contains_comment(snippet) {
835 return Some(snippet.into());
838 let shape = shape.offset_left(prefix.len() + 1)?;
840 .rewrite(context, shape)
841 .map(|rw| format!("{}[{}]", prefix, rw))
846 /// Returns the first group of attributes that fills the given predicate.
847 /// We consider two doc comments are in different group if they are separated by normal comments.
848 fn take_while_with_pred<'a, P>(
849 context: &RewriteContext,
850 attrs: &'a [ast::Attribute],
852 ) -> &'a [ast::Attribute]
854 P: Fn(&ast::Attribute) -> bool,
856 let mut last_index = 0;
857 let mut iter = attrs.iter().enumerate().peekable();
858 while let Some((i, attr)) = iter.next() {
862 if let Some(&(_, next_attr)) = iter.peek() {
863 // Extract comments between two attributes.
864 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
865 let snippet = context.snippet(span_between_attr);
866 if count_newlines(&snippet) >= 2 || snippet.contains('/') {
875 &attrs[..last_index + 1]
879 fn rewrite_first_group_attrs(
880 context: &RewriteContext,
881 attrs: &[ast::Attribute],
883 ) -> Option<(usize, String)> {
884 if attrs.is_empty() {
885 return Some((0, String::new()));
887 // Rewrite doc comments
888 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
889 if !sugared_docs.is_empty() {
890 let snippet = sugared_docs
892 .map(|a| context.snippet(a.span))
897 rewrite_comment(&snippet, false, shape, context.config)?,
900 // Rewrite `#[derive(..)]`s.
901 if context.config.merge_derives() {
902 let derives = take_while_with_pred(context, attrs, is_derive);
903 if !derives.is_empty() {
904 let mut derive_args = vec![];
905 for derive in derives {
906 derive_args.append(&mut get_derive_args(context, derive)?);
908 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
911 // Rewrite the first attribute.
912 Some((1, attrs[0].rewrite(context, shape)?))
915 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
916 // Look at before and after comment and see if there are any empty lines.
917 let comment_begin = comment.chars().position(|c| c == '/');
918 let len = comment_begin.unwrap_or_else(|| comment.len());
919 let mlb = count_newlines(&comment[..len]) > 1;
920 let mla = if comment_begin.is_none() {
923 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
924 let len = comment_end.unwrap();
929 .filter(|c| *c == '\n')
932 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
935 impl<'a> Rewrite for [ast::Attribute] {
936 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
938 return Some(String::new());
940 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
941 if self.len() == 1 || first_group_len == self.len() {
942 Some(first_group_str)
944 let rest_str = self[first_group_len..].rewrite(context, shape)?;
945 let missing_span = mk_sp(
946 self[first_group_len - 1].span.hi(),
947 self[first_group_len].span.lo(),
949 // Preserve an empty line before/after doc comments.
950 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
951 let snippet = context.snippet(missing_span);
952 let (mla, mlb) = has_newlines_before_after_comment(&snippet);
953 let comment = ::comment::recover_missing_comment_in_span(
955 shape.with_max_width(context.config),
959 let comment = if comment.is_empty() {
962 format!("{}{}\n{}", mla, comment, mlb)
968 shape.indent.to_string(context.config),
972 combine_strs_with_missing_comments(
985 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
986 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
987 let mut result = String::with_capacity(128);
988 result.push_str("#[derive(");
989 // 11 = `#[derive()]`
990 let initial_budget = shape.width.checked_sub(11)?;
991 let mut budget = initial_budget;
992 let num = derive_args.len();
993 for (i, a) in derive_args.iter().enumerate() {
995 let width = a.len() + 2;
998 // Remove trailing whitespace.
1003 result.push_str(&(shape.indent + 9).to_string(context.config));
1004 budget = initial_budget;
1006 budget = budget.checked_sub(width).unwrap_or(0);
1010 result.push_str(", ")
1013 result.push_str(")]");
1017 fn is_derive(attr: &ast::Attribute) -> bool {
1019 Some(meta_item) => match meta_item.node {
1020 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1027 /// Returns the arguments of `#[derive(...)]`.
1028 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
1029 attr.meta().and_then(|meta_item| match meta_item.node {
1030 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1031 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1034 .map(|a| context.snippet(a.span))
1035 .collect::<Vec<_>>(),
1042 // Rewrite `extern crate foo;` WITHOUT attributes.
1043 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1044 assert!(is_extern_crate(item));
1045 let new_str = context.snippet(item.span);
1046 Some(if contains_comment(&new_str) {
1049 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1050 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))