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, ptr, visit};
15 use syntax::attr::HasAttrs;
16 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
17 use syntax::parse::ParseSess;
19 use {Indent, Shape, Spanned};
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{contains_comment, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices,
23 use comment::rewrite_comment;
24 use config::{BraceStyle, Config};
25 use items::{format_impl, format_struct, format_struct_struct, format_trait,
26 rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
28 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
30 use macros::{rewrite_macro, MacroPosition};
32 use rewrite::{Rewrite, RewriteContext};
33 use utils::{self, contains_skip, inner_attributes, mk_sp};
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 pub struct FmtVisitor<'a> {
50 pub parse_session: &'a ParseSess,
51 pub codemap: &'a CodeMap,
52 pub buffer: StringBuffer,
53 pub last_pos: BytePos,
54 // FIXME: use an RAII util or closure for indenting
55 pub block_indent: Indent,
56 pub config: &'a Config,
57 pub is_if_else_block: bool,
60 impl<'a> FmtVisitor<'a> {
61 pub fn shape(&self) -> Shape {
62 Shape::indented(self.block_indent, self.config)
65 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
67 "visit_stmt: {:?} {:?}",
68 self.codemap.lookup_char_pos(stmt.span.lo()),
69 self.codemap.lookup_char_pos(stmt.span.hi())
73 ast::StmtKind::Item(ref item) => {
74 self.visit_item(item);
76 ast::StmtKind::Local(..) => {
77 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
78 self.push_rewrite(stmt.span(), rewrite);
80 ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
81 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
82 self.push_rewrite(stmt.span(), rewrite)
84 ast::StmtKind::Mac(ref mac) => {
85 let (ref mac, _macro_style, ref attrs) = **mac;
86 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
87 self.push_rewrite(stmt.span(), None);
89 self.visit_mac(mac, None, MacroPosition::Statement);
91 self.format_missing(stmt.span.hi());
96 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
98 "visit_block: {:?} {:?}",
99 self.codemap.lookup_char_pos(b.span.lo()),
100 self.codemap.lookup_char_pos(b.span.hi())
103 // Check if this block has braces.
104 let snippet = self.snippet(b.span);
105 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
106 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
108 self.last_pos = self.last_pos + brace_compensation;
109 self.block_indent = self.block_indent.block_indent(self.config);
110 self.buffer.push_str("{");
112 if self.config.remove_blank_lines_at_start_or_end_of_block() {
113 if let Some(first_stmt) = b.stmts.first() {
114 let attr_lo = inner_attrs
116 inner_attributes(attrs).first().map(|attr| attr.span.lo())
119 // Attributes for an item in a statement position
120 // do not belong to the statement. (rust-lang/rust#34459)
121 if let ast::StmtKind::Item(ref item) = first_stmt.node {
124 first_stmt.attrs().first()
126 // Some stmts can have embedded attributes.
127 // e.g. `match { #![attr] ... }`
128 let attr_lo = attr.span.lo();
129 if attr_lo < first_stmt.span.lo() {
137 let snippet = self.snippet(mk_sp(
139 attr_lo.unwrap_or(first_stmt.span.lo()),
141 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
142 |(kind, _, s)| if kind == CodeCharKind::Normal {
148 if let Some(len) = len {
149 self.last_pos = self.last_pos + BytePos::from_usize(len);
154 // Format inner attributes if available.
155 if let Some(attrs) = inner_attrs {
156 self.visit_attrs(attrs, ast::AttrStyle::Inner);
159 for stmt in &b.stmts {
160 self.visit_stmt(stmt)
163 if !b.stmts.is_empty() {
164 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
165 if utils::semicolon_for_expr(&self.get_context(), expr) {
166 self.buffer.push_str(";");
171 let mut remove_len = BytePos(0);
172 if self.config.remove_blank_lines_at_start_or_end_of_block() {
173 if let Some(stmt) = b.stmts.last() {
174 let snippet = self.snippet(mk_sp(
176 source!(self, b.span).hi() - brace_compensation,
178 let len = CommentCodeSlices::new(&snippet)
180 .and_then(|(kind, _, s)| {
181 if kind == CodeCharKind::Normal && s.trim().is_empty() {
187 if let Some(len) = len {
188 remove_len = BytePos::from_usize(len);
193 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
194 if unindent_comment {
195 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
196 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
197 unindent_comment = snippet.contains("//") || snippet.contains("/*");
199 // FIXME: we should compress any newlines here to just one
200 if unindent_comment {
201 self.block_indent = self.block_indent.block_unindent(self.config);
203 self.format_missing_with_indent(
204 source!(self, b.span).hi() - brace_compensation - remove_len,
206 if unindent_comment {
207 self.block_indent = self.block_indent.block_indent(self.config);
209 self.close_block(unindent_comment);
210 self.last_pos = source!(self, b.span).hi();
213 // FIXME: this is a terrible hack to indent the comments between the last
214 // item in the block and the closing brace to the block's level.
215 // The closing brace itself, however, should be indented at a shallower
217 fn close_block(&mut self, unindent_comment: bool) {
218 let total_len = self.buffer.len;
219 let chars_too_many = if unindent_comment {
221 } else if self.config.hard_tabs() {
224 self.config.tab_spaces()
226 self.buffer.truncate(total_len - chars_too_many);
227 self.buffer.push_str("}");
228 self.block_indent = self.block_indent.block_unindent(self.config);
231 // Note that this only gets called for function definitions. Required methods
232 // on traits do not get handled here.
239 defaultness: ast::Defaultness,
240 inner_attrs: Option<&[ast::Attribute]>,
242 let indent = self.block_indent;
244 let rewrite = match fk {
245 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
257 mk_sp(s.lo(), b.span.lo()),
261 visit::FnKind::Method(ident, sig, vis, b) => {
272 vis.unwrap_or(&ast::Visibility::Inherited),
273 mk_sp(s.lo(), b.span.lo()),
277 visit::FnKind::Closure(_) => unreachable!(),
280 if let Some(fn_str) = rewrite {
281 self.format_missing_with_indent(source!(self, s).lo());
282 self.buffer.push_str(&fn_str);
283 if let Some(c) = fn_str.chars().last() {
285 self.last_pos = source!(self, block.span).hi();
290 self.format_missing(source!(self, block.span).lo());
293 self.last_pos = source!(self, block.span).lo();
294 self.visit_block(block, inner_attrs)
297 pub fn visit_item(&mut self, item: &ast::Item) {
298 skip_out_of_file_lines_range_visitor!(self, item.span);
300 // This is where we bail out if there is a skip attribute. This is only
301 // complex in the module case. It is complex because the module could be
302 // in a separate file and there might be attributes in both files, but
303 // the AST lumps them all together.
305 let mut attrs = &item.attrs;
307 ast::ItemKind::Mod(ref m) => {
308 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
309 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
310 if outer_file.name == inner_file.name {
311 // Module is inline, in this case we treat modules like any
313 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
314 self.push_rewrite(item.span, None);
317 } else if contains_skip(&item.attrs) {
318 // Module is not inline, but should be skipped.
321 // Module is not inline and should not be skipped. We want
322 // to process only the attributes in the current file.
323 filterd_attrs = item.attrs
326 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
327 if attr_file.name == outer_file.name {
333 .collect::<Vec<_>>();
334 // Assert because if we should skip it should be caught by
336 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
337 attrs = &filterd_attrs;
340 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
341 self.push_rewrite(item.span, None);
347 ast::ItemKind::Use(ref vp) => self.format_import(&item, vp),
348 ast::ItemKind::Impl(..) => {
349 let snippet = self.snippet(item.span);
350 let where_span_end = snippet
351 .find_uncommented("{")
352 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
353 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
354 self.push_rewrite(item.span, rw);
356 ast::ItemKind::Trait(..) => {
357 let rw = format_trait(&self.get_context(), item, self.block_indent);
358 self.push_rewrite(item.span, rw);
360 ast::ItemKind::ExternCrate(_) => {
361 let rw = rewrite_extern_crate(&self.get_context(), item);
362 self.push_rewrite(item.span, rw);
364 ast::ItemKind::Struct(ref def, ref generics) => {
365 let rewrite = format_struct(
375 ).map(|s| match *def {
376 ast::VariantData::Tuple(..) => s + ";",
379 self.push_rewrite(item.span, rewrite);
381 ast::ItemKind::Enum(ref def, ref generics) => {
382 self.format_missing_with_indent(source!(self, item.span).lo());
383 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
384 self.last_pos = source!(self, item.span).hi();
386 ast::ItemKind::Mod(ref module) => {
387 self.format_missing_with_indent(source!(self, item.span).lo());
388 self.format_mod(module, &item.vis, item.span, item.ident, &attrs);
390 ast::ItemKind::Mac(ref mac) => {
391 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
393 ast::ItemKind::ForeignMod(ref foreign_mod) => {
394 self.format_missing_with_indent(source!(self, item.span).lo());
395 self.format_foreign_mod(foreign_mod, item.span);
397 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
398 let rewrite = rewrite_static(
409 self.push_rewrite(item.span, rewrite);
411 ast::ItemKind::Const(ref ty, ref expr) => {
412 let rewrite = rewrite_static(
417 ast::Mutability::Immutable,
423 self.push_rewrite(item.span, rewrite);
425 ast::ItemKind::DefaultImpl(..) => {
426 // FIXME(#78): format impl definitions.
428 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
430 visit::FnKind::ItemFn(
442 ast::Defaultness::Final,
446 ast::ItemKind::Ty(ref ty, ref generics) => {
447 let rewrite = rewrite_type_alias(
456 self.push_rewrite(item.span, rewrite);
458 ast::ItemKind::Union(ref def, ref generics) => {
459 let rewrite = format_struct_struct(
470 self.push_rewrite(item.span, rewrite);
472 ast::ItemKind::GlobalAsm(..) => {
473 let snippet = Some(self.snippet(item.span));
474 self.push_rewrite(item.span, snippet);
476 ast::ItemKind::MacroDef(..) => {
477 // FIXME(#1539): macros 2.0
478 let mac_snippet = Some(self.snippet(item.span));
479 self.push_rewrite(item.span, mac_snippet);
484 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
485 skip_out_of_file_lines_range_visitor!(self, ti.span);
487 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
488 self.push_rewrite(ti.span, None);
493 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
494 let rewrite = rewrite_static(
496 &ast::Visibility::Inherited,
499 ast::Mutability::Immutable,
505 self.push_rewrite(ti.span, rewrite);
507 ast::TraitItemKind::Method(ref sig, None) => {
508 let indent = self.block_indent;
509 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
510 self.push_rewrite(ti.span, rewrite);
512 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
514 visit::FnKind::Method(ti.ident, sig, None, body),
518 ast::Defaultness::Final,
522 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
523 let rewrite = rewrite_associated_type(
525 type_default.as_ref(),
526 Some(type_param_bounds),
530 self.push_rewrite(ti.span, rewrite);
532 ast::TraitItemKind::Macro(ref mac) => {
533 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
538 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
539 skip_out_of_file_lines_range_visitor!(self, ii.span);
541 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
542 self.push_rewrite(ii.span, None);
547 ast::ImplItemKind::Method(ref sig, ref body) => {
549 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
557 ast::ImplItemKind::Const(ref ty, ref expr) => {
558 let rewrite = rewrite_static(
563 ast::Mutability::Immutable,
569 self.push_rewrite(ii.span, rewrite);
571 ast::ImplItemKind::Type(ref ty) => {
572 let rewrite = rewrite_associated_impl_type(
580 self.push_rewrite(ii.span, rewrite);
582 ast::ImplItemKind::Macro(ref mac) => {
583 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
588 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
589 skip_out_of_file_lines_range_visitor!(self, mac.span);
592 let shape = self.shape().sub_width(1).unwrap();
593 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
594 self.push_rewrite(mac.span, rewrite);
597 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
598 self.format_missing_with_indent(source!(self, span).lo());
599 let result = rewrite.unwrap_or_else(|| self.snippet(span));
600 self.buffer.push_str(&result);
601 self.last_pos = source!(self, span).hi();
604 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
606 parse_session: parse_session,
607 codemap: parse_session.codemap(),
608 buffer: StringBuffer::new(),
609 last_pos: BytePos(0),
610 block_indent: Indent::empty(),
612 is_if_else_block: false,
616 pub fn snippet(&self, span: Span) -> String {
617 match self.codemap.span_to_snippet(span) {
621 "Couldn't make snippet for span {:?}->{:?}",
622 self.codemap.lookup_char_pos(span.lo()),
623 self.codemap.lookup_char_pos(span.hi())
630 // Returns true if we should skip the following item.
631 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
632 if contains_skip(attrs) {
636 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
637 if attrs.is_empty() {
641 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
642 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
643 self.push_rewrite(span, rewrite);
650 items_left: &[ptr::P<ast::Item>],
655 F: Fn(&ast::Item) -> bool,
657 let mut last = self.codemap.lookup_line_range(items_left[0].span());
658 let item_length = items_left
661 is_item(&***ppi) && (!in_group || {
662 let current = self.codemap.lookup_line_range(ppi.span());
663 let in_same_group = current.lo < last.hi + 2;
669 let items = &items_left[..item_length];
671 let at_least_one_in_file_lines = items
673 .any(|item| !out_of_file_lines_range!(self, item.span));
675 if at_least_one_in_file_lines {
676 self.format_imports(items);
679 self.push_rewrite(item.span, None);
686 fn walk_mod_items(&mut self, m: &ast::Mod) {
687 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
688 while !items_left.is_empty() {
689 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
690 // to be potentially reordered within `format_imports`. Otherwise, just format the
691 // next item for output.
692 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
693 let used_items_len = self.reorder_items(
696 self.config.reorder_imports_in_group(),
698 let (_, rest) = items_left.split_at(used_items_len);
700 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
701 let used_items_len = self.reorder_items(
704 self.config.reorder_extern_crates_in_group(),
706 let (_, rest) = items_left.split_at(used_items_len);
709 // `unwrap()` is safe here because we know `items_left`
710 // has elements from the loop condition
711 let (item, rest) = items_left.split_first().unwrap();
712 self.visit_item(item);
721 vis: &ast::Visibility,
724 attrs: &[ast::Attribute],
726 // Decide whether this is an inline mod or an external mod.
727 let local_file_name = self.codemap.span_to_filename(s);
728 let inner_span = source!(self, m.inner);
729 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0) &&
730 local_file_name == self.codemap.span_to_filename(inner_span);
732 self.buffer.push_str(&*utils::format_visibility(vis));
733 self.buffer.push_str("mod ");
734 self.buffer.push_str(&ident.to_string());
737 match self.config.item_brace_style() {
738 BraceStyle::AlwaysNextLine => self.buffer
739 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
740 _ => self.buffer.push_str(" {"),
742 // Hackery to account for the closing }.
743 let mod_lo = self.codemap.span_after(source!(self, s), "{");
745 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
746 let body_snippet = body_snippet.trim();
747 if body_snippet.is_empty() {
748 self.buffer.push_str("}");
750 self.last_pos = mod_lo;
751 self.block_indent = self.block_indent.block_indent(self.config);
752 self.visit_attrs(attrs, ast::AttrStyle::Inner);
753 self.walk_mod_items(m);
754 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
755 self.close_block(false);
757 self.last_pos = source!(self, m.inner).hi();
759 self.buffer.push_str(";");
760 self.last_pos = source!(self, s).hi();
764 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
765 self.block_indent = Indent::empty();
766 self.walk_mod_items(m);
767 self.format_missing_with_indent(filemap.end_pos);
770 pub fn get_context(&self) -> RewriteContext {
772 parse_session: self.parse_session,
773 codemap: self.codemap,
777 is_if_else_block: false,
778 force_one_line_chain: false,
783 impl Rewrite for ast::NestedMetaItem {
784 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
786 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
787 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
792 impl Rewrite for ast::MetaItem {
793 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
794 Some(match self.node {
795 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
796 ast::MetaItemKind::List(ref list) => {
797 let name = self.name.as_str();
798 // 3 = `#[` and `(`, 2 = `]` and `)`
799 let item_shape = try_opt!(
801 .shrink_left(name.len() + 3)
802 .and_then(|s| s.sub_width(2))
804 let items = itemize_list(
808 |nested_meta_item| nested_meta_item.span.lo(),
809 |nested_meta_item| nested_meta_item.span.hi(),
810 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
815 let item_vec = items.collect::<Vec<_>>();
816 let fmt = ListFormatting {
817 tactic: DefinitiveListTactic::Mixed,
819 trailing_separator: SeparatorTactic::Never,
820 separator_place: SeparatorPlace::Back,
822 ends_with_newline: false,
823 preserve_newline: false,
824 config: context.config,
826 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
828 ast::MetaItemKind::NameValue(ref literal) => {
829 let name = self.name.as_str();
830 let value = context.snippet(literal.span);
831 if &*name == "doc" && contains_comment(&value) {
832 let doc_shape = Shape {
833 width: cmp::min(shape.width, context.config.comment_width())
834 .checked_sub(shape.indent.width())
838 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
840 format!("{} = {}", name, value)
847 impl Rewrite for ast::Attribute {
848 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
849 try_opt!(self.meta())
850 .rewrite(context, shape)
851 .map(|rw| if self.is_sugared_doc {
854 let original = context.snippet(self.span);
855 let prefix = match self.style {
856 ast::AttrStyle::Inner => "#!",
857 ast::AttrStyle::Outer => "#",
859 if contains_comment(&original) {
862 format!("{}[{}]", prefix, rw)
868 impl<'a> Rewrite for [ast::Attribute] {
869 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
871 return Some(String::new());
873 let mut result = String::with_capacity(128);
874 let indent = shape.indent.to_string(context.config);
876 let mut derive_args = Vec::new();
878 let mut iter = self.iter().enumerate().peekable();
879 let mut insert_new_line = true;
880 let mut is_prev_sugared_doc = false;
881 while let Some((i, a)) = iter.next() {
882 let a_str = try_opt!(a.rewrite(context, shape));
884 // Write comments and blank lines between attributes.
886 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
887 // This particular horror show is to preserve line breaks in between doc
888 // comments. An alternative would be to force such line breaks to start
889 // with the usual doc comment token.
890 let (multi_line_before, multi_line_after) = if a.is_sugared_doc ||
893 // Look at before and after comment and see if there are any empty lines.
894 let comment_begin = comment.chars().position(|c| c == '/');
895 let len = comment_begin.unwrap_or_else(|| comment.len());
896 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
897 let mla = if comment_begin.is_none() {
900 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
901 let len = comment_end.unwrap();
906 .filter(|c| *c == '\n')
914 let comment = try_opt!(recover_missing_comment_in_span(
915 mk_sp(self[i - 1].span.hi(), a.span.lo()),
916 shape.with_max_width(context.config),
921 if !comment.is_empty() {
922 if multi_line_before {
925 result.push_str(&comment);
927 if multi_line_after {
930 } else if insert_new_line {
932 if multi_line_after {
937 if derive_args.is_empty() {
938 result.push_str(&indent);
941 insert_new_line = true;
944 // Write the attribute itself.
945 if context.config.merge_derives() {
946 // If the attribute is `#[derive(...)]`, take the arguments.
947 if let Some(mut args) = get_derive_args(context, a) {
948 derive_args.append(&mut args);
950 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
951 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
952 // If not, rewrite the merged derives.
954 result.push_str(&try_opt!(format_derive(context, &derive_args, shape)));
959 result.push_str(&a_str);
962 result.push_str(&a_str);
965 is_prev_sugared_doc = a.is_sugared_doc;
971 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
972 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
973 let mut result = String::with_capacity(128);
974 result.push_str("#[derive(");
975 // 11 = `#[derive()]`
976 let initial_budget = try_opt!(shape.width.checked_sub(11));
977 let mut budget = initial_budget;
978 let num = derive_args.len();
979 for (i, a) in derive_args.iter().enumerate() {
981 let width = a.len() + 2;
984 // Remove trailing whitespace.
989 result.push_str(&(shape.indent + 9).to_string(context.config));
990 budget = initial_budget;
992 budget = budget.checked_sub(width).unwrap_or(0);
996 result.push_str(", ")
999 result.push_str(")]");
1003 fn is_derive(attr: &ast::Attribute) -> bool {
1005 Some(meta_item) => match meta_item.node {
1006 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1013 /// Returns the arguments of `#[derive(...)]`.
1014 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1015 attr.meta().and_then(|meta_item| match meta_item.node {
1016 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1017 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1020 .map(|a| context.snippet(a.span))
1021 .collect::<Vec<_>>(),
1028 // Rewrite `extern crate foo;` WITHOUT attributes.
1029 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1030 assert!(is_extern_crate(item));
1031 let new_str = context.snippet(item.span);
1032 Some(if contains_comment(&new_str) {
1035 let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1036 String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))