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.
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.
11 //! Format attributes and meta items.
14 use config::IndentStyle;
16 use syntax::codemap::Span;
18 use comment::{combine_strs_with_missing_comments, contains_comment, rewrite_doc_comment};
19 use expr::rewrite_literal;
20 use lists::{itemize_list, write_list, ListFormatting};
21 use rewrite::{Rewrite, RewriteContext};
23 use utils::{count_newlines, mk_sp};
25 /// Returns attributes on the given statement.
26 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
28 ast::StmtKind::Local(ref local) => &local.attrs,
29 ast::StmtKind::Item(ref item) => &item.attrs,
30 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
31 ast::StmtKind::Mac(ref mac) => &mac.2,
35 /// Returns attributes that are within `outer_span`.
36 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
39 .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
44 fn is_derive(attr: &ast::Attribute) -> bool {
45 attr.check_name("derive")
48 /// Returns the arguments of `#[derive(...)]`.
49 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
50 attr.meta_item_list().map(|meta_item_list| {
53 .map(|nested_meta_item| context.snippet(nested_meta_item.span))
58 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
59 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
60 let mut result = String::with_capacity(128);
61 result.push_str("#[derive(");
63 let initial_budget = shape.width.checked_sub(11)?;
64 let mut budget = initial_budget;
65 let num = derive_args.len();
66 for (i, a) in derive_args.iter().enumerate() {
68 let width = a.len() + 2;
71 // Remove trailing whitespace.
76 result.push_str(&(shape.indent + 9).to_string(context.config));
77 budget = initial_budget;
79 budget = budget.checked_sub(width).unwrap_or(0);
86 result.push_str(")]");
90 /// Returns the first group of attributes that fills the given predicate.
91 /// We consider two doc comments are in different group if they are separated by normal comments.
92 fn take_while_with_pred<'a, P>(
93 context: &RewriteContext,
94 attrs: &'a [ast::Attribute],
96 ) -> &'a [ast::Attribute]
98 P: Fn(&ast::Attribute) -> bool,
101 let mut iter = attrs.iter().peekable();
103 while let Some(attr) = iter.next() {
109 if let Some(next_attr) = iter.peek() {
110 // Extract comments between two attributes.
111 let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
112 let snippet = context.snippet(span_between_attr);
113 if count_newlines(snippet) >= 2 || snippet.contains('/') {
122 /// Rewrite the same kind of attributes at the same time. This includes doc
123 /// comments and derives.
124 fn rewrite_first_group_attrs(
125 context: &RewriteContext,
126 attrs: &[ast::Attribute],
128 ) -> Option<(usize, String)> {
129 if attrs.is_empty() {
130 return Some((0, String::new()));
132 // Rewrite doc comments
133 let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
134 if !sugared_docs.is_empty() {
135 let snippet = sugared_docs
137 .map(|a| context.snippet(a.span))
142 rewrite_doc_comment(&snippet, shape.comment(context.config), context.config)?,
145 // Rewrite `#[derive(..)]`s.
146 if context.config.merge_derives() {
147 let derives = take_while_with_pred(context, attrs, is_derive);
148 if !derives.is_empty() {
149 let mut derive_args = vec![];
150 for derive in derives {
151 derive_args.append(&mut get_derive_args(context, derive)?);
153 return Some((derives.len(), format_derive(context, &derive_args, shape)?));
156 // Rewrite the first attribute.
157 Some((1, attrs[0].rewrite(context, shape)?))
160 impl Rewrite for ast::NestedMetaItem {
161 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
163 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
164 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
169 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
170 // Look at before and after comment and see if there are any empty lines.
171 let comment_begin = comment.find('/');
172 let len = comment_begin.unwrap_or_else(|| comment.len());
173 let mlb = count_newlines(&comment[..len]) > 1;
174 let mla = if comment_begin.is_none() {
180 .take_while(|c| c.is_whitespace())
181 .filter(|&c| c == '\n')
184 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
187 fn allow_mixed_tactic_for_nested_metaitem_list(list: &[ast::NestedMetaItem]) -> bool {
188 list.iter().all(|nested_metaitem| {
189 if let ast::NestedMetaItemKind::MetaItem(ref inner_metaitem) = nested_metaitem.node {
190 match inner_metaitem.node {
191 ast::MetaItemKind::List(..) | ast::MetaItemKind::NameValue(..) => false,
200 impl Rewrite for ast::MetaItem {
201 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
202 Some(match self.node {
203 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
204 ast::MetaItemKind::List(ref list) => {
205 let name = self.name.as_str();
206 let item_shape = match context.config.indent_style() {
207 IndentStyle::Block => shape
208 .block_indent(context.config.tab_spaces())
209 .with_max_width(context.config),
210 // 1 = `(`, 2 = `]` and `)`
211 IndentStyle::Visual => shape
213 .shrink_left(name.len() + 1)
214 .and_then(|s| s.sub_width(2))?,
216 let items = itemize_list(
217 context.snippet_provider,
221 |nested_meta_item| nested_meta_item.span.lo(),
222 |nested_meta_item| nested_meta_item.span.hi(),
223 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
228 let item_vec = items.collect::<Vec<_>>();
229 let tactic = if allow_mixed_tactic_for_nested_metaitem_list(list) {
230 DefinitiveListTactic::Mixed
232 ::lists::definitive_tactic(
234 ListTactic::HorizontalVertical,
235 ::lists::Separator::Comma,
239 let fmt = ListFormatting {
242 trailing_separator: SeparatorTactic::Never,
243 separator_place: SeparatorPlace::Back,
245 ends_with_newline: false,
246 preserve_newline: false,
247 config: context.config,
249 let item_str = write_list(&item_vec, &fmt)?;
250 let one_line_budget = shape.offset_left(name.len())?.sub_width(2)?.width;
251 if context.config.indent_style() == IndentStyle::Visual
252 || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
254 format!("{}({})", name, item_str)
256 let indent = shape.indent.to_string_with_newline(context.config);
257 let nested_indent = item_shape.indent.to_string_with_newline(context.config);
258 format!("{}({}{}{})", name, nested_indent, item_str, indent)
261 ast::MetaItemKind::NameValue(ref literal) => {
262 let name = self.name.as_str();
264 let lit_shape = shape.shrink_left(name.len() + 3)?;
265 // `rewrite_literal` returns `None` when `literal` exceeds max
266 // width. Since a literal is basically unformattable unless it
267 // is a string literal (and only if `format_strings` is set),
268 // we might be better off ignoring the fact that the attribute
269 // is longer than the max width and contiue on formatting.
270 // See #2479 for example.
271 let value = rewrite_literal(context, literal, lit_shape)
272 .unwrap_or_else(|| context.snippet(literal.span).to_owned());
273 format!("{} = {}", name, value)
279 impl Rewrite for ast::Attribute {
280 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
281 let prefix = match self.style {
282 ast::AttrStyle::Inner => "#!",
283 ast::AttrStyle::Outer => "#",
285 let snippet = context.snippet(self.span);
286 if self.is_sugared_doc {
287 rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
289 if contains_comment(snippet) {
290 return Some(snippet.to_owned());
293 let shape = shape.offset_left(prefix.len() + 1)?;
296 .and_then(|meta| meta.rewrite(context, shape))
297 .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
303 impl<'a> Rewrite for [ast::Attribute] {
304 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
306 return Some(String::new());
308 let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
309 if self.len() == 1 || first_group_len == self.len() {
310 Some(first_group_str)
312 let rest_str = self[first_group_len..].rewrite(context, shape)?;
313 let missing_span = mk_sp(
314 self[first_group_len - 1].span.hi(),
315 self[first_group_len].span.lo(),
317 // Preserve an empty line before/after doc comments.
318 if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
319 let snippet = context.snippet(missing_span);
320 let (mla, mlb) = has_newlines_before_after_comment(snippet);
321 let comment = ::comment::recover_missing_comment_in_span(
323 shape.with_max_width(context.config),
327 let comment = if comment.is_empty() {
330 format!("{}{}\n{}", mla, comment, mlb)
336 shape.indent.to_string(context.config),
340 combine_strs_with_missing_comments(