]> git.lizzy.rs Git - rust.git/blob - src/attr.rs
Merge pull request #2795 from jechase/issue-2794
[rust.git] / src / attr.rs
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.
4 //
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.
10
11 //! Format attributes and meta items.
12
13 use config::lists::*;
14 use config::IndentStyle;
15 use syntax::ast;
16 use syntax::codemap::Span;
17
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};
22 use shape::Shape;
23 use types::{rewrite_path, PathContext};
24 use utils::{count_newlines, mk_sp};
25
26 /// Returns attributes on the given statement.
27 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
28     match stmt.node {
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,
33     }
34 }
35
36 /// Returns attributes that are within `outer_span`.
37 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
38     attrs
39         .iter()
40         .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
41         .cloned()
42         .collect()
43 }
44
45 fn is_derive(attr: &ast::Attribute) -> bool {
46     attr.check_name("derive")
47 }
48
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| {
52         meta_item_list
53             .iter()
54             .map(|nested_meta_item| context.snippet(nested_meta_item.span))
55             .collect()
56     })
57 }
58
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(");
63     // 11 = `#[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() {
68         // 2 = `, ` or `)]`
69         let width = a.len() + 2;
70         if width > budget {
71             if i > 0 {
72                 // Remove trailing whitespace.
73                 result.pop();
74             }
75             result.push('\n');
76             // 9 = `#[derive(`
77             result.push_str(&(shape.indent + 9).to_string(context.config));
78             budget = initial_budget;
79         } else {
80             budget = budget.saturating_sub(width);
81         }
82         result.push_str(a);
83         if i != num - 1 {
84             result.push_str(", ")
85         }
86     }
87     result.push_str(")]");
88     Some(result)
89 }
90
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],
96     pred: P,
97 ) -> &'a [ast::Attribute]
98 where
99     P: Fn(&ast::Attribute) -> bool,
100 {
101     let mut len = 0;
102     let mut iter = attrs.iter().peekable();
103
104     while let Some(attr) = iter.next() {
105         if pred(attr) {
106             len += 1;
107         } else {
108             break;
109         }
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('/') {
115                 break;
116             }
117         }
118     }
119
120     &attrs[..len]
121 }
122
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],
128     shape: Shape,
129 ) -> Option<(usize, String)> {
130     if attrs.is_empty() {
131         return Some((0, String::new()));
132     }
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
137             .iter()
138             .map(|a| context.snippet(a.span))
139             .collect::<Vec<_>>()
140             .join("\n");
141         return Some((
142             sugared_docs.len(),
143             rewrite_doc_comment(&snippet, shape.comment(context.config), context.config)?,
144         ));
145     }
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)?);
153             }
154             return Some((derives.len(), format_derive(context, &derive_args, shape)?));
155         }
156     }
157     // Rewrite the first attribute.
158     Some((1, attrs[0].rewrite(context, shape)?))
159 }
160
161 impl Rewrite for ast::NestedMetaItem {
162     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
163         match self.node {
164             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
165             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
166         }
167     }
168 }
169
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() {
176         mlb
177     } else {
178         comment
179             .chars()
180             .rev()
181             .take_while(|c| c.is_whitespace())
182             .filter(|&c| c == '\n')
183             .count() > 1
184     };
185     (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
186 }
187
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,
193                 _ => true,
194             }
195         } else {
196             true
197         }
198     })
199 }
200
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)?
206             }
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
215                         .visual_indent(0)
216                         .shrink_left(path.len() + 1)
217                         .and_then(|s| s.sub_width(2))?,
218                 };
219                 let items = itemize_list(
220                     context.snippet_provider,
221                     list.iter(),
222                     ")",
223                     ",",
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),
227                     self.span.lo(),
228                     self.span.hi(),
229                     false,
230                 );
231                 let item_vec = items.collect::<Vec<_>>();
232                 let tactic = if allow_mixed_tactic_for_nested_metaitem_list(list) {
233                     DefinitiveListTactic::Mixed
234                 } else {
235                     ::lists::definitive_tactic(
236                         &item_vec,
237                         ListTactic::HorizontalVertical,
238                         ::lists::Separator::Comma,
239                         item_shape.width,
240                     )
241                 };
242                 let fmt = ListFormatting {
243                     tactic,
244                     separator: ",",
245                     trailing_separator: SeparatorTactic::Never,
246                     separator_place: SeparatorPlace::Back,
247                     shape: item_shape,
248                     ends_with_newline: false,
249                     preserve_newline: false,
250                     nested: false,
251                     config: context.config,
252                 };
253                 let item_str = write_list(&item_vec, &fmt)?;
254                 // 3 = "()" and "]"
255                 let one_line_budget = shape.offset_left(path.len())?.sub_width(3)?.width;
256                 if context.config.indent_style() == IndentStyle::Visual
257                     || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
258                 {
259                     format!("{}({})", path, item_str)
260                 } else {
261                     let indent = shape.indent.to_string_with_newline(context.config);
262                     let nested_indent = item_shape.indent.to_string_with_newline(context.config);
263                     format!("{}({}{}{})", path, nested_indent, item_str, indent)
264                 }
265             }
266             ast::MetaItemKind::NameValue(ref literal) => {
267                 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
268                 // 3 = ` = `
269                 let lit_shape = shape.shrink_left(path.len() + 3)?;
270                 // `rewrite_literal` returns `None` when `literal` exceeds max
271                 // width. Since a literal is basically unformattable unless it
272                 // is a string literal (and only if `format_strings` is set),
273                 // we might be better off ignoring the fact that the attribute
274                 // is longer than the max width and contiue on formatting.
275                 // See #2479 for example.
276                 let value = rewrite_literal(context, literal, lit_shape)
277                     .unwrap_or_else(|| context.snippet(literal.span).to_owned());
278                 format!("{} = {}", path, value)
279             }
280         })
281     }
282 }
283
284 impl Rewrite for ast::Attribute {
285     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
286         let prefix = match self.style {
287             ast::AttrStyle::Inner => "#!",
288             ast::AttrStyle::Outer => "#",
289         };
290         let snippet = context.snippet(self.span);
291         if self.is_sugared_doc {
292             rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
293         } else {
294             if contains_comment(snippet) {
295                 return Some(snippet.to_owned());
296             }
297             // 1 = `[`
298             let shape = shape.offset_left(prefix.len() + 1)?;
299             Some(
300                 self.meta()
301                     .and_then(|meta| meta.rewrite(context, shape))
302                     .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
303             )
304         }
305     }
306 }
307
308 impl<'a> Rewrite for [ast::Attribute] {
309     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
310         if self.is_empty() {
311             return Some(String::new());
312         }
313         let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
314         if self.len() == 1 || first_group_len == self.len() {
315             Some(first_group_str)
316         } else {
317             let rest_str = self[first_group_len..].rewrite(context, shape)?;
318             let missing_span = mk_sp(
319                 self[first_group_len - 1].span.hi(),
320                 self[first_group_len].span.lo(),
321             );
322             // Preserve an empty line before/after doc comments.
323             if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
324                 let snippet = context.snippet(missing_span);
325                 let (mla, mlb) = has_newlines_before_after_comment(snippet);
326                 let comment = ::comment::recover_missing_comment_in_span(
327                     missing_span,
328                     shape.with_max_width(context.config),
329                     context,
330                     0,
331                 )?;
332                 let comment = if comment.is_empty() {
333                     format!("\n{}", mlb)
334                 } else {
335                     format!("{}{}\n{}", mla, comment, mlb)
336                 };
337                 Some(format!(
338                     "{}{}{}{}",
339                     first_group_str,
340                     comment,
341                     shape.indent.to_string(context.config),
342                     rest_str
343                 ))
344             } else {
345                 combine_strs_with_missing_comments(
346                     context,
347                     &first_group_str,
348                     &rest_str,
349                     missing_span,
350                     shape,
351                     false,
352                 )
353             }
354         }
355     }
356 }