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