Skip to main content

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