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