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_trait, rewrite_associated_impl_type, rewrite_associated_type,
26 rewrite_static, rewrite_type_alias};
27 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
29 use macros::{rewrite_macro, MacroPosition};
31 use rewrite::{Rewrite, RewriteContext};
32 use utils::{self, contains_skip, inner_attributes, mk_sp};
34 fn is_use_item(item: &ast::Item) -> bool {
36 ast::ItemKind::Use(_) => true,
41 fn is_extern_crate(item: &ast::Item) -> bool {
43 ast::ItemKind::ExternCrate(..) => true,
48 pub struct FmtVisitor<'a> {
49 pub parse_session: &'a ParseSess,
50 pub codemap: &'a CodeMap,
51 pub buffer: StringBuffer,
52 pub last_pos: BytePos,
53 // FIXME: use an RAII util or closure for indenting
54 pub block_indent: Indent,
55 pub config: &'a Config,
56 pub is_if_else_block: bool,
59 impl<'a> FmtVisitor<'a> {
60 pub fn shape(&self) -> Shape {
61 Shape::indented(self.block_indent, self.config)
64 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
66 "visit_stmt: {:?} {:?}",
67 self.codemap.lookup_char_pos(stmt.span.lo()),
68 self.codemap.lookup_char_pos(stmt.span.hi())
72 ast::StmtKind::Item(ref item) => {
73 self.visit_item(item);
75 ast::StmtKind::Local(..) => {
76 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
77 self.push_rewrite(stmt.span(), rewrite);
79 ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
80 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
81 self.push_rewrite(stmt.span(), rewrite)
83 ast::StmtKind::Mac(ref mac) => {
84 let (ref mac, _macro_style, ref attrs) = **mac;
85 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
86 self.push_rewrite(stmt.span(), None);
88 self.visit_mac(mac, None, MacroPosition::Statement);
90 self.format_missing(stmt.span.hi());
95 pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
97 "visit_block: {:?} {:?}",
98 self.codemap.lookup_char_pos(b.span.lo()),
99 self.codemap.lookup_char_pos(b.span.hi())
102 // Check if this block has braces.
103 let snippet = self.snippet(b.span);
104 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
105 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
107 self.last_pos = self.last_pos + brace_compensation;
108 self.block_indent = self.block_indent.block_indent(self.config);
109 self.buffer.push_str("{");
111 if self.config.remove_blank_lines_at_start_or_end_of_block() {
112 if let Some(first_stmt) = b.stmts.first() {
113 let attr_lo = inner_attrs
115 inner_attributes(attrs).first().map(|attr| attr.span.lo())
118 // Attributes for an item in a statement position
119 // do not belong to the statement. (rust-lang/rust#34459)
120 if let ast::StmtKind::Item(ref item) = first_stmt.node {
123 first_stmt.attrs().first()
125 // Some stmts can have embedded attributes.
126 // e.g. `match { #![attr] ... }`
127 let attr_lo = attr.span.lo();
128 if attr_lo < first_stmt.span.lo() {
136 let snippet = self.snippet(mk_sp(
138 attr_lo.unwrap_or(first_stmt.span.lo()),
140 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
141 |(kind, _, s)| 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 if let Some(attrs) = inner_attrs {
155 self.visit_attrs(attrs, ast::AttrStyle::Inner);
158 for stmt in &b.stmts {
159 self.visit_stmt(stmt)
162 if !b.stmts.is_empty() {
163 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
164 if utils::semicolon_for_expr(&self.get_context(), expr) {
165 self.buffer.push_str(";");
170 let mut remove_len = BytePos(0);
171 if self.config.remove_blank_lines_at_start_or_end_of_block() {
172 if let Some(stmt) = b.stmts.last() {
173 let snippet = self.snippet(mk_sp(
175 source!(self, b.span).hi() - brace_compensation,
177 let len = CommentCodeSlices::new(&snippet)
179 .and_then(|(kind, _, s)| {
180 if kind == CodeCharKind::Normal && s.trim().is_empty() {
186 if let Some(len) = len {
187 remove_len = BytePos::from_usize(len);
192 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
193 if unindent_comment {
194 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
195 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
196 unindent_comment = snippet.contains("//") || snippet.contains("/*");
198 // FIXME: we should compress any newlines here to just one
199 if unindent_comment {
200 self.block_indent = self.block_indent.block_unindent(self.config);
202 self.format_missing_with_indent(
203 source!(self, b.span).hi() - brace_compensation - remove_len,
205 if unindent_comment {
206 self.block_indent = self.block_indent.block_indent(self.config);
208 self.close_block(unindent_comment);
209 self.last_pos = source!(self, b.span).hi();
212 // FIXME: this is a terrible hack to indent the comments between the last
213 // item in the block and the closing brace to the block's level.
214 // The closing brace itself, however, should be indented at a shallower
216 fn close_block(&mut self, unindent_comment: bool) {
217 let total_len = self.buffer.len;
218 let chars_too_many = if unindent_comment {
220 } else if self.config.hard_tabs() {
223 self.config.tab_spaces()
225 self.buffer.truncate(total_len - chars_too_many);
226 self.buffer.push_str("}");
227 self.block_indent = self.block_indent.block_unindent(self.config);
230 // Note that this only gets called for function definitions. Required methods
231 // on traits do not get handled here.
238 defaultness: ast::Defaultness,
239 inner_attrs: Option<&[ast::Attribute]>,
241 let indent = self.block_indent;
243 let rewrite = match fk {
244 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
256 mk_sp(s.lo(), b.span.lo()),
260 visit::FnKind::Method(ident, sig, vis, b) => {
271 vis.unwrap_or(&ast::Visibility::Inherited),
272 mk_sp(s.lo(), b.span.lo()),
276 visit::FnKind::Closure(_) => unreachable!(),
279 if let Some(fn_str) = rewrite {
280 self.format_missing_with_indent(source!(self, s).lo());
281 self.buffer.push_str(&fn_str);
282 if let Some(c) = fn_str.chars().last() {
284 self.last_pos = source!(self, block.span).hi();
289 self.format_missing(source!(self, block.span).lo());
292 self.last_pos = source!(self, block.span).lo();
293 self.visit_block(block, inner_attrs)
296 pub fn visit_item(&mut self, item: &ast::Item) {
297 skip_out_of_file_lines_range_visitor!(self, item.span);
299 // This is where we bail out if there is a skip attribute. This is only
300 // complex in the module case. It is complex because the module could be
301 // in a separate file and there might be attributes in both files, but
302 // the AST lumps them all together.
303 let mut attrs = item.attrs.clone();
305 ast::ItemKind::Mod(ref m) => {
306 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
307 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
308 if outer_file.name == inner_file.name {
309 // Module is inline, in this case we treat modules like any
311 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
312 self.push_rewrite(item.span, None);
315 } else if contains_skip(&item.attrs) {
316 // Module is not inline, but should be skipped.
319 // Module is not inline and should not be skipped. We want
320 // to process only the attributes in the current file.
321 let filterd_attrs = item.attrs
324 let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
325 if attr_file.name == outer_file.name {
331 .collect::<Vec<_>>();
332 // Assert because if we should skip it should be caught by
334 assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
335 attrs = filterd_attrs;
338 _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
339 self.push_rewrite(item.span, None);
345 ast::ItemKind::Use(ref vp) => {
346 self.format_import(&item.vis, vp, item.span, &item.attrs);
348 ast::ItemKind::Impl(..) => {
349 self.format_missing_with_indent(source!(self, item.span).lo());
350 let snippet = self.snippet(item.span);
351 let where_span_end = snippet
352 .find_uncommented("{")
353 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
354 if let Some(impl_str) =
355 format_impl(&self.get_context(), item, self.block_indent, where_span_end)
357 self.buffer.push_str(&impl_str);
358 self.last_pos = source!(self, item.span).hi();
361 ast::ItemKind::Trait(..) => {
362 self.format_missing_with_indent(item.span.lo());
363 if let Some(trait_str) = format_trait(&self.get_context(), item, self.block_indent)
365 self.buffer.push_str(&trait_str);
366 self.last_pos = source!(self, item.span).hi();
369 ast::ItemKind::ExternCrate(_) => {
370 self.format_missing_with_indent(source!(self, item.span).lo());
371 let new_str = self.snippet(item.span);
372 if contains_comment(&new_str) {
373 self.buffer.push_str(&new_str)
376 &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
378 .push_str(&Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"));
380 self.last_pos = source!(self, item.span).hi();
382 ast::ItemKind::Struct(ref def, ref generics) => {
384 let indent = self.block_indent;
385 let context = self.get_context();
386 ::items::format_struct(
396 ).map(|s| match *def {
397 ast::VariantData::Tuple(..) => s + ";",
401 self.push_rewrite(item.span, rewrite);
403 ast::ItemKind::Enum(ref def, ref generics) => {
404 self.format_missing_with_indent(source!(self, item.span).lo());
405 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
406 self.last_pos = source!(self, item.span).hi();
408 ast::ItemKind::Mod(ref module) => {
409 self.format_missing_with_indent(source!(self, item.span).lo());
410 self.format_mod(module, &item.vis, item.span, item.ident, &attrs);
412 ast::ItemKind::Mac(ref mac) => {
413 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
415 ast::ItemKind::ForeignMod(ref foreign_mod) => {
416 self.format_missing_with_indent(source!(self, item.span).lo());
417 self.format_foreign_mod(foreign_mod, item.span);
419 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
420 let rewrite = rewrite_static(
431 self.push_rewrite(item.span, rewrite);
433 ast::ItemKind::Const(ref ty, ref expr) => {
434 let rewrite = rewrite_static(
439 ast::Mutability::Immutable,
445 self.push_rewrite(item.span, rewrite);
447 ast::ItemKind::DefaultImpl(..) => {
448 // FIXME(#78): format impl definitions.
450 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
452 visit::FnKind::ItemFn(
464 ast::Defaultness::Final,
468 ast::ItemKind::Ty(ref ty, ref generics) => {
469 let rewrite = rewrite_type_alias(
478 self.push_rewrite(item.span, rewrite);
480 ast::ItemKind::Union(ref def, ref generics) => {
481 let rewrite = ::items::format_struct_struct(
492 self.push_rewrite(item.span, rewrite);
494 ast::ItemKind::GlobalAsm(..) => {
495 let snippet = Some(self.snippet(item.span));
496 self.push_rewrite(item.span, snippet);
498 ast::ItemKind::MacroDef(..) => {
499 // FIXME(#1539): macros 2.0
500 let mac_snippet = Some(self.snippet(item.span));
501 self.push_rewrite(item.span, mac_snippet);
506 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
507 skip_out_of_file_lines_range_visitor!(self, ti.span);
509 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
510 self.push_rewrite(ti.span, None);
515 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
516 let rewrite = rewrite_static(
518 &ast::Visibility::Inherited,
521 ast::Mutability::Immutable,
527 self.push_rewrite(ti.span, rewrite);
529 ast::TraitItemKind::Method(ref sig, None) => {
530 let indent = self.block_indent;
531 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
532 self.push_rewrite(ti.span, rewrite);
534 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
536 visit::FnKind::Method(ti.ident, sig, None, body),
540 ast::Defaultness::Final,
544 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
545 let rewrite = rewrite_associated_type(
547 type_default.as_ref(),
548 Some(type_param_bounds),
552 self.push_rewrite(ti.span, rewrite);
554 ast::TraitItemKind::Macro(ref mac) => {
555 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
560 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
561 skip_out_of_file_lines_range_visitor!(self, ii.span);
563 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
564 self.push_rewrite(ii.span, None);
569 ast::ImplItemKind::Method(ref sig, ref body) => {
571 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
579 ast::ImplItemKind::Const(ref ty, ref expr) => {
580 let rewrite = rewrite_static(
585 ast::Mutability::Immutable,
591 self.push_rewrite(ii.span, rewrite);
593 ast::ImplItemKind::Type(ref ty) => {
594 let rewrite = rewrite_associated_impl_type(
602 self.push_rewrite(ii.span, rewrite);
604 ast::ImplItemKind::Macro(ref mac) => {
605 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
610 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
611 skip_out_of_file_lines_range_visitor!(self, mac.span);
614 let shape = self.shape().sub_width(1).unwrap();
615 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
616 self.push_rewrite(mac.span, rewrite);
619 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
620 self.format_missing_with_indent(source!(self, span).lo());
621 let result = rewrite.unwrap_or_else(|| self.snippet(span));
622 self.buffer.push_str(&result);
623 self.last_pos = source!(self, span).hi();
626 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
628 parse_session: parse_session,
629 codemap: parse_session.codemap(),
630 buffer: StringBuffer::new(),
631 last_pos: BytePos(0),
632 block_indent: Indent::empty(),
634 is_if_else_block: false,
638 pub fn snippet(&self, span: Span) -> String {
639 match self.codemap.span_to_snippet(span) {
643 "Couldn't make snippet for span {:?}->{:?}",
644 self.codemap.lookup_char_pos(span.lo()),
645 self.codemap.lookup_char_pos(span.hi())
652 // Returns true if we should skip the following item.
653 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
654 if contains_skip(attrs) {
658 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
659 if attrs.is_empty() {
663 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
664 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
665 self.push_rewrite(span, rewrite);
672 items_left: &[ptr::P<ast::Item>],
677 F: Fn(&ast::Item) -> bool,
679 let mut last = self.codemap.lookup_line_range(items_left[0].span());
680 let item_length = items_left
683 is_item(&***ppi) && (!in_group || {
684 let current = self.codemap.lookup_line_range(ppi.span());
685 let in_same_group = current.lo < last.hi + 2;
691 let items = &items_left[..item_length];
693 let at_least_one_in_file_lines = items
695 .any(|item| !out_of_file_lines_range!(self, item.span));
697 if at_least_one_in_file_lines {
698 self.format_imports(items);
701 self.push_rewrite(item.span, None);
708 fn walk_mod_items(&mut self, m: &ast::Mod) {
709 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
710 while !items_left.is_empty() {
711 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
712 // to be potentially reordered within `format_imports`. Otherwise, just format the
713 // next item for output.
714 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
715 let used_items_len = self.reorder_items(
718 self.config.reorder_imports_in_group(),
720 let (_, rest) = items_left.split_at(used_items_len);
722 } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
723 let used_items_len = self.reorder_items(
726 self.config.reorder_extern_crates_in_group(),
728 let (_, rest) = items_left.split_at(used_items_len);
731 // `unwrap()` is safe here because we know `items_left`
732 // has elements from the loop condition
733 let (item, rest) = items_left.split_first().unwrap();
734 self.visit_item(item);
743 vis: &ast::Visibility,
746 attrs: &[ast::Attribute],
748 // Decide whether this is an inline mod or an external mod.
749 let local_file_name = self.codemap.span_to_filename(s);
750 let inner_span = source!(self, m.inner);
751 let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0) &&
752 local_file_name == self.codemap.span_to_filename(inner_span);
754 self.buffer.push_str(&*utils::format_visibility(vis));
755 self.buffer.push_str("mod ");
756 self.buffer.push_str(&ident.to_string());
759 match self.config.item_brace_style() {
760 BraceStyle::AlwaysNextLine => self.buffer
761 .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
762 _ => self.buffer.push_str(" {"),
764 // Hackery to account for the closing }.
765 let mod_lo = self.codemap.span_after(source!(self, s), "{");
767 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
768 let body_snippet = body_snippet.trim();
769 if body_snippet.is_empty() {
770 self.buffer.push_str("}");
772 self.last_pos = mod_lo;
773 self.block_indent = self.block_indent.block_indent(self.config);
774 self.visit_attrs(attrs, ast::AttrStyle::Inner);
775 self.walk_mod_items(m);
776 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
777 self.close_block(false);
779 self.last_pos = source!(self, m.inner).hi();
781 self.buffer.push_str(";");
782 self.last_pos = source!(self, s).hi();
786 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
787 self.block_indent = Indent::empty();
788 self.walk_mod_items(m);
789 self.format_missing_with_indent(filemap.end_pos);
792 pub fn get_context(&self) -> RewriteContext {
794 parse_session: self.parse_session,
795 codemap: self.codemap,
799 is_if_else_block: false,
800 force_one_line_chain: false,
805 impl Rewrite for ast::NestedMetaItem {
806 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
808 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
809 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
814 impl Rewrite for ast::MetaItem {
815 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
816 Some(match self.node {
817 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
818 ast::MetaItemKind::List(ref list) => {
819 let name = self.name.as_str();
820 // 3 = `#[` and `(`, 2 = `]` and `)`
821 let item_shape = try_opt!(
823 .shrink_left(name.len() + 3)
824 .and_then(|s| s.sub_width(2))
826 let items = itemize_list(
830 |nested_meta_item| nested_meta_item.span.lo(),
831 |nested_meta_item| nested_meta_item.span.hi(),
832 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
837 let item_vec = items.collect::<Vec<_>>();
838 let fmt = ListFormatting {
839 tactic: DefinitiveListTactic::Mixed,
841 trailing_separator: SeparatorTactic::Never,
842 separator_place: SeparatorPlace::Back,
844 ends_with_newline: false,
845 preserve_newline: false,
846 config: context.config,
848 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
850 ast::MetaItemKind::NameValue(ref literal) => {
851 let name = self.name.as_str();
852 let value = context.snippet(literal.span);
853 if &*name == "doc" && contains_comment(&value) {
854 let doc_shape = Shape {
855 width: cmp::min(shape.width, context.config.comment_width())
856 .checked_sub(shape.indent.width())
860 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
862 format!("{} = {}", name, value)
869 impl Rewrite for ast::Attribute {
870 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
871 try_opt!(self.meta())
872 .rewrite(context, shape)
873 .map(|rw| if self.is_sugared_doc {
876 let original = context.snippet(self.span);
877 let prefix = match self.style {
878 ast::AttrStyle::Inner => "#!",
879 ast::AttrStyle::Outer => "#",
881 if contains_comment(&original) {
884 format!("{}[{}]", prefix, rw)
890 impl<'a> Rewrite for [ast::Attribute] {
891 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
893 return Some(String::new());
895 let mut result = String::with_capacity(128);
896 let indent = shape.indent.to_string(context.config);
898 let mut derive_args = Vec::new();
900 let mut iter = self.iter().enumerate().peekable();
901 let mut insert_new_line = true;
902 let mut is_prev_sugared_doc = false;
903 while let Some((i, a)) = iter.next() {
904 let a_str = try_opt!(a.rewrite(context, shape));
906 // Write comments and blank lines between attributes.
908 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
909 // This particular horror show is to preserve line breaks in between doc
910 // comments. An alternative would be to force such line breaks to start
911 // with the usual doc comment token.
912 let (multi_line_before, multi_line_after) = if a.is_sugared_doc ||
915 // Look at before and after comment and see if there are any empty lines.
916 let comment_begin = comment.chars().position(|c| c == '/');
917 let len = comment_begin.unwrap_or_else(|| comment.len());
918 let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
919 let mla = if comment_begin.is_none() {
922 let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
923 let len = comment_end.unwrap();
928 .filter(|c| *c == '\n')
936 let comment = try_opt!(recover_missing_comment_in_span(
937 mk_sp(self[i - 1].span.hi(), a.span.lo()),
938 shape.with_max_width(context.config),
943 if !comment.is_empty() {
944 if multi_line_before {
947 result.push_str(&comment);
949 if multi_line_after {
952 } else if insert_new_line {
954 if multi_line_after {
959 if derive_args.is_empty() {
960 result.push_str(&indent);
963 insert_new_line = true;
966 // Write the attribute itself.
967 if context.config.merge_derives() {
968 // If the attribute is `#[derive(...)]`, take the arguments.
969 if let Some(mut args) = get_derive_args(context, a) {
970 derive_args.append(&mut args);
972 // If the next attribute is `#[derive(...)]` as well, skip rewriting.
973 Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
974 // If not, rewrite the merged derives.
976 result.push_str(&try_opt!(format_derive(context, &derive_args, shape)));
981 result.push_str(&a_str);
984 result.push_str(&a_str);
987 is_prev_sugared_doc = a.is_sugared_doc;
993 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
994 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
995 let mut result = String::with_capacity(128);
996 result.push_str("#[derive(");
997 // 11 = `#[derive()]`
998 let initial_budget = try_opt!(shape.width.checked_sub(11));
999 let mut budget = initial_budget;
1000 let num = derive_args.len();
1001 for (i, a) in derive_args.iter().enumerate() {
1003 let width = a.len() + 2;
1006 // Remove trailing whitespace.
1011 result.push_str(&(shape.indent + 9).to_string(context.config));
1012 budget = initial_budget;
1014 budget = budget.checked_sub(width).unwrap_or(0);
1018 result.push_str(", ")
1021 result.push_str(")]");
1025 fn is_derive(attr: &ast::Attribute) -> bool {
1027 Some(meta_item) => match meta_item.node {
1028 ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1035 /// Returns the arguments of `#[derive(...)]`.
1036 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1037 attr.meta().and_then(|meta_item| match meta_item.node {
1038 ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1039 // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1042 .map(|a| context.snippet(a.span))
1043 .collect::<Vec<_>>(),