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.
65 context: &RewriteContext,
67 match context.config.indent_style() {
68 IndentStyle::Block => Some(
70 .block_indent(context.config.tab_spaces())
71 .with_max_width(context.config),
73 IndentStyle::Visual => shape
76 .and_then(|s| s.sub_width(right)),
84 context: &RewriteContext,
86 let mut result = String::with_capacity(128);
87 result.push_str(prefix);
88 result.push_str("[derive(");
90 let argument_shape = argument_shape(10 + prefix.len(), 2, shape, context)?;
91 let item_str = format_arg_list(
95 |sp| Some(context.snippet(**sp).to_owned()),
99 // 10 = "[derive()]", 3 = "()" and "]"
100 shape.offset_left(10 + prefix.len())?.sub_width(3)?,
104 result.push_str(&item_str);
105 if item_str.starts_with('\n') {
107 result.push_str(&shape.indent.to_string_with_newline(context.config));
109 result.push_str(")]");
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],
119 ) -> &'a [ast::Attribute]
121 P: Fn(&ast::Attribute) -> bool,
124 let mut iter = attrs.iter().peekable();
126 while let Some(attr) = iter.next() {
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('/') {
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],
150 ) -> Option<(usize, Option<String>)> {
151 if attrs.is_empty() {
152 return Some((0, None));
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
159 .map(|a| context.snippet(a.span))
164 Some(rewrite_doc_comment(
166 shape.comment(context.config),
175 impl Rewrite for ast::NestedMetaItem {
176 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
178 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
179 ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
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() {
195 .take_while(|c| c.is_whitespace())
196 .filter(|&c| c == '\n')
200 (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
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)?
209 ast::MetaItemKind::List(ref list) => {
210 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
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 { "" };
219 argument_shape(path.len() + 1, 2 + trailing_comma.len(), shape, context)?;
220 let item_str = format_arg_list(
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),
230 .offset_left(path.len())?
231 .sub_width(3 + trailing_comma.len())?,
232 Some(context.config.width_heuristics().fn_call_width),
235 let indent = if item_str.starts_with('\n') {
236 shape.indent.to_string_with_newline(context.config)
241 format!("{}({}{}{})", path, item_str, trailing_comma, indent)
243 ast::MetaItemKind::NameValue(ref literal) => {
244 let path = rewrite_path(context, PathContext::Type, None, &self.ident, shape)?;
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)
261 fn format_arg_list<I, T, F1, F2, F3>(
267 context: &RewriteContext,
269 one_line_shape: Shape,
270 one_line_limit: Option<usize>,
273 I: Iterator<Item = T>,
274 F1: Fn(&T) -> BytePos,
275 F2: Fn(&T) -> BytePos,
276 F3: Fn(&T) -> Option<String>,
278 let items = itemize_list(
279 context.snippet_provider,
290 let item_vec = items.collect::<Vec<_>>();
291 let tactic = if let Some(limit) = one_line_limit {
292 ListTactic::LimitedHorizontalVertical(limit)
294 ListTactic::HorizontalVertical
298 ::lists::definitive_tactic(&item_vec, tactic, ::lists::Separator::Comma, shape.width);
299 let fmt = ListFormatting {
302 trailing_separator: SeparatorTactic::Never,
303 separator_place: SeparatorPlace::Back,
305 ends_with_newline: false,
306 preserve_newline: false,
308 config: context.config,
310 let item_str = write_list(&item_vec, &fmt)?;
312 let one_line_budget = one_line_shape.width;
313 if context.config.indent_style() == IndentStyle::Visual
314 || (!item_str.contains('\n') && item_str.len() <= one_line_budget)
318 let nested_indent = shape.indent.to_string_with_newline(context.config);
319 Some(format!("{}{}", nested_indent, item_str))
323 impl Rewrite for ast::Attribute {
324 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
325 let snippet = context.snippet(self.span);
326 if self.is_sugared_doc {
327 rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
329 let prefix = attr_prefix(self);
331 if contains_comment(snippet) {
332 return Some(snippet.to_owned());
335 let shape = shape.offset_left(prefix.len() + 1)?;
338 .and_then(|meta| meta.rewrite(context, shape))
339 .map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
345 impl<'a> Rewrite for [ast::Attribute] {
346 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
348 return Some(String::new());
351 // The current remaining attributes.
352 let mut attrs = self;
353 let mut result = String::new();
355 // This is not just a simple map because we need to handle doc comments
356 // (where we take as many doc comment attributes as possible) and possibly
357 // merging derives into a single attribute.
359 if attrs.is_empty() {
363 // Handle doc comments.
364 let (doc_comment_len, doc_comment_str) =
365 rewrite_initial_doc_comments(context, attrs, shape)?;
366 if doc_comment_len > 0 {
367 let doc_comment_str = doc_comment_str.expect("doc comments, but no result");
368 result.push_str(&doc_comment_str);
370 let missing_span = attrs
371 .get(doc_comment_len)
372 .map(|next| mk_sp(attrs[doc_comment_len - 1].span.hi(), next.span.lo()));
373 if let Some(missing_span) = missing_span {
374 let snippet = context.snippet(missing_span);
375 let (mla, mlb) = has_newlines_before_after_comment(snippet);
376 let comment = ::comment::recover_missing_comment_in_span(
378 shape.with_max_width(context.config),
382 let comment = if comment.is_empty() {
385 format!("{}{}\n{}", mla, comment, mlb)
387 result.push_str(&comment);
388 result.push_str(&shape.indent.to_string(context.config));
391 attrs = &attrs[doc_comment_len..];
396 // Handle derives if we will merge them.
397 if context.config.merge_derives() && is_derive(&attrs[0]) {
398 let derives = take_while_with_pred(context, attrs, is_derive);
399 let mut derive_spans = vec![];
400 for derive in derives {
401 derive_spans.append(&mut get_derive_spans(derive)?);
404 format_derive(&derive_spans, attr_prefix(&attrs[0]), shape, context)?;
405 result.push_str(&derive_str);
407 let missing_span = attrs
409 .map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
410 if let Some(missing_span) = missing_span {
411 let comment = ::comment::recover_missing_comment_in_span(
413 shape.with_max_width(context.config),
417 result.push_str(&comment);
418 if let Some(next) = attrs.get(derives.len()) {
419 if next.is_sugared_doc {
420 let snippet = context.snippet(missing_span);
421 let (_, mlb) = has_newlines_before_after_comment(snippet);
422 result.push_str(&mlb);
426 result.push_str(&shape.indent.to_string(context.config));
429 attrs = &attrs[derives.len()..];
434 // If we get here, then we have a regular attribute, just handle one
437 let formatted_attr = attrs[0].rewrite(context, shape)?;
438 result.push_str(&formatted_attr);
440 let missing_span = attrs
442 .map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
443 if let Some(missing_span) = missing_span {
444 let comment = ::comment::recover_missing_comment_in_span(
446 shape.with_max_width(context.config),
450 result.push_str(&comment);
451 if let Some(next) = attrs.get(1) {
452 if next.is_sugared_doc {
453 let snippet = context.snippet(missing_span);
454 let (_, mlb) = has_newlines_before_after_comment(snippet);
455 result.push_str(&mlb);
459 result.push_str(&shape.indent.to_string(context.config));
467 fn attr_prefix(attr: &ast::Attribute) -> &'static str {
469 ast::AttrStyle::Inner => "#!",
470 ast::AttrStyle::Outer => "#",