rustfmt_nightly/
attr.rs

1//! Format attributes and meta items.
2
3use rustc_ast::HasAttrs;
4use rustc_ast::ast;
5use rustc_span::{Span, symbol::sym};
6use tracing::debug;
7
8use self::doc_comment::DocCommentFormatter;
9use crate::comment::{CommentStyle, contains_comment, rewrite_doc_comment};
10use crate::config::IndentStyle;
11use crate::config::lists::*;
12use crate::expr::rewrite_literal;
13use crate::lists::{ListFormatting, Separator, definitive_tactic, itemize_list, write_list};
14use crate::overflow;
15use crate::rewrite::{Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult};
16use crate::shape::Shape;
17use crate::source_map::SpanUtils;
18use crate::types::{PathContext, rewrite_path};
19use crate::utils::{count_newlines, mk_sp};
20
21mod doc_comment;
22
23/// Returns attributes on the given statement.
24pub(crate) fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
25    stmt.attrs()
26}
27
28pub(crate) fn get_span_without_attrs(stmt: &ast::Stmt) -> Span {
29    match stmt.kind {
30        ast::StmtKind::Let(ref local) => local.span,
31        ast::StmtKind::Item(ref item) => item.span,
32        ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => expr.span,
33        ast::StmtKind::MacCall(ref mac_stmt) => mac_stmt.mac.span(),
34        ast::StmtKind::Empty => stmt.span,
35    }
36}
37
38/// Returns attributes that are within `outer_span`.
39pub(crate) fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> ast::AttrVec {
40    attrs
41        .iter()
42        .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi())
43        .cloned()
44        .collect()
45}
46
47fn is_derive(attr: &ast::Attribute) -> bool {
48    attr.has_name(sym::derive)
49}
50
51// The shape of the arguments to a function-like attribute.
52fn argument_shape(
53    left: usize,
54    right: usize,
55    combine: bool,
56    shape: Shape,
57    context: &RewriteContext<'_>,
58) -> Option<Shape> {
59    match context.config.indent_style() {
60        IndentStyle::Block => {
61            if combine {
62                shape.offset_left(left)
63            } else {
64                Some(
65                    shape
66                        .block_indent(context.config.tab_spaces())
67                        .with_max_width(context.config),
68                )
69            }
70        }
71        IndentStyle::Visual => shape
72            .visual_indent(0)
73            .shrink_left(left)
74            .and_then(|s| s.sub_width(right)),
75    }
76}
77
78fn format_derive(
79    derives: &[ast::Attribute],
80    shape: Shape,
81    context: &RewriteContext<'_>,
82) -> Option<String> {
83    // Collect all items from all attributes
84    let all_items = derives
85        .iter()
86        .map(|attr| {
87            // Parse the derive items and extract the span for each item; if any
88            // attribute is not parseable, none of the attributes will be
89            // reformatted.
90            let item_spans = attr.meta_item_list().map(|meta_item_list| {
91                meta_item_list
92                    .into_iter()
93                    .map(|meta_item_inner| meta_item_inner.span())
94            })?;
95
96            let items = itemize_list(
97                context.snippet_provider,
98                item_spans,
99                ")",
100                ",",
101                |span| span.lo(),
102                |span| span.hi(),
103                |span| Ok(context.snippet(*span).to_owned()),
104                // We update derive attribute spans to start after the opening '('
105                // This helps us focus parsing to just what's inside #[derive(...)]
106                context.snippet_provider.span_after(attr.span, "("),
107                attr.span.hi(),
108                false,
109            );
110
111            Some(items)
112        })
113        // Fail if any attribute failed.
114        .collect::<Option<Vec<_>>>()?
115        // Collect the results into a single, flat, Vec.
116        .into_iter()
117        .flatten()
118        .collect::<Vec<_>>();
119
120    // Collect formatting parameters.
121    let prefix = attr_prefix(&derives[0]);
122    let argument_shape = argument_shape(
123        "[derive()]".len() + prefix.len(),
124        ")]".len(),
125        false,
126        shape,
127        context,
128    )?;
129    let one_line_shape = shape
130        .offset_left("[derive()]".len() + prefix.len())?
131        .sub_width("()]".len())?;
132    let one_line_budget = one_line_shape.width;
133
134    let tactic = definitive_tactic(
135        &all_items,
136        ListTactic::HorizontalVertical,
137        Separator::Comma,
138        argument_shape.width,
139    );
140    let trailing_separator = match context.config.indent_style() {
141        // We always add the trailing comma and remove it if it is not needed.
142        IndentStyle::Block => SeparatorTactic::Always,
143        IndentStyle::Visual => SeparatorTactic::Never,
144    };
145
146    // Format the collection of items.
147    let fmt = ListFormatting::new(argument_shape, context.config)
148        .tactic(tactic)
149        .trailing_separator(trailing_separator)
150        .ends_with_newline(false);
151    let item_str = write_list(&all_items, &fmt).ok()?;
152
153    debug!("item_str: '{}'", item_str);
154
155    // Determine if the result will be nested, i.e. if we're using the block
156    // indent style and either the items are on multiple lines or we've exceeded
157    // our budget to fit on a single line.
158    let nested = context.config.indent_style() == IndentStyle::Block
159        && (item_str.contains('\n') || item_str.len() > one_line_budget);
160
161    // Format the final result.
162    let mut result = String::with_capacity(128);
163    result.push_str(prefix);
164    result.push_str("[derive(");
165    if nested {
166        let nested_indent = argument_shape.indent.to_string_with_newline(context.config);
167        result.push_str(&nested_indent);
168        result.push_str(&item_str);
169        result.push_str(&shape.indent.to_string_with_newline(context.config));
170    } else if let SeparatorTactic::Always = context.config.trailing_comma() {
171        // Retain the trailing comma.
172        result.push_str(&item_str);
173    } else if item_str.ends_with(',') {
174        // Remove the trailing comma.
175        result.push_str(&item_str[..item_str.len() - 1]);
176    } else {
177        result.push_str(&item_str);
178    }
179    result.push_str(")]");
180
181    Some(result)
182}
183
184/// Returns the first group of attributes that fills the given predicate.
185/// We consider two doc comments are in different group if they are separated by normal comments.
186fn take_while_with_pred<'a, P>(
187    context: &RewriteContext<'_>,
188    attrs: &'a [ast::Attribute],
189    pred: P,
190) -> &'a [ast::Attribute]
191where
192    P: Fn(&ast::Attribute) -> bool,
193{
194    let mut len = 0;
195    let mut iter = attrs.iter().peekable();
196
197    while let Some(attr) = iter.next() {
198        if pred(attr) {
199            len += 1;
200        } else {
201            break;
202        }
203        if let Some(next_attr) = iter.peek() {
204            // Extract comments between two attributes.
205            let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
206            let snippet = context.snippet(span_between_attr);
207            if count_newlines(snippet) >= 2 || snippet.contains('/') {
208                break;
209            }
210        }
211    }
212
213    &attrs[..len]
214}
215
216/// Rewrite the any doc comments which come before any other attributes.
217fn rewrite_initial_doc_comments(
218    context: &RewriteContext<'_>,
219    attrs: &[ast::Attribute],
220    shape: Shape,
221) -> Result<(usize, Option<String>), RewriteError> {
222    if attrs.is_empty() {
223        return Ok((0, None));
224    }
225    // Rewrite doc comments
226    let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_doc_comment());
227    if !sugared_docs.is_empty() {
228        let snippet = sugared_docs
229            .iter()
230            .map(|a| context.snippet(a.span))
231            .collect::<Vec<_>>()
232            .join("\n");
233        return Ok((
234            sugared_docs.len(),
235            Some(rewrite_doc_comment(
236                &snippet,
237                shape.comment(context.config),
238                context.config,
239            )?),
240        ));
241    }
242
243    Ok((0, None))
244}
245
246impl Rewrite for ast::MetaItemInner {
247    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
248        self.rewrite_result(context, shape).ok()
249    }
250
251    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
252        match self {
253            ast::MetaItemInner::MetaItem(ref meta_item) => meta_item.rewrite_result(context, shape),
254            ast::MetaItemInner::Lit(ref l) => {
255                rewrite_literal(context, l.as_token_lit(), l.span, shape)
256            }
257        }
258    }
259}
260
261fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
262    // Look at before and after comment and see if there are any empty lines.
263    let comment_begin = comment.find('/');
264    let len = comment_begin.unwrap_or_else(|| comment.len());
265    let mlb = count_newlines(&comment[..len]) > 1;
266    let mla = if comment_begin.is_none() {
267        mlb
268    } else {
269        comment
270            .chars()
271            .rev()
272            .take_while(|c| c.is_whitespace())
273            .filter(|&c| c == '\n')
274            .count()
275            > 1
276    };
277    (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
278}
279
280impl Rewrite for ast::MetaItem {
281    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
282        self.rewrite_result(context, shape).ok()
283    }
284
285    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
286        Ok(match self.kind {
287            ast::MetaItemKind::Word => {
288                rewrite_path(context, PathContext::Type, &None, &self.path, shape)?
289            }
290            ast::MetaItemKind::List(ref list) => {
291                let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
292                let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span);
293                overflow::rewrite_with_parens(
294                    context,
295                    &path,
296                    list.iter(),
297                    // 1 = "]"
298                    shape.sub_width(1).max_width_error(shape.width, self.span)?,
299                    self.span,
300                    context.config.attr_fn_like_width(),
301                    Some(if has_trailing_comma {
302                        SeparatorTactic::Always
303                    } else {
304                        SeparatorTactic::Never
305                    }),
306                )?
307            }
308            ast::MetaItemKind::NameValue(ref lit) => {
309                let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?;
310                // 3 = ` = `
311                let lit_shape = shape
312                    .shrink_left(path.len() + 3)
313                    .max_width_error(shape.width, self.span)?;
314                // `rewrite_literal` returns `None` when `lit` exceeds max
315                // width. Since a literal is basically unformattable unless it
316                // is a string literal (and only if `format_strings` is set),
317                // we might be better off ignoring the fact that the attribute
318                // is longer than the max width and continue on formatting.
319                // See #2479 for example.
320                let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape)
321                    .unwrap_or_else(|_| context.snippet(lit.span).to_owned());
322                format!("{path} = {value}")
323            }
324        })
325    }
326}
327
328impl Rewrite for ast::Attribute {
329    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
330        self.rewrite_result(context, shape).ok()
331    }
332
333    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
334        let snippet = context.snippet(self.span);
335        if self.is_doc_comment() {
336            rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
337        } else {
338            let should_skip = self
339                .ident()
340                .map(|s| context.skip_context.attributes.skip(s.name.as_str()))
341                .unwrap_or(false);
342            let prefix = attr_prefix(self);
343
344            if should_skip || contains_comment(snippet) {
345                return Ok(snippet.to_owned());
346            }
347
348            if let Some(ref meta) = self.meta() {
349                // This attribute is possibly a doc attribute needing normalization to a doc comment
350                if context.config.normalize_doc_attributes() && meta.has_name(sym::doc) {
351                    if let Some(ref literal) = meta.value_str() {
352                        let comment_style = match self.style {
353                            ast::AttrStyle::Inner => CommentStyle::Doc,
354                            ast::AttrStyle::Outer => CommentStyle::TripleSlash,
355                        };
356
357                        let literal_str = literal.as_str();
358                        let doc_comment_formatter =
359                            DocCommentFormatter::new(literal_str, comment_style);
360                        let doc_comment = format!("{doc_comment_formatter}");
361                        return rewrite_doc_comment(
362                            &doc_comment,
363                            shape.comment(context.config),
364                            context.config,
365                        );
366                    }
367                }
368
369                // 1 = `[`
370                let shape = shape
371                    .offset_left(prefix.len() + 1)
372                    .max_width_error(shape.width, self.span)?;
373                Ok(meta.rewrite_result(context, shape).map_or_else(
374                    |_| snippet.to_owned(),
375                    |rw| match &self.kind {
376                        ast::AttrKind::Normal(normal_attr) => match normal_attr.item.unsafety {
377                            // For #![feature(unsafe_attributes)]
378                            // See https://github.com/rust-lang/rust/issues/123757
379                            ast::Safety::Unsafe(_) => format!("{}[unsafe({})]", prefix, rw),
380                            _ => format!("{}[{}]", prefix, rw),
381                        },
382                        _ => format!("{}[{}]", prefix, rw),
383                    },
384                ))
385            } else {
386                Ok(snippet.to_owned())
387            }
388        }
389    }
390}
391
392impl Rewrite for [ast::Attribute] {
393    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
394        self.rewrite_result(context, shape).ok()
395    }
396
397    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
398        if self.is_empty() {
399            return Ok(String::new());
400        }
401
402        // The current remaining attributes.
403        let mut attrs = self;
404        let mut result = String::new();
405
406        // Determine if the source text is annotated with `#[rustfmt::skip::attributes(derive)]`
407        // or `#![rustfmt::skip::attributes(derive)]`
408        let skip_derives = context.skip_context.attributes.skip("derive");
409
410        // This is not just a simple map because we need to handle doc comments
411        // (where we take as many doc comment attributes as possible) and possibly
412        // merging derives into a single attribute.
413        loop {
414            if attrs.is_empty() {
415                return Ok(result);
416            }
417
418            // Handle doc comments.
419            let (doc_comment_len, doc_comment_str) =
420                rewrite_initial_doc_comments(context, attrs, shape)?;
421            if doc_comment_len > 0 {
422                let doc_comment_str = doc_comment_str.expect("doc comments, but no result");
423                result.push_str(&doc_comment_str);
424
425                let missing_span = attrs
426                    .get(doc_comment_len)
427                    .map(|next| mk_sp(attrs[doc_comment_len - 1].span.hi(), next.span.lo()));
428                if let Some(missing_span) = missing_span {
429                    let snippet = context.snippet(missing_span);
430                    let (mla, mlb) = has_newlines_before_after_comment(snippet);
431                    let comment = crate::comment::recover_missing_comment_in_span(
432                        missing_span,
433                        shape.with_max_width(context.config),
434                        context,
435                        0,
436                    )?;
437                    let comment = if comment.is_empty() {
438                        format!("\n{mlb}")
439                    } else {
440                        format!("{mla}{comment}\n{mlb}")
441                    };
442                    result.push_str(&comment);
443                    result.push_str(&shape.indent.to_string(context.config));
444                }
445
446                attrs = &attrs[doc_comment_len..];
447
448                continue;
449            }
450
451            // Handle derives if we will merge them.
452            if !skip_derives && context.config.merge_derives() && is_derive(&attrs[0]) {
453                let derives = take_while_with_pred(context, attrs, is_derive);
454                let derive_str = format_derive(derives, shape, context).unknown_error()?;
455                result.push_str(&derive_str);
456
457                let missing_span = attrs
458                    .get(derives.len())
459                    .map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
460                if let Some(missing_span) = missing_span {
461                    let comment = crate::comment::recover_missing_comment_in_span(
462                        missing_span,
463                        shape.with_max_width(context.config),
464                        context,
465                        0,
466                    )?;
467                    result.push_str(&comment);
468                    if let Some(next) = attrs.get(derives.len()) {
469                        if next.is_doc_comment() {
470                            let snippet = context.snippet(missing_span);
471                            let (_, mlb) = has_newlines_before_after_comment(snippet);
472                            result.push_str(mlb);
473                        }
474                    }
475                    result.push('\n');
476                    result.push_str(&shape.indent.to_string(context.config));
477                }
478
479                attrs = &attrs[derives.len()..];
480
481                continue;
482            }
483
484            // If we get here, then we have a regular attribute, just handle one
485            // at a time.
486
487            let formatted_attr = attrs[0].rewrite_result(context, shape)?;
488            result.push_str(&formatted_attr);
489
490            let missing_span = attrs
491                .get(1)
492                .map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
493            if let Some(missing_span) = missing_span {
494                let comment = crate::comment::recover_missing_comment_in_span(
495                    missing_span,
496                    shape.with_max_width(context.config),
497                    context,
498                    0,
499                )?;
500                result.push_str(&comment);
501                if let Some(next) = attrs.get(1) {
502                    if next.is_doc_comment() {
503                        let snippet = context.snippet(missing_span);
504                        let (_, mlb) = has_newlines_before_after_comment(snippet);
505                        result.push_str(mlb);
506                    }
507                }
508                result.push('\n');
509                result.push_str(&shape.indent.to_string(context.config));
510            }
511
512            attrs = &attrs[1..];
513        }
514    }
515}
516
517fn attr_prefix(attr: &ast::Attribute) -> &'static str {
518    match attr.style {
519        ast::AttrStyle::Inner => "#!",
520        ast::AttrStyle::Outer => "#",
521    }
522}
523
524pub(crate) trait MetaVisitor<'ast> {
525    fn visit_meta_item(&mut self, meta_item: &'ast ast::MetaItem) {
526        match meta_item.kind {
527            ast::MetaItemKind::Word => self.visit_meta_word(meta_item),
528            ast::MetaItemKind::List(ref list) => self.visit_meta_list(meta_item, list),
529            ast::MetaItemKind::NameValue(ref lit) => self.visit_meta_name_value(meta_item, lit),
530        }
531    }
532
533    fn visit_meta_list(
534        &mut self,
535        _meta_item: &'ast ast::MetaItem,
536        list: &'ast [ast::MetaItemInner],
537    ) {
538        for nm in list {
539            self.visit_meta_item_inner(nm);
540        }
541    }
542
543    fn visit_meta_word(&mut self, _meta_item: &'ast ast::MetaItem) {}
544
545    fn visit_meta_name_value(
546        &mut self,
547        _meta_item: &'ast ast::MetaItem,
548        _lit: &'ast ast::MetaItemLit,
549    ) {
550    }
551
552    fn visit_meta_item_inner(&mut self, nm: &'ast ast::MetaItemInner) {
553        match nm {
554            ast::MetaItemInner::MetaItem(ref meta_item) => self.visit_meta_item(meta_item),
555            ast::MetaItemInner::Lit(ref lit) => self.visit_meta_item_lit(lit),
556        }
557    }
558
559    fn visit_meta_item_lit(&mut self, _lit: &'ast ast::MetaItemLit) {}
560}