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.
13 use comment::{contains_comment, rewrite_doc_comment};
15 use config::IndentStyle;
16 use expr::rewrite_literal;
17 use lists::{itemize_list, write_list, ListFormatting};
18 use rewrite::{Rewrite, RewriteContext};
20 use types::{rewrite_path, PathContext};
21 use utils::{count_newlines, mk_sp};
25 use syntax::codemap::{BytePos, Span, DUMMY_SP};
27 /// Returns attributes on the given statement.
28 pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
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,
37 /// Returns attributes that are within `outer_span`.
38 pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec<ast::Attribute> {
41 .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
46 fn is_derive(attr: &ast::Attribute) -> bool {
47 attr.check_name("derive")
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| {
55 .map(|nested_meta_item| nested_meta_item.span)
60 // The shape of the arguments to a function-like attribute.
66 context: &RewriteContext,
68 match context.config.indent_style() {
69 IndentStyle::Block => {
71 shape.offset_left(left)
75 .block_indent(context.config.tab_spaces())
76 .with_max_width(context.config),
80 IndentStyle::Visual => shape
83 .and_then(|s| s.sub_width(right)),
91 context: &RewriteContext,
93 let mut result = String::with_capacity(128);
94 result.push_str(prefix);
95 result.push_str("[derive(");
97 let argument_shape = argument_shape(10 + prefix.len(), 2, false, shape, context)?;
98 let item_str = format_arg_list(
102 |sp| Some(context.snippet(**sp).to_owned()),
106 // 10 = "[derive()]", 3 = "()" and "]"
107 shape.offset_left(10 + prefix.len())?.sub_width(3)?,
112 result.push_str(&item_str);
113 if item_str.starts_with('\n') {
115 result.push_str(&shape.indent.to_string_with_newline(context.config));
117 result.push_str(")]");
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],
127 ) -> &'a [ast::Attribute]
129 P: Fn(&ast::Attribute) -> bool,
132 let mut iter = attrs.iter().peekable();
134 while let Some(attr) = iter.next() {
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('/') {
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],
158 ) -> Option<(usize, Option<String>)> {
159 if attrs.is_empty() {
160 return Some((0, None));
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
167 .map(|a| context.snippet(a.span))
172 Some(rewrite_doc_comment(
174 shape.comment(context.config),
183 impl Rewrite for ast::NestedMetaItem {
184 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
186 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
187 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
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() {
203 .take_while(|c| c.is_whitespace())
204 .filter(|&c| c == '\n')
208 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
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)?
217 ast::MetaItemKind::List(ref list) => {
218 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
220 let snippet = context.snippet(self.span);
221 // 2 = )] (this might go wrong if there is whitespace between the brackets, but
222 // it's close enough).
223 let snippet = snippet[..snippet.len() - 2].trim();
224 let trailing_comma = if snippet.ends_with(',') { "," } else { "" };
225 let combine = list.len() == 1 && match list[0].node {
226 ast::NestedMetaItemKind::Literal(..) => false,
227 ast::NestedMetaItemKind::MetaItem(ref inner_meta_item) => {
228 match inner_meta_item.node {
229 ast::MetaItemKind::List(..) => rewrite_path(
233 &inner_meta_item.ident,
235 ).map_or(false, |s| s.len() + path.len() + 2 <= shape.width),
241 let argument_shape = argument_shape(
243 2 + trailing_comma.len(),
248 let item_str = format_arg_list(
250 |nested_meta_item| nested_meta_item.span.lo(),
251 |nested_meta_item| nested_meta_item.span.hi(),
252 |nested_meta_item| nested_meta_item.rewrite(context, argument_shape),
258 .offset_left(path.len())?
259 .sub_width(3 + trailing_comma.len())?,
260 Some(context.config.width_heuristics().fn_call_width),
264 let indent = if item_str.starts_with('\n') {
265 shape.indent.to_string_with_newline(context.config)
270 format!("{}({}{}{})", path, item_str, trailing_comma, indent)
272 ast::MetaItemKind::NameValue(ref literal) => {
273 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
275 let lit_shape = shape.shrink_left(path.len() + 3)?;
276 // `rewrite_literal` returns `None` when `literal` exceeds max
277 // width. Since a literal is basically unformattable unless it
278 // is a string literal (and only if `format_strings` is set),
279 // we might be better off ignoring the fact that the attribute
280 // is longer than the max width and contiue on formatting.
281 // See #2479 for example.
282 let value = rewrite_literal(context, literal, lit_shape)
283 .unwrap_or_else(|| context.snippet(literal.span).to_owned());
284 format!("{} = {}", path, value)
290 fn format_arg_list<I, T, F1, F2, F3>(
296 context: &RewriteContext,
298 one_line_shape: Shape,
299 one_line_limit: Option<usize>,
303 I: Iterator<Item = T>,
304 F1: Fn(&T) -> BytePos,
305 F2: Fn(&T) -> BytePos,
306 F3: Fn(&T) -> Option<String>,
308 let items = itemize_list(
309 context.snippet_provider,
320 let item_vec = items.collect::<Vec<_>>();
321 let tactic = if let Some(limit) = one_line_limit {
322 ListTactic::LimitedHorizontalVertical(limit)
324 ListTactic::HorizontalVertical
328 ::lists::definitive_tactic(&item_vec, tactic, ::lists::Separator::Comma, shape.width);
329 let fmt = ListFormatting {
332 trailing_separator: SeparatorTactic::Never,
333 separator_place: SeparatorPlace::Back,
335 ends_with_newline: false,
336 preserve_newline: false,
338 config: context.config,
340 let item_str = write_list(&item_vec, &fmt)?;
342 let one_line_budget = one_line_shape.width;
343 if context.config.indent_style() == IndentStyle::Visual
345 || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
349 let nested_indent = shape.indent.to_string_with_newline(context.config);
350 Some(format!("{}{}", nested_indent, item_str))
354 impl Rewrite for ast::Attribute {
355 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
356 let snippet = context.snippet(self.span);
357 if self.is_sugared_doc {
358 rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
360 let prefix = attr_prefix(self);
362 if contains_comment(snippet) {
363 return Some(snippet.to_owned());
366 let shape = shape.offset_left(prefix.len() + 1)?;
369 .and_then(|meta| meta.rewrite(context, shape))
370 .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
376 impl<'a> Rewrite for [ast::Attribute] {
377 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
379 return Some(String::new());
382 // The current remaining attributes.
383 let mut attrs = self;
384 let mut result = String::new();
386 // This is not just a simple map because we need to handle doc comments
387 // (where we take as many doc comment attributes as possible) and possibly
388 // merging derives into a single attribute.
390 if attrs.is_empty() {
394 // Handle doc comments.
395 let (doc_comment_len, doc_comment_str) =
396 rewrite_initial_doc_comments(context, attrs, shape)?;
397 if doc_comment_len > 0 {
398 let doc_comment_str = doc_comment_str.expect("doc comments, but no result");
399 result.push_str(&doc_comment_str);
401 let missing_span = attrs
402 .get(doc_comment_len)
403 .map(|next| mk_sp(attrs[doc_comment_len - 1].span.hi(), next.span.lo()));
404 if let Some(missing_span) = missing_span {
405 let snippet = context.snippet(missing_span);
406 let (mla, mlb) = has_newlines_before_after_comment(snippet);
407 let comment = ::comment::recover_missing_comment_in_span(
409 shape.with_max_width(context.config),
413 let comment = if comment.is_empty() {
416 format!("{}{}\n{}", mla, comment, mlb)
418 result.push_str(&comment);
419 result.push_str(&shape.indent.to_string(context.config));
422 attrs = &attrs[doc_comment_len..];
427 // Handle derives if we will merge them.
428 if context.config.merge_derives() && is_derive(&attrs[0]) {
429 let derives = take_while_with_pred(context, attrs, is_derive);
430 let mut derive_spans = vec![];
431 for derive in derives {
432 derive_spans.append(&mut get_derive_spans(derive)?);
435 format_derive(&derive_spans, attr_prefix(&attrs[0]), shape, context)?;
436 result.push_str(&derive_str);
438 let missing_span = attrs
440 .map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
441 if let Some(missing_span) = missing_span {
442 let comment = ::comment::recover_missing_comment_in_span(
444 shape.with_max_width(context.config),
448 result.push_str(&comment);
449 if let Some(next) = attrs.get(derives.len()) {
450 if next.is_sugared_doc {
451 let snippet = context.snippet(missing_span);
452 let (_, mlb) = has_newlines_before_after_comment(snippet);
453 result.push_str(&mlb);
457 result.push_str(&shape.indent.to_string(context.config));
460 attrs = &attrs[derives.len()..];
465 // If we get here, then we have a regular attribute, just handle one
468 let formatted_attr = attrs[0].rewrite(context, shape)?;
469 result.push_str(&formatted_attr);
471 let missing_span = attrs
473 .map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
474 if let Some(missing_span) = missing_span {
475 let comment = ::comment::recover_missing_comment_in_span(
477 shape.with_max_width(context.config),
481 result.push_str(&comment);
482 if let Some(next) = attrs.get(1) {
483 if next.is_sugared_doc {
484 let snippet = context.snippet(missing_span);
485 let (_, mlb) = has_newlines_before_after_comment(snippet);
486 result.push_str(&mlb);
490 result.push_str(&shape.indent.to_string(context.config));
498 fn attr_prefix(attr: &ast::Attribute) -> &'static str {
500 ast::AttrStyle::Inner => "#!",
501 ast::AttrStyle::Outer => "#",