clippy_utils/
attrs.rs

1//! Utility functions for attributes, including Clippy's built-in ones
2
3use crate::source::SpanRangeExt;
4use crate::{sym, tokenize_with_text};
5use rustc_ast::attr::AttributeExt;
6use rustc_errors::Applicability;
7use rustc_hir::attrs::AttributeKind;
8use rustc_hir::find_attr;
9use rustc_lexer::TokenKind;
10use rustc_lint::LateContext;
11use rustc_middle::ty::{AdtDef, TyCtxt};
12use rustc_session::Session;
13use rustc_span::{Span, Symbol};
14use std::str::FromStr;
15
16/// Given `attrs`, extract all the instances of a built-in Clippy attribute called `name`
17pub fn get_builtin_attr<'a, A: AttributeExt + 'a>(
18    sess: &'a Session,
19    attrs: &'a [A],
20    name: Symbol,
21) -> impl Iterator<Item = &'a A> {
22    attrs.iter().filter(move |attr| {
23        if let [clippy, segment2] = &*attr.path()
24            && *clippy == sym::clippy
25        {
26            let path_span = attr.path_span().expect("Clippy attributes are unparsed and have a span");
27            let new_name = match *segment2 {
28                sym::cyclomatic_complexity => Some("cognitive_complexity"),
29                sym::author
30                | sym::version
31                | sym::cognitive_complexity
32                | sym::dump
33                | sym::msrv
34                // The following attributes are for the 3rd party crate authors.
35                // See book/src/attribs.md
36                | sym::has_significant_drop
37                | sym::format_args => None,
38                _ => {
39                    sess.dcx().span_err(path_span, "usage of unknown attribute");
40                    return false;
41                },
42            };
43
44            match new_name {
45                Some(new_name) => {
46                    sess.dcx()
47                        .struct_span_err(path_span, "usage of deprecated attribute")
48                        .with_span_suggestion(
49                            path_span,
50                            "consider using",
51                            format!("clippy::{}", new_name),
52                            Applicability::MachineApplicable,
53                        )
54                        .emit();
55                    false
56                },
57                None => *segment2 == name,
58            }
59        } else {
60            false
61        }
62    })
63}
64
65/// If `attrs` contain exactly one instance of a built-in Clippy attribute called `name`,
66/// returns that attribute, and `None` otherwise
67pub fn get_unique_builtin_attr<'a, A: AttributeExt>(sess: &'a Session, attrs: &'a [A], name: Symbol) -> Option<&'a A> {
68    let mut unique_attr: Option<&A> = None;
69    for attr in get_builtin_attr(sess, attrs, name) {
70        if let Some(duplicate) = unique_attr {
71            sess.dcx()
72                .struct_span_err(attr.span(), format!("`{name}` is defined multiple times"))
73                .with_span_note(duplicate.span(), "first definition found here")
74                .emit();
75        } else {
76            unique_attr = Some(attr);
77        }
78    }
79    unique_attr
80}
81
82/// Checks whether `attrs` contain any of `proc_macro`, `proc_macro_derive` or
83/// `proc_macro_attribute`
84pub fn is_proc_macro(attrs: &[impl AttributeExt]) -> bool {
85    attrs.iter().any(AttributeExt::is_proc_macro_attr)
86}
87
88/// Checks whether `attrs` contain `#[doc(hidden)]`
89pub fn is_doc_hidden(attrs: &[impl AttributeExt]) -> bool {
90    attrs.iter().any(AttributeExt::is_doc_hidden)
91}
92
93/// Checks whether the given ADT, or any of its fields/variants, are marked as `#[non_exhaustive]`
94pub fn has_non_exhaustive_attr(tcx: TyCtxt<'_>, adt: AdtDef<'_>) -> bool {
95    adt.is_variant_list_non_exhaustive()
96        || find_attr!(tcx.get_all_attrs(adt.did()), AttributeKind::NonExhaustive(..))
97        || adt.variants().iter().any(|variant_def| {
98            variant_def.is_field_list_non_exhaustive()
99                || find_attr!(tcx.get_all_attrs(variant_def.def_id), AttributeKind::NonExhaustive(..))
100        })
101        || adt
102            .all_fields()
103            .any(|field_def| find_attr!(tcx.get_all_attrs(field_def.did), AttributeKind::NonExhaustive(..)))
104}
105
106/// Checks whether the given span contains a `#[cfg(..)]` attribute
107pub fn span_contains_cfg(cx: &LateContext<'_>, s: Span) -> bool {
108    s.check_source_text(cx, |src| {
109        let mut iter = tokenize_with_text(src);
110
111        // Search for the token sequence [`#`, `[`, `cfg`]
112        while iter.any(|(t, ..)| matches!(t, TokenKind::Pound)) {
113            let mut iter = iter.by_ref().skip_while(|(t, ..)| {
114                matches!(
115                    t,
116                    TokenKind::Whitespace | TokenKind::LineComment { .. } | TokenKind::BlockComment { .. }
117                )
118            });
119            if matches!(iter.next(), Some((TokenKind::OpenBracket, ..)))
120                && matches!(iter.next(), Some((TokenKind::Ident, "cfg", _)))
121            {
122                return true;
123            }
124        }
125        false
126    })
127}
128
129/// Currently used to keep track of the current value of `#[clippy::cognitive_complexity(N)]`
130pub struct LimitStack {
131    default: u64,
132    stack: Vec<u64>,
133}
134
135impl Drop for LimitStack {
136    fn drop(&mut self) {
137        debug_assert_eq!(self.stack, Vec::<u64>::new()); // avoid `.is_empty()`, for a nicer error message
138    }
139}
140
141#[expect(missing_docs, reason = "they're all trivial...")]
142impl LimitStack {
143    #[must_use]
144    /// Initialize the stack starting with a default value, which usually comes from configuration
145    pub fn new(limit: u64) -> Self {
146        Self {
147            default: limit,
148            stack: vec![],
149        }
150    }
151    pub fn limit(&self) -> u64 {
152        self.stack.last().copied().unwrap_or(self.default)
153    }
154    pub fn push_attrs(&mut self, sess: &Session, attrs: &[impl AttributeExt], name: Symbol) {
155        let stack = &mut self.stack;
156        parse_attrs(sess, attrs, name, |val| stack.push(val));
157    }
158    pub fn pop_attrs(&mut self, sess: &Session, attrs: &[impl AttributeExt], name: Symbol) {
159        let stack = &mut self.stack;
160        parse_attrs(sess, attrs, name, |val| debug_assert_eq!(stack.pop(), Some(val)));
161    }
162}
163
164fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[impl AttributeExt], name: Symbol, mut f: F) {
165    for attr in get_builtin_attr(sess, attrs, name) {
166        let Some(value) = attr.value_str() else {
167            sess.dcx().span_err(attr.span(), "bad clippy attribute");
168            continue;
169        };
170        let Ok(value) = u64::from_str(value.as_str()) else {
171            sess.dcx().span_err(attr.span(), "not a number");
172            continue;
173        };
174        f(value);
175    }
176}