]> git.lizzy.rs Git - rust.git/blob - src/attr.rs
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::{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         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 =
298         ::lists::definitive_tactic(&item_vec, tactic, ::lists::Separator::Comma, shape.width);
299     let fmt = ListFormatting::new(shape, context.config)
300         .tactic(tactic)
301         .ends_with_newline(false);
302     let item_str = write_list(&item_vec, &fmt)?;
303
304     let one_line_budget = one_line_shape.width;
305     if context.config.indent_style() == IndentStyle::Visual
306         || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
307     {
308         Some(item_str)
309     } else {
310         let nested_indent = shape.indent.to_string_with_newline(context.config);
311         Some(format!("{}{}", nested_indent, item_str))
312     }
313 }
314
315 impl Rewrite for ast::Attribute {
316     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
317         let snippet = context.snippet(self.span);
318         if self.is_sugared_doc {
319             rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
320         } else {
321             let prefix = attr_prefix(self);
322
323             if contains_comment(snippet) {
324                 return Some(snippet.to_owned());
325             }
326             // 1 = `[`
327             let shape = shape.offset_left(prefix.len() + 1)?;
328             Some(
329                 self.meta()
330                     .and_then(|meta| meta.rewrite(context, shape))
331                     .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
332             )
333         }
334     }
335 }
336
337 impl<'a> Rewrite for [ast::Attribute] {
338     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
339         if self.is_empty() {
340             return Some(String::new());
341         }
342
343         // The current remaining attributes.
344         let mut attrs = self;
345         let mut result = String::new();
346
347         // This is not just a simple map because we need to handle doc comments
348         // (where we take as many doc comment attributes as possible) and possibly
349         // merging derives into a single attribute.
350         loop {
351             if attrs.is_empty() {
352                 return Some(result);
353             }
354
355             // Handle doc comments.
356             let (doc_comment_len, doc_comment_str) =
357                 rewrite_initial_doc_comments(context, attrs, shape)?;
358             if doc_comment_len > 0 {
359                 let doc_comment_str = doc_comment_str.expect("doc comments, but no result");
360                 result.push_str(&doc_comment_str);
361
362                 let missing_span = attrs
363                     .get(doc_comment_len)
364                     .map(|next| mk_sp(attrs[doc_comment_len - 1].span.hi(), next.span.lo()));
365                 if let Some(missing_span) = missing_span {
366                     let snippet = context.snippet(missing_span);
367                     let (mla, mlb) = has_newlines_before_after_comment(snippet);
368                     let comment = ::comment::recover_missing_comment_in_span(
369                         missing_span,
370                         shape.with_max_width(context.config),
371                         context,
372                         0,
373                     )?;
374                     let comment = if comment.is_empty() {
375                         format!("\n{}", mlb)
376                     } else {
377                         format!("{}{}\n{}", mla, comment, mlb)
378                     };
379                     result.push_str(&comment);
380                     result.push_str(&shape.indent.to_string(context.config));
381                 }
382
383                 attrs = &attrs[doc_comment_len..];
384
385                 continue;
386             }
387
388             // Handle derives if we will merge them.
389             if context.config.merge_derives() && is_derive(&attrs[0]) {
390                 let derives = take_while_with_pred(context, attrs, is_derive);
391                 let mut derive_spans = vec![];
392                 for derive in derives {
393                     derive_spans.append(&mut get_derive_spans(derive)?);
394                 }
395                 let derive_str =
396                     format_derive(&derive_spans, attr_prefix(&attrs[0]), shape, context)?;
397                 result.push_str(&derive_str);
398
399                 let missing_span = attrs
400                     .get(derives.len())
401                     .map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
402                 if let Some(missing_span) = missing_span {
403                     let comment = ::comment::recover_missing_comment_in_span(
404                         missing_span,
405                         shape.with_max_width(context.config),
406                         context,
407                         0,
408                     )?;
409                     result.push_str(&comment);
410                     if let Some(next) = attrs.get(derives.len()) {
411                         if next.is_sugared_doc {
412                             let snippet = context.snippet(missing_span);
413                             let (_, mlb) = has_newlines_before_after_comment(snippet);
414                             result.push_str(&mlb);
415                         }
416                     }
417                     result.push('\n');
418                     result.push_str(&shape.indent.to_string(context.config));
419                 }
420
421                 attrs = &attrs[derives.len()..];
422
423                 continue;
424             }
425
426             // If we get here, then we have a regular attribute, just handle one
427             // at a time.
428
429             let formatted_attr = attrs[0].rewrite(context, shape)?;
430             result.push_str(&formatted_attr);
431
432             let missing_span = attrs
433                 .get(1)
434                 .map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
435             if let Some(missing_span) = missing_span {
436                 let comment = ::comment::recover_missing_comment_in_span(
437                     missing_span,
438                     shape.with_max_width(context.config),
439                     context,
440                     0,
441                 )?;
442                 result.push_str(&comment);
443                 if let Some(next) = attrs.get(1) {
444                     if next.is_sugared_doc {
445                         let snippet = context.snippet(missing_span);
446                         let (_, mlb) = has_newlines_before_after_comment(snippet);
447                         result.push_str(&mlb);
448                     }
449                 }
450                 result.push('\n');
451                 result.push_str(&shape.indent.to_string(context.config));
452             }
453
454             attrs = &attrs[1..];
455         }
456     }
457 }
458
459 fn attr_prefix(attr: &ast::Attribute) -> &'static str {
460     match attr.style {
461         ast::AttrStyle::Inner => "#!",
462         ast::AttrStyle::Outer => "#",
463     }
464 }