]> git.lizzy.rs Git - rust.git/blob - src/attr.rs
6aa62f40db2440122719be9605bc58c2c9dfa21c
[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 comment::{contains_comment, rewrite_doc_comment};
14 use config::lists::*;
15 use config::IndentStyle;
16 use expr::rewrite_literal;
17 use lists::{itemize_list, write_list, ListFormatting};
18 use rewrite::{Rewrite, RewriteContext};
19 use shape::Shape;
20 use types::{rewrite_path, PathContext};
21 use utils::{count_newlines, mk_sp};
22
23 use std::borrow::Cow;
24 use syntax::ast;
25 use syntax::codemap::{BytePos, Span, DUMMY_SP};
26
27 /// Returns attributes on the given statement.
28 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
29     match stmt.node {
30         ast::StmtKind::Local(ref local) => &local.attrs,
31         ast::StmtKind::Item(ref item) => &item.attrs,
32         ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
33         ast::StmtKind::Mac(ref mac) => &mac.2,
34     }
35 }
36
37 /// Returns attributes that are within `outer_span`.
38 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
39     attrs
40         .iter()
41         .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
42         .cloned()
43         .collect()
44 }
45
46 fn is_derive(attr: &ast::Attribute) -> bool {
47     attr.check_name("derive")
48 }
49
50 /// Returns the arguments of `#[derive(...)]`.
51 fn get_derive_spans<'a>(attr: &ast::Attribute) -> Option<Vec<Span>> {
52     attr.meta_item_list().map(|meta_item_list| {
53         meta_item_list
54             .iter()
55             .map(|nested_meta_item| nested_meta_item.span)
56             .collect()
57     })
58 }
59
60 // The shape of the arguments to a function-like attribute.
61 fn argument_shape(
62     left: usize,
63     right: usize,
64     shape: Shape,
65     context: &RewriteContext,
66 ) -> Option<Shape> {
67     match context.config.indent_style() {
68         IndentStyle::Block => Some(
69             shape
70                 .block_indent(context.config.tab_spaces())
71                 .with_max_width(context.config),
72         ),
73         IndentStyle::Visual => shape
74             .visual_indent(0)
75             .shrink_left(left)
76             .and_then(|s| s.sub_width(right)),
77     }
78 }
79
80 fn format_derive(
81     derive_args: &[Span],
82     prefix: &str,
83     shape: Shape,
84     context: &RewriteContext,
85 ) -> Option<String> {
86     let mut result = String::with_capacity(128);
87     result.push_str(prefix);
88     result.push_str("[derive(");
89
90     let argument_shape = argument_shape(10 + prefix.len(), 2, shape, context)?;
91     let item_str = format_arg_list(
92         derive_args.iter(),
93         |_| DUMMY_SP.lo(),
94         |_| DUMMY_SP.hi(),
95         |sp| Some(context.snippet(**sp).to_owned()),
96         DUMMY_SP,
97         context,
98         argument_shape,
99         // 10 = "[derive()]", 3 = "()" and "]"
100         shape.offset_left(10 + prefix.len())?.sub_width(3)?,
101     )?;
102
103     result.push_str(&item_str);
104     if item_str.starts_with('\n') {
105         result.push(',');
106         result.push_str(&shape.indent.to_string_with_newline(context.config));
107     }
108     result.push_str(")]");
109     Some(result)
110 }
111
112 /// Returns the first group of attributes that fills the given predicate.
113 /// We consider two doc comments are in different group if they are separated by normal comments.
114 fn take_while_with_pred<'a, P>(
115     context: &RewriteContext,
116     attrs: &'a [ast::Attribute],
117     pred: P,
118 ) -> &'a [ast::Attribute]
119 where
120     P: Fn(&ast::Attribute) -> bool,
121 {
122     let mut len = 0;
123     let mut iter = attrs.iter().peekable();
124
125     while let Some(attr) = iter.next() {
126         if pred(attr) {
127             len += 1;
128         } else {
129             break;
130         }
131         if let Some(next_attr) = iter.peek() {
132             // Extract comments between two attributes.
133             let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
134             let snippet = context.snippet(span_between_attr);
135             if count_newlines(snippet) >= 2 || snippet.contains('/') {
136                 break;
137             }
138         }
139     }
140
141     &attrs[..len]
142 }
143
144 /// Rewrite the any doc comments which come before any other attributes.
145 fn rewrite_initial_doc_comments(
146     context: &RewriteContext,
147     attrs: &[ast::Attribute],
148     shape: Shape,
149 ) -> Option<(usize, Option<String>)> {
150     if attrs.is_empty() {
151         return Some((0, None));
152     }
153     // Rewrite doc comments
154     let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
155     if !sugared_docs.is_empty() {
156         let snippet = sugared_docs
157             .iter()
158             .map(|a| context.snippet(a.span))
159             .collect::<Vec<_>>()
160             .join("\n");
161         return Some((
162             sugared_docs.len(),
163             Some(rewrite_doc_comment(
164                 &snippet,
165                 shape.comment(context.config),
166                 context.config,
167             )?),
168         ));
169     }
170
171     Some((0, None))
172 }
173
174 impl Rewrite for ast::NestedMetaItem {
175     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
176         match self.node {
177             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
178             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
179         }
180     }
181 }
182
183 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
184     // Look at before and after comment and see if there are any empty lines.
185     let comment_begin = comment.find('/');
186     let len = comment_begin.unwrap_or_else(|| comment.len());
187     let mlb = count_newlines(&comment[..len]) > 1;
188     let mla = if comment_begin.is_none() {
189         mlb
190     } else {
191         comment
192             .chars()
193             .rev()
194             .take_while(|c| c.is_whitespace())
195             .filter(|&c| c == '\n')
196             .count() > 1
197     };
198     (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
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
210                 let snippet = context.snippet(self.span);
211                 // 2 = )] (this might go wrong if there is whitespace between the brackets, but
212                 // it's close enough).
213                 let snippet = snippet[..snippet.len() - 2].trim();
214                 let trailing_comma = if snippet.ends_with(',') { "," } else { "" };
215
216                 let argument_shape =
217                     argument_shape(path.len() + 1, 2 + trailing_comma.len(), shape, context)?;
218                 let item_str = format_arg_list(
219                     list.iter(),
220                     |nested_meta_item| nested_meta_item.span.lo(),
221                     |nested_meta_item| nested_meta_item.span.hi(),
222                     |nested_meta_item| nested_meta_item.rewrite(context, argument_shape),
223                     self.span,
224                     context,
225                     argument_shape,
226                     // 3 = "()" and "]"
227                     shape
228                         .offset_left(path.len())?
229                         .sub_width(3 + trailing_comma.len())?,
230                 )?;
231
232                 let indent = if item_str.starts_with('\n') {
233                     shape.indent.to_string_with_newline(context.config)
234                 } else {
235                     Cow::Borrowed("")
236                 };
237
238                 format!("{}({}{}{})", path, item_str, trailing_comma, indent)
239             }
240             ast::MetaItemKind::NameValue(ref literal) => {
241                 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
242                 // 3 = ` = `
243                 let lit_shape = shape.shrink_left(path.len() + 3)?;
244                 // `rewrite_literal` returns `None` when `literal` exceeds max
245                 // width. Since a literal is basically unformattable unless it
246                 // is a string literal (and only if `format_strings` is set),
247                 // we might be better off ignoring the fact that the attribute
248                 // is longer than the max width and contiue on formatting.
249                 // See #2479 for example.
250                 let value = rewrite_literal(context, literal, lit_shape)
251                     .unwrap_or_else(|| context.snippet(literal.span).to_owned());
252                 format!("{} = {}", path, value)
253             }
254         })
255     }
256 }
257
258 fn format_arg_list<I, T, F1, F2, F3>(
259     list: I,
260     get_lo: F1,
261     get_hi: F2,
262     get_item_string: F3,
263     span: Span,
264     context: &RewriteContext,
265     shape: Shape,
266     one_line_shape: Shape,
267 ) -> Option<String>
268 where
269     I: Iterator<Item = T>,
270     F1: Fn(&T) -> BytePos,
271     F2: Fn(&T) -> BytePos,
272     F3: Fn(&T) -> Option<String>,
273 {
274     let items = itemize_list(
275         context.snippet_provider,
276         list,
277         ")",
278         ",",
279         get_lo,
280         get_hi,
281         get_item_string,
282         span.lo(),
283         span.hi(),
284         false,
285     );
286     let item_vec = items.collect::<Vec<_>>();
287     let tactic = ::lists::definitive_tactic(
288         &item_vec,
289         ListTactic::HorizontalVertical,
290         ::lists::Separator::Comma,
291         shape.width,
292     );
293     let fmt = ListFormatting {
294         tactic,
295         separator: ",",
296         trailing_separator: SeparatorTactic::Never,
297         separator_place: SeparatorPlace::Back,
298         shape,
299         ends_with_newline: false,
300         preserve_newline: false,
301         nested: false,
302         config: context.config,
303     };
304     let item_str = write_list(&item_vec, &fmt)?;
305
306     let one_line_budget = one_line_shape.width;
307     if context.config.indent_style() == IndentStyle::Visual
308         || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
309     {
310         Some(item_str)
311     } else {
312         let nested_indent = shape.indent.to_string_with_newline(context.config);
313         Some(format!("{}{}", nested_indent, item_str))
314     }
315 }
316
317 impl Rewrite for ast::Attribute {
318     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
319         let snippet = context.snippet(self.span);
320         if self.is_sugared_doc {
321             rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
322         } else {
323             let prefix = attr_prefix(self);
324
325             if contains_comment(snippet) {
326                 return Some(snippet.to_owned());
327             }
328             // 1 = `[`
329             let shape = shape.offset_left(prefix.len() + 1)?;
330             Some(
331                 self.meta()
332                     .and_then(|meta| meta.rewrite(context, shape))
333                     .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
334             )
335         }
336     }
337 }
338
339 impl<'a> Rewrite for [ast::Attribute] {
340     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
341         if self.is_empty() {
342             return Some(String::new());
343         }
344
345         // The current remaining attributes.
346         let mut attrs = self;
347         let mut result = String::new();
348
349         // This is not just a simple map because we need to handle doc comments
350         // (where we take as many doc comment attributes as possible) and possibly
351         // merging derives into a single attribute.
352         loop {
353             if attrs.is_empty() {
354                 return Some(result);
355             }
356
357             // Handle doc comments.
358             let (doc_comment_len, doc_comment_str) =
359                 rewrite_initial_doc_comments(context, attrs, shape)?;
360             if doc_comment_len > 0 {
361                 let doc_comment_str = doc_comment_str.expect("doc comments, but no result");
362                 result.push_str(&doc_comment_str);
363
364                 let missing_span = attrs
365                     .get(doc_comment_len)
366                     .map(|next| mk_sp(attrs[doc_comment_len - 1].span.hi(), next.span.lo()));
367                 if let Some(missing_span) = missing_span {
368                     let snippet = context.snippet(missing_span);
369                     let (mla, mlb) = has_newlines_before_after_comment(snippet);
370                     let comment = ::comment::recover_missing_comment_in_span(
371                         missing_span,
372                         shape.with_max_width(context.config),
373                         context,
374                         0,
375                     )?;
376                     let comment = if comment.is_empty() {
377                         format!("\n{}", mlb)
378                     } else {
379                         format!("{}{}\n{}", mla, comment, mlb)
380                     };
381                     result.push_str(&comment);
382                     result.push_str(&shape.indent.to_string(context.config));
383                 }
384
385                 attrs = &attrs[doc_comment_len..];
386
387                 continue;
388             }
389
390             // Handle derives if we will merge them.
391             if context.config.merge_derives() && is_derive(&attrs[0]) {
392                 let derives = take_while_with_pred(context, attrs, is_derive);
393                 let mut derive_spans = vec![];
394                 for derive in derives {
395                     derive_spans.append(&mut get_derive_spans(derive)?);
396                 }
397                 let derive_str =
398                     format_derive(&derive_spans, attr_prefix(&attrs[0]), shape, context)?;
399                 result.push_str(&derive_str);
400
401                 let missing_span = attrs
402                     .get(derives.len())
403                     .map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
404                 if let Some(missing_span) = missing_span {
405                     let comment = ::comment::recover_missing_comment_in_span(
406                         missing_span,
407                         shape.with_max_width(context.config),
408                         context,
409                         0,
410                     )?;
411                     result.push_str(&comment);
412                     if let Some(next) = attrs.get(derives.len()) {
413                         if next.is_sugared_doc {
414                             let snippet = context.snippet(missing_span);
415                             let (_, mlb) = has_newlines_before_after_comment(snippet);
416                             result.push_str(&mlb);
417                         }
418                     }
419                     result.push('\n');
420                     result.push_str(&shape.indent.to_string(context.config));
421                 }
422
423                 attrs = &attrs[derives.len()..];
424
425                 continue;
426             }
427
428             // If we get here, then we have a regular attribute, just handle one
429             // at a time.
430
431             let formatted_attr = attrs[0].rewrite(context, shape)?;
432             result.push_str(&formatted_attr);
433
434             let missing_span = attrs
435                 .get(1)
436                 .map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
437             if let Some(missing_span) = missing_span {
438                 let comment = ::comment::recover_missing_comment_in_span(
439                     missing_span,
440                     shape.with_max_width(context.config),
441                     context,
442                     0,
443                 )?;
444                 result.push_str(&comment);
445                 if let Some(next) = attrs.get(1) {
446                     if next.is_sugared_doc {
447                         let snippet = context.snippet(missing_span);
448                         let (_, mlb) = has_newlines_before_after_comment(snippet);
449                         result.push_str(&mlb);
450                     }
451                 }
452                 result.push('\n');
453                 result.push_str(&shape.indent.to_string(context.config));
454             }
455
456             attrs = &attrs[1..];
457         }
458     }
459 }
460
461 fn attr_prefix(attr: &ast::Attribute) -> &'static str {
462     match attr.style {
463         ast::AttrStyle::Inner => "#!",
464         ast::AttrStyle::Outer => "#",
465     }
466 }