Skip to main content

clippy_utils/
attrs.rs

1//! Utility functions for attributes, including Clippy's built-in ones
2
3use crate::source::SpanExt as _;
4use crate::{sym, tokenize_with_text};
5use rustc_ast::AttrKind;
6use rustc_attr_ir::{AttrArgs, find_attr};
7use rustc_errors::Applicability;
8use rustc_hir::def_id::DefId;
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 as _;
15
16/// Validates a single clippy attribute and emits errors for unknown or deprecated ones.
17pub fn check_clippy_attr(sess: &Session, attr: &rustc_ast::ast::Attribute) {
18    let AttrKind::Normal(normal) = &attr.kind else { return };
19    let attr_item = &normal.item;
20    if let [clippy, segment2] = &*attr_item.path.segments
21        && clippy.ident.name == sym::clippy
22    {
23        let path_span = attr_item.path.span;
24
25        match segment2.ident.name {
26            sym::cyclomatic_complexity => {
27                sess.dcx()
28                    .struct_span_err(path_span, "usage of deprecated attribute")
29                    .with_span_suggestion(
30                        path_span,
31                        "consider using",
32                        "clippy::cognitive_complexity",
33                        Applicability::MachineApplicable,
34                    )
35                    .emit();
36            },
37            sym::author
38            | sym::version
39            | sym::cognitive_complexity
40            | sym::dump
41            | sym::msrv
42            | sym::has_significant_drop
43            | sym::may_panic
44            | sym::format_args => {},
45            _ => {
46                sess.dcx().span_err(path_span, "usage of unknown attribute");
47            },
48        }
49    }
50}
51
52/// Returns the first occurrence of `#[clippy::<name>]`.
53///
54/// Additionally, raises an error for duplicates of this attribute.
55pub fn get_clippy_attr(tcx: TyCtxt<'_>, did: impl Into<DefId>, name: Symbol) -> Option<&rustc_attr_ir::AttrItem> {
56    let attr_name = [sym::clippy, name];
57    let mut attrs = tcx.tool_attrs(did, &attr_name);
58    let first = attrs.next()?;
59
60    //FIXME(mejrs): this should really be checked during validation
61    for attr in attrs {
62        tcx.dcx()
63            .struct_span_err(attr.span, format!("`{name}` is defined multiple times"))
64            .with_span_note(first.span, "first definition found here")
65            .emit();
66    }
67
68    Some(first)
69}
70
71/// Checks whether `attrs` contain any of `proc_macro`, `proc_macro_derive` or
72/// `proc_macro_attribute`
73pub fn is_proc_macro(attrs: &[rustc_attr_ir::Attribute]) -> bool {
74    find_attr!(attrs, ProcMacro | ProcMacroAttribute | ProcMacroDerive { .. })
75}
76
77/// Checks whether `attrs` contain `#[doc(hidden)]`
78pub fn is_doc_hidden(attrs: &[rustc_attr_ir::Attribute]) -> bool {
79    find_attr!(attrs, Doc(rustc_attr_ir::DocAttribute { hidden: Some(_), .. }))
80}
81
82/// Checks whether the given ADT, or any of its fields/variants, are marked as `#[non_exhaustive]`
83pub fn has_non_exhaustive_attr(tcx: TyCtxt<'_>, adt: AdtDef<'_>) -> bool {
84    adt.is_variant_list_non_exhaustive()
85        || find_attr!(tcx, adt.did(), NonExhaustive(..))
86        || adt.variants().iter().any(|variant_def| {
87            variant_def.is_field_list_non_exhaustive() || find_attr!(tcx, variant_def.def_id, NonExhaustive(..))
88        })
89        || adt
90            .all_fields()
91            .any(|field_def| find_attr!(tcx, field_def.did, NonExhaustive(..)))
92}
93
94fn span_contains_attr_idents(cx: &LateContext<'_>, s: Span, idents: &[&str]) -> bool {
95    s.check_text(cx, |src| {
96        // PERF: Attributes need a literal `#`, so skip the lexer when the source has none.
97        if !src.contains('#') {
98            return false;
99        }
100
101        let mut iter = tokenize_with_text(src);
102
103        // Search for the token sequence [`#`, `[`, <ident>]
104        while iter.any(|(t, ..)| matches!(t, TokenKind::Pound)) {
105            let mut iter = iter.by_ref().skip_while(|(t, ..)| {
106                matches!(
107                    t,
108                    TokenKind::Whitespace | TokenKind::LineComment { .. } | TokenKind::BlockComment { .. }
109                )
110            });
111            if matches!(iter.next(), Some((TokenKind::OpenBracket, ..)))
112                && matches!(iter.next(), Some((TokenKind::Ident, name, _)) if idents.contains(&name))
113            {
114                return true;
115            }
116        }
117        false
118    })
119}
120
121/// Checks whether the given span contains a `#[cfg(..)]` attribute
122pub fn span_contains_cfg(cx: &LateContext<'_>, s: Span) -> bool {
123    span_contains_attr_idents(cx, s, &["cfg"])
124}
125
126/// Checks whether the given span contains a `#[cfg(..)]` or `#[cfg_attr(..)]` attribute
127pub fn span_contains_cfg_or_cfg_attr(cx: &LateContext<'_>, s: Span) -> bool {
128    span_contains_attr_idents(cx, s, &["cfg", "cfg_attr"])
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: &[rustc_attr_ir::Attribute], 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: &[rustc_attr_ir::Attribute], 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: &[rustc_attr_ir::Attribute], name: Symbol, mut f: F) {
170    let attrs = attrs.iter().filter_map(move |attr| {
171        if let rustc_attr_ir::Attribute::Tool { item, .. } = attr
172            && *item.path.segments == [sym::clippy, name]
173        {
174            Some(&**item)
175        } else {
176            None
177        }
178    });
179    for attr in attrs {
180        let AttrArgs::Eq { expr, .. } = attr.args else {
181            sess.dcx().span_err(attr.span, "bad clippy attribute");
182            continue;
183        };
184        let Some(value) = expr.value_as_str() else {
185            sess.dcx().span_err(attr.span, "not a number");
186            continue;
187        };
188        let Ok(value) = u64::from_str(value.as_str()) else {
189            sess.dcx().span_err(attr.span, "not a number");
190            continue;
191        };
192        f(value);
193    }
194}