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