1 // Copyright 2018 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.
11 //! Format attributes and meta items.
14 use config::IndentStyle;
16 use syntax::codemap::Span;
18 use comment::{combine_strs_with_missing_comments, contains_comment, rewrite_doc_comment};
19 use expr::rewrite_literal;
20 use lists::{itemize_list, write_list, ListFormatting};
21 use rewrite::{Rewrite, RewriteContext};
23 use types::{rewrite_path, PathContext};
24 use utils::{count_newlines, mk_sp};
26 /// Returns attributes on the given statement.
27 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
29 ast::StmtKind::Local(ref local) => &local.attrs,
30 ast::StmtKind::Item(ref item) => &item.attrs,
31 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
32 ast::StmtKind::Mac(ref mac) => &mac.2,
36 /// Returns attributes that are within `outer_span`.
37 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
40 .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
45 fn is_derive(attr: &ast::Attribute) -> bool {
46 attr.check_name("derive")
49 /// Returns the arguments of `#[derive(...)]`.
50 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
51 attr.meta_item_list().map(|meta_item_list| {
54 .map(|nested_meta_item| context.snippet(nested_meta_item.span))
59 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
60 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
61 let mut result = String::with_capacity(128);
62 result.push_str("#[derive(");
64 let initial_budget = shape.width.checked_sub(11)?;
65 let mut budget = initial_budget;
66 let num = derive_args.len();
67 for (i, a) in derive_args.iter().enumerate() {
69 let width = a.len() + 2;
72 // Remove trailing whitespace.
77 result.push_str(&(shape.indent + 9).to_string(context.config));
78 budget = initial_budget;
80 budget = budget.saturating_sub(width);
87 result.push_str(")]");
91 /// Returns the first group of attributes that fills the given predicate.
92 /// We consider two doc comments are in different group if they are separated by normal comments.
93 fn take_while_with_pred<'a, P>(
94 context: &RewriteContext,
95 attrs: &'a [ast::Attribute],
97 ) -> &'a [ast::Attribute]
99 P: Fn(&ast::Attribute) -> bool,
102 let mut iter = attrs.iter().peekable();
104 while let Some(attr) = iter.next() {
110 if let Some(next_attr) = iter.peek() {
111 // Extract comments between two attributes.
112 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
113 let snippet = context.snippet(span_between_attr);
114 if count_newlines(snippet) >= 2 || snippet.contains('/') {
123 /// Rewrite the same kind of attributes at the same time. This includes doc
124 /// comments and derives.
125 fn rewrite_first_group_attrs(
126 context: &RewriteContext,
127 attrs: &[ast::Attribute],
129 ) -> Option<(usize, String)> {
130 if attrs.is_empty() {
131 return Some((0, String::new()));
133 // Rewrite doc comments
134 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
135 if !sugared_docs.is_empty() {
136 let snippet = sugared_docs
138 .map(|a| context.snippet(a.span))
143 rewrite_doc_comment(&snippet, shape.comment(context.config), context.config)?,
146 // Rewrite `#[derive(..)]`s.
147 if context.config.merge_derives() {
148 let derives = take_while_with_pred(context, attrs, is_derive);
149 if !derives.is_empty() {
150 let mut derive_args = vec![];
151 for derive in derives {
152 derive_args.append(&mut get_derive_args(context, derive)?);
154 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
157 // Rewrite the first attribute.
158 Some((1, attrs[0].rewrite(context, shape)?))
161 impl Rewrite for ast::NestedMetaItem {
162 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
164 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
165 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
170 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
171 // Look at before and after comment and see if there are any empty lines.
172 let comment_begin = comment.find('/');
173 let len = comment_begin.unwrap_or_else(|| comment.len());
174 let mlb = count_newlines(&comment[..len]) > 1;
175 let mla = if comment_begin.is_none() {
181 .take_while(|c| c.is_whitespace())
182 .filter(|&c| c == '\n')
185 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
188 fn allow_mixed_tactic_for_nested_metaitem_list(list: &[ast::NestedMetaItem]) -> bool {
189 list.iter().all(|nested_metaitem| {
190 if let ast::NestedMetaItemKind::MetaItem(ref inner_metaitem) = nested_metaitem.node {
191 match inner_metaitem.node {
192 ast::MetaItemKind::List(..) | ast::MetaItemKind::NameValue(..) => false,
201 impl Rewrite for ast::MetaItem {
202 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
203 Some(match self.node {
204 ast::MetaItemKind::Word => {
205 rewrite_path(context, PathContext::Type, None, &self.ident, shape)?
207 ast::MetaItemKind::List(ref list) => {
208 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
209 let item_shape = match context.config.indent_style() {
210 IndentStyle::Block => shape
211 .block_indent(context.config.tab_spaces())
212 .with_max_width(context.config),
213 // 1 = `(`, 2 = `]` and `)`
214 IndentStyle::Visual => shape
216 .shrink_left(path.len() + 1)
217 .and_then(|s| s.sub_width(2))?,
219 let items = itemize_list(
220 context.snippet_provider,
224 |nested_meta_item| nested_meta_item.span.lo(),
225 |nested_meta_item| nested_meta_item.span.hi(),
226 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
231 let item_vec = items.collect::<Vec<_>>();
232 let tactic = if allow_mixed_tactic_for_nested_metaitem_list(list) {
233 DefinitiveListTactic::Mixed
235 ::lists::definitive_tactic(
237 ListTactic::HorizontalVertical,
238 ::lists::Separator::Comma,
242 let fmt = ListFormatting {
245 trailing_separator: SeparatorTactic::Never,
246 separator_place: SeparatorPlace::Back,
248 ends_with_newline: false,
249 preserve_newline: false,
250 config: context.config,
252 let item_str = write_list(&item_vec, &fmt)?;
254 let one_line_budget = shape.offset_left(path.len())?.sub_width(3)?.width;
255 if context.config.indent_style() == IndentStyle::Visual
256 || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
258 format!("{}({})", path, item_str)
260 let indent = shape.indent.to_string_with_newline(context.config);
261 let nested_indent = item_shape.indent.to_string_with_newline(context.config);
262 format!("{}({}{}{})", path, nested_indent, item_str, indent)
265 ast::MetaItemKind::NameValue(ref literal) => {
266 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
268 let lit_shape = shape.shrink_left(path.len() + 3)?;
269 // `rewrite_literal` returns `None` when `literal` exceeds max
270 // width. Since a literal is basically unformattable unless it
271 // is a string literal (and only if `format_strings` is set),
272 // we might be better off ignoring the fact that the attribute
273 // is longer than the max width and contiue on formatting.
274 // See #2479 for example.
275 let value = rewrite_literal(context, literal, lit_shape)
276 .unwrap_or_else(|| context.snippet(literal.span).to_owned());
277 format!("{} = {}", path, value)
283 impl Rewrite for ast::Attribute {
284 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
285 let prefix = match self.style {
286 ast::AttrStyle::Inner => "#!",
287 ast::AttrStyle::Outer => "#",
289 let snippet = context.snippet(self.span);
290 if self.is_sugared_doc {
291 rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
293 if contains_comment(snippet) {
294 return Some(snippet.to_owned());
297 let shape = shape.offset_left(prefix.len() + 1)?;
300 .and_then(|meta| meta.rewrite(context, shape))
301 .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
307 impl<'a> Rewrite for [ast::Attribute] {
308 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
310 return Some(String::new());
312 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
313 if self.len() == 1 || first_group_len == self.len() {
314 Some(first_group_str)
316 let rest_str = self[first_group_len..].rewrite(context, shape)?;
317 let missing_span = mk_sp(
318 self[first_group_len - 1].span.hi(),
319 self[first_group_len].span.lo(),
321 // Preserve an empty line before/after doc comments.
322 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
323 let snippet = context.snippet(missing_span);
324 let (mla, mlb) = has_newlines_before_after_comment(snippet);
325 let comment = ::comment::recover_missing_comment_in_span(
327 shape.with_max_width(context.config),
331 let comment = if comment.is_empty() {
334 format!("{}{}\n{}", mla, comment, mlb)
340 shape.indent.to_string(context.config),
344 combine_strs_with_missing_comments(