]> git.lizzy.rs Git - rust.git/blob - src/attr.rs
Use vertical layout for complex attributes
[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 syntax::ast;
15 use syntax::codemap::Span;
16
17 use comment::{combine_strs_with_missing_comments, contains_comment, rewrite_doc_comment};
18 use expr::rewrite_literal;
19 use lists::{itemize_list, write_list, ListFormatting};
20 use rewrite::{Rewrite, RewriteContext};
21 use shape::Shape;
22 use utils::{count_newlines, mk_sp};
23
24 /// Returns attributes on the given statement.
25 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
26     match stmt.node {
27         ast::StmtKind::Local(ref local) => &local.attrs,
28         ast::StmtKind::Item(ref item) => &item.attrs,
29         ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
30         ast::StmtKind::Mac(ref mac) => &mac.2,
31     }
32 }
33
34 /// Returns attributes that are within `outer_span`.
35 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
36     attrs
37         .iter()
38         .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
39         .cloned()
40         .collect()
41 }
42
43 fn is_derive(attr: &ast::Attribute) -> bool {
44     attr.check_name("derive")
45 }
46
47 /// Returns the arguments of `#[derive(...)]`.
48 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
49     attr.meta_item_list().map(|meta_item_list| {
50         meta_item_list
51             .iter()
52             .map(|nested_meta_item| context.snippet(nested_meta_item.span))
53             .collect()
54     })
55 }
56
57 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
58 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
59     let mut result = String::with_capacity(128);
60     result.push_str("#[derive(");
61     // 11 = `#[derive()]`
62     let initial_budget = shape.width.checked_sub(11)?;
63     let mut budget = initial_budget;
64     let num = derive_args.len();
65     for (i, a) in derive_args.iter().enumerate() {
66         // 2 = `, ` or `)]`
67         let width = a.len() + 2;
68         if width > budget {
69             if i > 0 {
70                 // Remove trailing whitespace.
71                 result.pop();
72             }
73             result.push('\n');
74             // 9 = `#[derive(`
75             result.push_str(&(shape.indent + 9).to_string(context.config));
76             budget = initial_budget;
77         } else {
78             budget = budget.checked_sub(width).unwrap_or(0);
79         }
80         result.push_str(a);
81         if i != num - 1 {
82             result.push_str(", ")
83         }
84     }
85     result.push_str(")]");
86     Some(result)
87 }
88
89 /// Returns the first group of attributes that fills the given predicate.
90 /// We consider two doc comments are in different group if they are separated by normal comments.
91 fn take_while_with_pred<'a, P>(
92     context: &RewriteContext,
93     attrs: &'a [ast::Attribute],
94     pred: P,
95 ) -> &'a [ast::Attribute]
96 where
97     P: Fn(&ast::Attribute) -> bool,
98 {
99     let mut len = 0;
100     let mut iter = attrs.iter().peekable();
101
102     while let Some(attr) = iter.next() {
103         if pred(attr) {
104             len += 1;
105         } else {
106             break;
107         }
108         if let Some(next_attr) = iter.peek() {
109             // Extract comments between two attributes.
110             let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
111             let snippet = context.snippet(span_between_attr);
112             if count_newlines(snippet) >= 2 || snippet.contains('/') {
113                 break;
114             }
115         }
116     }
117
118     &attrs[..len]
119 }
120
121 /// Rewrite the same kind of attributes at the same time. This includes doc
122 /// comments and derives.
123 fn rewrite_first_group_attrs(
124     context: &RewriteContext,
125     attrs: &[ast::Attribute],
126     shape: Shape,
127 ) -> Option<(usize, String)> {
128     if attrs.is_empty() {
129         return Some((0, String::new()));
130     }
131     // Rewrite doc comments
132     let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
133     if !sugared_docs.is_empty() {
134         let snippet = sugared_docs
135             .iter()
136             .map(|a| context.snippet(a.span))
137             .collect::<Vec<_>>()
138             .join("\n");
139         return Some((
140             sugared_docs.len(),
141             rewrite_doc_comment(&snippet, shape.comment(context.config), context.config)?,
142         ));
143     }
144     // Rewrite `#[derive(..)]`s.
145     if context.config.merge_derives() {
146         let derives = take_while_with_pred(context, attrs, is_derive);
147         if !derives.is_empty() {
148             let mut derive_args = vec![];
149             for derive in derives {
150                 derive_args.append(&mut get_derive_args(context, derive)?);
151             }
152             return Some((derives.len(), format_derive(context, &derive_args, shape)?));
153         }
154     }
155     // Rewrite the first attribute.
156     Some((1, attrs[0].rewrite(context, shape)?))
157 }
158
159 impl Rewrite for ast::NestedMetaItem {
160     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
161         match self.node {
162             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
163             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
164         }
165     }
166 }
167
168 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
169     // Look at before and after comment and see if there are any empty lines.
170     let comment_begin = comment.find('/');
171     let len = comment_begin.unwrap_or_else(|| comment.len());
172     let mlb = count_newlines(&comment[..len]) > 1;
173     let mla = if comment_begin.is_none() {
174         mlb
175     } else {
176         comment
177             .chars()
178             .rev()
179             .take_while(|c| c.is_whitespace())
180             .filter(|&c| c == '\n')
181             .count() > 1
182     };
183     (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
184 }
185
186 fn allow_mixed_tactic_for_nested_metaitem_list(list: &[ast::NestedMetaItem]) -> bool {
187     list.iter().all(|nested_metaitem| {
188         if let ast::NestedMetaItemKind::MetaItem(ref inner_metaitem) = nested_metaitem.node {
189             match inner_metaitem.node {
190                 ast::MetaItemKind::List(..) | ast::MetaItemKind::NameValue(..) => false,
191                 _ => true,
192             }
193         } else {
194             true
195         }
196     })
197 }
198
199 impl Rewrite for ast::MetaItem {
200     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
201         Some(match self.node {
202             ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
203             ast::MetaItemKind::List(ref list) => {
204                 let name = self.name.as_str();
205                 // 1 = `(`, 2 = `]` and `)`
206                 let item_shape = shape
207                     .visual_indent(0)
208                     .shrink_left(name.len() + 1)
209                     .and_then(|s| s.sub_width(2))?;
210                 let items = itemize_list(
211                     context.snippet_provider,
212                     list.iter(),
213                     ")",
214                     ",",
215                     |nested_meta_item| nested_meta_item.span.lo(),
216                     |nested_meta_item| nested_meta_item.span.hi(),
217                     |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
218                     self.span.lo(),
219                     self.span.hi(),
220                     false,
221                 );
222                 let item_vec = items.collect::<Vec<_>>();
223                 let tactic = if allow_mixed_tactic_for_nested_metaitem_list(list) {
224                     DefinitiveListTactic::Mixed
225                 } else {
226                     ::lists::definitive_tactic(
227                         &item_vec,
228                         ListTactic::HorizontalVertical,
229                         ::lists::Separator::Comma,
230                         item_shape.width,
231                     )
232                 };
233                 let fmt = ListFormatting {
234                     tactic,
235                     separator: ",",
236                     trailing_separator: SeparatorTactic::Never,
237                     separator_place: SeparatorPlace::Back,
238                     shape: item_shape,
239                     ends_with_newline: false,
240                     preserve_newline: false,
241                     config: context.config,
242                 };
243                 format!("{}({})", name, write_list(&item_vec, &fmt)?)
244             }
245             ast::MetaItemKind::NameValue(ref literal) => {
246                 let name = self.name.as_str();
247                 // 3 = ` = `
248                 let lit_shape = shape.shrink_left(name.len() + 3)?;
249                 // `rewrite_literal` returns `None` when `literal` exceeds max
250                 // width. Since a literal is basically unformattable unless it
251                 // is a string literal (and only if `format_strings` is set),
252                 // we might be better off ignoring the fact that the attribute
253                 // is longer than the max width and contiue on formatting.
254                 // See #2479 for example.
255                 let value = rewrite_literal(context, literal, lit_shape)
256                     .unwrap_or_else(|| context.snippet(literal.span).to_owned());
257                 format!("{} = {}", name, value)
258             }
259         })
260     }
261 }
262
263 impl Rewrite for ast::Attribute {
264     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
265         let prefix = match self.style {
266             ast::AttrStyle::Inner => "#!",
267             ast::AttrStyle::Outer => "#",
268         };
269         let snippet = context.snippet(self.span);
270         if self.is_sugared_doc {
271             rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
272         } else {
273             if contains_comment(snippet) {
274                 return Some(snippet.to_owned());
275             }
276             // 1 = `[`
277             let shape = shape.offset_left(prefix.len() + 1)?;
278             Some(
279                 self.meta()
280                     .and_then(|meta| meta.rewrite(context, shape))
281                     .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
282             )
283         }
284     }
285 }
286
287 impl<'a> Rewrite for [ast::Attribute] {
288     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
289         if self.is_empty() {
290             return Some(String::new());
291         }
292         let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
293         if self.len() == 1 || first_group_len == self.len() {
294             Some(first_group_str)
295         } else {
296             let rest_str = self[first_group_len..].rewrite(context, shape)?;
297             let missing_span = mk_sp(
298                 self[first_group_len - 1].span.hi(),
299                 self[first_group_len].span.lo(),
300             );
301             // Preserve an empty line before/after doc comments.
302             if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
303                 let snippet = context.snippet(missing_span);
304                 let (mla, mlb) = has_newlines_before_after_comment(snippet);
305                 let comment = ::comment::recover_missing_comment_in_span(
306                     missing_span,
307                     shape.with_max_width(context.config),
308                     context,
309                     0,
310                 )?;
311                 let comment = if comment.is_empty() {
312                     format!("\n{}", mlb)
313                 } else {
314                     format!("{}{}\n{}", mla, comment, mlb)
315                 };
316                 Some(format!(
317                     "{}{}{}{}",
318                     first_group_str,
319                     comment,
320                     shape.indent.to_string(context.config),
321                     rest_str
322                 ))
323             } else {
324                 combine_strs_with_missing_comments(
325                     context,
326                     &first_group_str,
327                     &rest_str,
328                     missing_span,
329                     shape,
330                     false,
331                 )
332             }
333         }
334     }
335 }