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 strings::string_buffer::StringBuffer;
14 use syntax::{ast, visit};
15 use syntax::attr::HasAttrs;
16 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
17 use syntax::parse::ParseSess;
19 use expr::rewrite_literal;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, recover_missing_comment_in_span, remove_trailing_white_spaces,
23 CodeCharKind, CommentCodeSlices, FindUncommented};
24 use comment::rewrite_comment;
25 use config::{BraceStyle, Config};
26 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
27 rewrite_type_alias, FnSig, StaticParts, StructParts};
28 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
30 use macros::{rewrite_macro, MacroPosition};
32 use rewrite::{Rewrite, RewriteContext};
33 use shape::{Indent, Shape};
34 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
36 fn is_use_item(item: &ast::Item) -> bool {
38 ast::ItemKind::Use(_) => true,
43 fn is_extern_crate(item: &ast::Item) -> bool {
45 ast::ItemKind::ExternCrate(..) => true,
50 pub struct FmtVisitor<'a> {
51 pub parse_session: &'a ParseSess,
52 pub codemap: &'a CodeMap,
53 pub buffer: StringBuffer,
54 pub last_pos: BytePos,
55 // FIXME: use an RAII util or closure for indenting
56 pub block_indent: Indent,
57 pub config: &'a Config,
58 pub is_if_else_block: bool,
61 impl<'a> FmtVisitor<'a> {
62 pub fn shape(&self) -> Shape {
63 Shape::indented(self.block_indent, self.config)
66 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
68 "visit_stmt: {:?} {:?}",
69 self.codemap.lookup_char_pos(stmt.span.lo()),
70 self.codemap.lookup_char_pos(stmt.span.hi())
74 ast::StmtKind::Item(ref item) => {
75 self.visit_item(item);
77 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
78 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
79 self.push_rewrite(stmt.span(), rewrite)
81 ast::StmtKind::Mac(ref mac) => {
82 let (ref mac, _macro_style, ref attrs) = **mac;
83 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
84 self.push_rewrite(stmt.span(), None);
86 self.visit_mac(mac, None, MacroPosition::Statement);
88 self.format_missing(stmt.span.hi());
93 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
95 "visit_block: {:?} {:?}",
96 self.codemap.lookup_char_pos(b.span.lo()),
97 self.codemap.lookup_char_pos(b.span.hi())
100 // Check if this block has braces.
101 let snippet = self.snippet(b.span);
102 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
103 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
105 self.last_pos = self.last_pos + brace_compensation;
106 self.block_indent = self.block_indent.block_indent(self.config);
107 self.buffer.push_str("{");
109 if self.config.remove_blank_lines_at_start_or_end_of_block() {
110 if let Some(first_stmt) = b.stmts.first() {
111 let attr_lo = inner_attrs
113 inner_attributes(attrs).first().map(|attr| attr.span.lo())
116 // Attributes for an item in a statement position
117 // do not belong to the statement. (rust-lang/rust#34459)
118 if let ast::StmtKind::Item(ref item) = first_stmt.node {
121 first_stmt.attrs().first()
123 // Some stmts can have embedded attributes.
124 // e.g. `match { #![attr] ... }`
125 let attr_lo = attr.span.lo();
126 if attr_lo < first_stmt.span.lo() {
134 let snippet = self.snippet(mk_sp(
136 attr_lo.unwrap_or(first_stmt.span.lo()),
138 let len = CommentCodeSlices::new(&snippet)
140 .and_then(|(kind, _, s)| {
141 if kind == CodeCharKind::Normal {
147 if let Some(len) = len {
148 self.last_pos = self.last_pos + BytePos::from_usize(len);
153 // Format inner attributes if available.
154 let skip_rewrite = if let Some(attrs) = inner_attrs {
155 self.visit_attrs(attrs, ast::AttrStyle::Inner)
161 self.push_rewrite(b.span, None);
162 self.close_block(false);
163 self.last_pos = source!(self, b.span).hi();
167 self.walk_block_stmts(b);
169 if !b.stmts.is_empty() {
170 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
171 if utils::semicolon_for_expr(&self.get_context(), expr) {
172 self.buffer.push_str(";");
177 let mut remove_len = BytePos(0);
178 if self.config.remove_blank_lines_at_start_or_end_of_block() {
179 if let Some(stmt) = b.stmts.last() {
180 let snippet = self.snippet(mk_sp(
182 source!(self, b.span).hi() - brace_compensation,
184 let len = CommentCodeSlices::new(&snippet)
186 .and_then(|(kind, _, s)| {
187 if kind == CodeCharKind::Normal && s.trim().is_empty() {
193 if let Some(len) = len {
194 remove_len = BytePos::from_usize(len);
199 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
200 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
201 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
202 snippet.contains("//") || snippet.contains("/*")
204 // FIXME: we should compress any newlines here to just one
205 if unindent_comment {
206 self.block_indent = self.block_indent.block_unindent(self.config);
208 self.format_missing_with_indent(
209 source!(self, b.span).hi() - brace_compensation - remove_len,
211 if unindent_comment {
212 self.block_indent = self.block_indent.block_indent(self.config);
214 self.close_block(unindent_comment);
215 self.last_pos = source!(self, b.span).hi();
218 // FIXME: this is a terrible hack to indent the comments between the last
219 // item in the block and the closing brace to the block's level.
220 // The closing brace itself, however, should be indented at a shallower
222 fn close_block(&mut self, unindent_comment: bool) {
223 let total_len = self.buffer.len;
224 let chars_too_many = if unindent_comment {
226 } else if self.config.hard_tabs() {
229 self.config.tab_spaces()
231 self.buffer.truncate(total_len - chars_too_many);
232 self.buffer.push_str("}");
233 self.block_indent = self.block_indent.block_unindent(self.config);
236 // Note that this only gets called for function definitions. Required methods
237 // on traits do not get handled here.
241 generics: &ast::Generics,
244 defaultness: ast::Defaultness,
245 inner_attrs: Option<&[ast::Attribute]>,
247 let indent = self.block_indent;
249 let rewrite = match fk {
250 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
255 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
256 mk_sp(s.lo(), b.span.lo()),
260 visit::FnKind::Closure(_) => unreachable!(),
263 if let Some(fn_str) = rewrite {
264 self.format_missing_with_indent(source!(self, s).lo());
265 self.buffer.push_str(&fn_str);
266 if let Some(c) = fn_str.chars().last() {
268 self.last_pos = source!(self, block.span).hi();
273 self.format_missing(source!(self, block.span).lo());
276 self.last_pos = source!(self, block.span).lo();
277 self.visit_block(block, inner_attrs)
280 pub fn visit_item(&mut self, item: &ast::Item) {
281 skip_out_of_file_lines_range_visitor!(self, item.span);
283 // This is where we bail out if there is a skip attribute. This is only
284 // complex in the module case. It is complex because the module could be
285 // in a separate file and there might be attributes in both files, but
286 // the AST lumps them all together.
288 let mut attrs = &item.attrs;
290 ast::ItemKind::Mod(ref m) => {
291 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
292 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
293 if outer_file.name == inner_file.name {
294 // Module is inline, in this case we treat modules like any
296 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
297 self.push_rewrite(item.span, None);
300 } else if contains_skip(&item.attrs) {
301 // Module is not inline, but should be skipped.
304 // Module is not inline and should not be skipped. We want
305 // to process only the attributes in the current file.
306 filtered_attrs = item.attrs
309 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
310 if attr_file.name == outer_file.name {
316 .collect::<Vec<_>>();
317 // Assert because if we should skip it should be caught by
319 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
320 attrs = &filtered_attrs;
323 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
324 self.push_rewrite(item.span, None);
330 ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
331 ast::ItemKind::Impl(..) => {
332 let snippet = self.snippet(item.span);
333 let where_span_end = snippet
334 .find_uncommented("{")
335 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
336 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
337 self.push_rewrite(item.span, rw);
339 ast::ItemKind::Trait(..) => {
340 let rw = format_trait(&self.get_context(), item, self.block_indent);
341 self.push_rewrite(item.span, rw);
343 ast::ItemKind::ExternCrate(_) => {
344 let rw = rewrite_extern_crate(&self.get_context(), item);
345 self.push_rewrite(item.span, rw);
347 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
348 self.visit_struct(&StructParts::from_item(item));
350 ast::ItemKind::Enum(ref def, ref generics) => {
351 self.format_missing_with_indent(source!(self, item.span).lo());
352 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
353 self.last_pos = source!(self, item.span).hi();
355 ast::ItemKind::Mod(ref module) => {
356 self.format_missing_with_indent(source!(self, item.span).lo());
357 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
359 ast::ItemKind::Mac(ref mac) => {
360 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
362 ast::ItemKind::ForeignMod(ref foreign_mod) => {
363 self.format_missing_with_indent(source!(self, item.span).lo());
364 self.format_foreign_mod(foreign_mod, item.span);
366 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
367 self.visit_static(&StaticParts::from_item(item));
369 ast::ItemKind::AutoImpl(..) => {
370 // FIXME(#78): format impl definitions.
372 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
374 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
378 ast::Defaultness::Final,
382 ast::ItemKind::Ty(ref ty, ref generics) => {
383 let rewrite = rewrite_type_alias(
392 self.push_rewrite(item.span, rewrite);
394 ast::ItemKind::GlobalAsm(..) => {
395 let snippet = Some(self.snippet(item.span));
396 self.push_rewrite(item.span, snippet);
398 ast::ItemKind::MacroDef(..) => {
399 // FIXME(#1539): macros 2.0
400 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
401 self.push_rewrite(item.span, mac_snippet);
406 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
407 skip_out_of_file_lines_range_visitor!(self, ti.span);
409 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
410 self.push_rewrite(ti.span, None);
415 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
416 ast::TraitItemKind::Method(ref sig, None) => {
417 let indent = self.block_indent;
419 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
420 self.push_rewrite(ti.span, rewrite);
422 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
424 visit::FnKind::Method(ti.ident, sig, None, body),
428 ast::Defaultness::Final,
432 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
433 let rewrite = rewrite_associated_type(
435 type_default.as_ref(),
436 Some(type_param_bounds),
440 self.push_rewrite(ti.span, rewrite);
442 ast::TraitItemKind::Macro(ref mac) => {
443 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
448 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
449 skip_out_of_file_lines_range_visitor!(self, ii.span);
451 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
452 self.push_rewrite(ii.span, None);
457 ast::ImplItemKind::Method(ref sig, ref body) => {
459 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
467 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
468 ast::ImplItemKind::Type(ref ty) => {
469 let rewrite = rewrite_associated_impl_type(
477 self.push_rewrite(ii.span, rewrite);
479 ast::ImplItemKind::Macro(ref mac) => {
480 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
485 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
486 skip_out_of_file_lines_range_visitor!(self, mac.span);
489 let shape = self.shape().sub_width(1).unwrap();
490 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
491 self.push_rewrite(mac.span, rewrite);
494 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
495 self.format_missing_with_indent(source!(self, span).lo());
496 let result = rewrite.unwrap_or_else(|| self.snippet(span));
497 self.buffer.push_str(&result);
498 self.last_pos = source!(self, span).hi();
501 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
503 parse_session: parse_session,
504 codemap: parse_session.codemap(),
505 buffer: StringBuffer::new(),
506 last_pos: BytePos(0),
507 block_indent: Indent::empty(),
509 is_if_else_block: false,
513 pub fn snippet(&self, span: Span) -> String {
514 match self.codemap.span_to_snippet(span) {
518 "Couldn't make snippet for span {:?}->{:?}",
519 self.codemap.lookup_char_pos(span.lo()),
520 self.codemap.lookup_char_pos(span.hi())
527 // Returns true if we should skip the following item.
528 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
529 if contains_skip(attrs) {
533 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
534 if attrs.is_empty() {
538 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
539 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
540 self.push_rewrite(span, rewrite);
545 fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
547 F: Fn(&ast::Item) -> bool,
549 let mut last = self.codemap.lookup_line_range(items_left[0].span());
550 let item_length = items_left
553 is_item(&***ppi) && (!in_group || {
554 let current = self.codemap.lookup_line_range(ppi.span());
555 let in_same_group = current.lo < last.hi + 2;
561 let items = &items_left[..item_length];
563 let at_least_one_in_file_lines = items
565 .any(|item| !out_of_file_lines_range!(self, item.span));
567 if at_least_one_in_file_lines {
568 self.format_imports(items);
571 self.push_rewrite(item.span, None);
578 fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
579 while !items_left.is_empty() {
580 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
581 // to be potentially reordered within `format_imports`. Otherwise, just format the
582 // next item for output.
583 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
584 let used_items_len = self.reorder_items(
587 self.config.reorder_imports_in_group(),
589 let (_, rest) = items_left.split_at(used_items_len);
591 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
592 let used_items_len = self.reorder_items(
595 self.config.reorder_extern_crates_in_group(),
597 let (_, rest) = items_left.split_at(used_items_len);
600 // `unwrap()` is safe here because we know `items_left`
601 // has elements from the loop condition
602 let (item, rest) = items_left.split_first().unwrap();
603 self.visit_item(item);
609 fn walk_mod_items(&mut self, m: &ast::Mod) {
610 self.walk_items(&ptr_vec_to_ref_vec(&m.items));
613 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
614 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
616 ast::StmtKind::Item(ref item) => Some(&**item),
621 if stmts.is_empty() {
625 // Extract leading `use ...;`.
626 let items: Vec<_> = stmts
628 .take_while(|stmt| to_stmt_item(stmt).is_some())
629 .filter_map(|stmt| to_stmt_item(stmt))
630 .take_while(|item| is_use_item(item))
633 if items.is_empty() {
634 self.visit_stmt(&stmts[0]);
635 self.walk_stmts(&stmts[1..]);
637 self.walk_items(&items);
638 self.walk_stmts(&stmts[items.len()..]);
642 fn walk_block_stmts(&mut self, b: &ast::Block) {
643 self.walk_stmts(&b.stmts)
649 vis: &ast::Visibility,
652 attrs: &[ast::Attribute],
654 // Decide whether this is an inline mod or an external mod.
655 let local_file_name = self.codemap.span_to_filename(s);
656 let inner_span = source!(self, m.inner);
657 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
658 && local_file_name == self.codemap.span_to_filename(inner_span);
660 self.buffer.push_str(&*utils::format_visibility(vis));
661 self.buffer.push_str("mod ");
662 self.buffer.push_str(&ident.to_string());
665 match self.config.item_brace_style() {
666 BraceStyle::AlwaysNextLine => self.buffer
667 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
668 _ => self.buffer.push_str(" {"),
670 // Hackery to account for the closing }.
671 let mod_lo = self.codemap.span_after(source!(self, s), "{");
673 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
674 let body_snippet = body_snippet.trim();
675 if body_snippet.is_empty() {
676 self.buffer.push_str("}");
678 self.last_pos = mod_lo;
679 self.block_indent = self.block_indent.block_indent(self.config);
680 self.visit_attrs(attrs, ast::AttrStyle::Inner);
681 self.walk_mod_items(m);
682 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
683 self.close_block(false);
685 self.last_pos = source!(self, m.inner).hi();
687 self.buffer.push_str(";");
688 self.last_pos = source!(self, s).hi();
692 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
693 self.block_indent = Indent::empty();
694 self.walk_mod_items(m);
695 self.format_missing_with_indent(filemap.end_pos);
698 pub fn get_context(&self) -> RewriteContext {
700 parse_session: self.parse_session,
701 codemap: self.codemap,
705 is_if_else_block: false,
706 force_one_line_chain: false,
711 impl Rewrite for ast::NestedMetaItem {
712 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
714 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
715 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
720 impl Rewrite for ast::MetaItem {
721 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
722 Some(match self.node {
723 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
724 ast::MetaItemKind::List(ref list) => {
725 let name = self.name.as_str();
726 // 1 = `(`, 2 = `]` and `)`
727 let item_shape = shape
729 .shrink_left(name.len() + 1)
730 .and_then(|s| s.sub_width(2))?;
731 let items = itemize_list(
735 |nested_meta_item| nested_meta_item.span.lo(),
736 |nested_meta_item| nested_meta_item.span.hi(),
737 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
742 let item_vec = items.collect::<Vec<_>>();
743 let fmt = ListFormatting {
744 tactic: DefinitiveListTactic::Mixed,
746 trailing_separator: SeparatorTactic::Never,
747 separator_place: SeparatorPlace::Back,
749 ends_with_newline: false,
750 preserve_newline: false,
751 config: context.config,
753 format!("{}({})", name, write_list(&item_vec, &fmt)?)
755 ast::MetaItemKind::NameValue(ref literal) => {
756 let name = self.name.as_str();
758 let lit_shape = shape.shrink_left(name.len() + 3)?;
759 let value = rewrite_literal(context, literal, lit_shape)?;
760 format!("{} = {}", name, value)
766 impl Rewrite for ast::Attribute {
767 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
768 let prefix = match self.style {
769 ast::AttrStyle::Inner => "#!",
770 ast::AttrStyle::Outer => "#",
772 let snippet = context.snippet(self.span);
773 if self.is_sugared_doc {
774 let doc_shape = Shape {
775 width: cmp::min(shape.width, context.config.comment_width())
776 .checked_sub(shape.indent.width())
780 rewrite_comment(&snippet, false, doc_shape, context.config)
782 if contains_comment(&snippet) {
783 return Some(snippet);
786 let shape = shape.offset_left(prefix.len() + 1)?;
788 .rewrite(context, shape)
789 .map(|rw| format!("{}[{}]", prefix, rw))
794 impl<'a> Rewrite for [ast::Attribute] {
795 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
797 return Some(String::new());
799 let mut result = String::with_capacity(128);
800 let indent = shape.indent.to_string(context.config);
802 let mut derive_args = Vec::new();
804 let mut iter = self.iter().enumerate().peekable();
805 let mut insert_new_line = true;
806 let mut is_prev_sugared_doc = false;
807 while let Some((i, a)) = iter.next() {
808 let a_str = a.rewrite(context, shape)?;
810 // Write comments and blank lines between attributes.
812 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
813 // This particular horror show is to preserve line breaks in between doc
814 // comments. An alternative would be to force such line breaks to start
815 // with the usual doc comment token.
816 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
817 || is_prev_sugared_doc
819 // Look at before and after comment and see if there are any empty lines.
820 let comment_begin = comment.chars().position(|c| c == '/');
821 let len = comment_begin.unwrap_or_else(|| comment.len());
822 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
823 let mla = if comment_begin.is_none() {
826 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
827 let len = comment_end.unwrap();
832 .filter(|c| *c == '\n')
840 let comment = recover_missing_comment_in_span(
841 mk_sp(self[i - 1].span.hi(), a.span.lo()),
842 shape.with_max_width(context.config),
847 if !comment.is_empty() {
848 if multi_line_before {
851 result.push_str(&comment);
853 if multi_line_after {
856 } else if insert_new_line {
858 if multi_line_after {
863 if derive_args.is_empty() {
864 result.push_str(&indent);
867 insert_new_line = true;
870 // Write the attribute itself.
871 if context.config.merge_derives() {
872 // If the attribute is `#[derive(...)]`, take the arguments.
873 if let Some(mut args) = get_derive_args(context, a) {
874 derive_args.append(&mut args);
876 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
877 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
878 // If not, rewrite the merged derives.
880 result.push_str(&format_derive(context, &derive_args, shape)?);
885 result.push_str(&a_str);
888 result.push_str(&a_str);
891 is_prev_sugared_doc = a.is_sugared_doc;
897 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
898 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
899 let mut result = String::with_capacity(128);
900 result.push_str("#[derive(");
901 // 11 = `#[derive()]`
902 let initial_budget = shape.width.checked_sub(11)?;
903 let mut budget = initial_budget;
904 let num = derive_args.len();
905 for (i, a) in derive_args.iter().enumerate() {
907 let width = a.len() + 2;
910 // Remove trailing whitespace.
915 result.push_str(&(shape.indent + 9).to_string(context.config));
916 budget = initial_budget;
918 budget = budget.checked_sub(width).unwrap_or(0);
922 result.push_str(", ")
925 result.push_str(")]");
929 fn is_derive(attr: &ast::Attribute) -> bool {
931 Some(meta_item) => match meta_item.node {
932 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
939 /// Returns the arguments of `#[derive(...)]`.
940 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
941 attr.meta().and_then(|meta_item| match meta_item.node {
942 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
943 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
946 .map(|a| context.snippet(a.span))
947 .collect::<Vec<_>>(),
954 // Rewrite `extern crate foo;` WITHOUT attributes.
955 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
956 assert!(is_extern_crate(item));
957 let new_str = context.snippet(item.span);
958 Some(if contains_comment(&new_str) {
961 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
962 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))