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