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::attr::AttributeExt;
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    if let [clippy, segment2] = &*attr.path()
19        && *clippy == sym::clippy
20    {
21        let path_span = attr
22            .path_span()
23            .expect("Clippy attributes are tool attributes, so they have a span");
24
25        match *segment2 {
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::format_args => {},
44            _ => {
45                sess.dcx().span_err(path_span, "usage of unknown attribute");
46            },
47        }
48    }
49}
50
51/// Retrieves the span of a Clippy attribute, such as `#[clippy::format_args]`.
52///
53/// Panics if used on an attribute that isn't a tool attribute, so always check
54/// for that first with e.g. `path` or `path_matches`.
55pub fn span_of_clippy_attr(attr: &(impl AttributeExt + 'static)) -> Span {
56    let a: &dyn core::any::Any = attr;
57    if let Some(a) = a.downcast_ref::<rustc_ast::ast::Attribute>() {
58        a.span
59    } else if let Some(rustc_attr_ir::Attribute::Tool(u)) = a.downcast_ref::<rustc_attr_ir::Attribute>() {
60        u.span
61    } else {
62        panic!("attribute {attr:?} is not a clippy attribute")
63    }
64}
65
66/// Returns the first occurrence of `#[clippy::<name>]`.
67///
68/// Additionally, raises an error for duplicates of this attribute.
69pub fn get_clippy_attr(tcx: TyCtxt<'_>, did: impl Into<DefId>, name: Symbol) -> Option<&rustc_attr_ir::AttrItem> {
70    let attr_name = [sym::clippy, name];
71    let mut attrs = tcx.tool_attrs(did, &attr_name);
72    let first = attrs.next()?;
73
74    //FIXME(mejrs): this should really be checked during validation
75    for attr in attrs {
76        tcx.dcx()
77            .struct_span_err(attr.span, format!("`{name}` is defined multiple times"))
78            .with_span_note(first.span, "first definition found here")
79            .emit();
80    }
81
82    Some(first)
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: &[rustc_attr_ir::Attribute]) -> bool {
88    find_attr!(
89        attrs,
90        ProcMacro
91        | ProcMacroAttribute
92        | ProcMacroDerive { .. }
93    )
94}
95
96/// Checks whether `attrs` contain `#[doc(hidden)]`
97pub fn is_doc_hidden(attrs: &[rustc_attr_ir::Attribute]) -> bool {
98    find_attr!(attrs, Doc(rustc_attr_ir::DocAttribute { hidden: Some(_), .. }))
99}
100
101/// Checks whether the given ADT, or any of its fields/variants, are marked as `#[non_exhaustive]`
102pub fn has_non_exhaustive_attr(tcx: TyCtxt<'_>, adt: AdtDef<'_>) -> bool {
103    adt.is_variant_list_non_exhaustive()
104        || find_attr!(tcx, adt.did(), NonExhaustive(..))
105        || adt.variants().iter().any(|variant_def| {
106            variant_def.is_field_list_non_exhaustive() || find_attr!(tcx, variant_def.def_id, NonExhaustive(..))
107        })
108        || adt
109            .all_fields()
110            .any(|field_def| find_attr!(tcx, field_def.did, NonExhaustive(..)))
111}
112
113fn span_contains_attr_idents(cx: &LateContext<'_>, s: Span, idents: &[&str]) -> bool {
114    s.check_text(cx, |src| {
115        // PERF: Attributes need a literal `#`, so skip the lexer when the source has none.
116        if !src.contains('#') {
117            return false;
118        }
119
120        let mut iter = tokenize_with_text(src);
121
122        // Search for the token sequence [`#`, `[`, <ident>]
123        while iter.any(|(t, ..)| matches!(t, TokenKind::Pound)) {
124            let mut iter = iter.by_ref().skip_while(|(t, ..)| {
125                matches!(
126                    t,
127                    TokenKind::Whitespace | TokenKind::LineComment { .. } | TokenKind::BlockComment { .. }
128                )
129            });
130            if matches!(iter.next(), Some((TokenKind::OpenBracket, ..)))
131                && matches!(iter.next(), Some((TokenKind::Ident, name, _)) if idents.contains(&name))
132            {
133                return true;
134            }
135        }
136        false
137    })
138}
139
140/// Checks whether the given span contains a `#[cfg(..)]` attribute
141pub fn span_contains_cfg(cx: &LateContext<'_>, s: Span) -> bool {
142    span_contains_attr_idents(cx, s, &["cfg"])
143}
144
145/// Checks whether the given span contains a `#[cfg(..)]` or `#[cfg_attr(..)]` attribute
146pub fn span_contains_cfg_or_cfg_attr(cx: &LateContext<'_>, s: Span) -> bool {
147    span_contains_attr_idents(cx, s, &["cfg", "cfg_attr"])
148}
149
150/// Currently used to keep track of the current value of `#[clippy::cognitive_complexity(N)]`
151pub struct LimitStack {
152    default: u64,
153    stack: Vec<u64>,
154}
155
156impl Drop for LimitStack {
157    fn drop(&mut self) {
158        debug_assert_eq!(self.stack, Vec::<u64>::new()); // avoid `.is_empty()`, for a nicer error message
159    }
160}
161
162#[expect(missing_docs, reason = "they're all trivial...")]
163impl LimitStack {
164    #[must_use]
165    /// Initialize the stack starting with a default value, which usually comes from configuration
166    pub fn new(limit: u64) -> Self {
167        Self {
168            default: limit,
169            stack: vec![],
170        }
171    }
172    pub fn limit(&self) -> u64 {
173        self.stack.last().copied().unwrap_or(self.default)
174    }
175    pub fn push_attrs(&mut self, sess: &Session, attrs: &[rustc_attr_ir::Attribute], name: Symbol) {
176        let stack = &mut self.stack;
177        parse_attrs(sess, attrs, name, |val| stack.push(val));
178    }
179    pub fn pop_attrs(&mut self, sess: &Session, attrs: &[rustc_attr_ir::Attribute], name: Symbol) {
180        let stack = &mut self.stack;
181        parse_attrs(sess, attrs, name, |val| {
182            let popped = stack.pop();
183            debug_assert_eq!(popped, Some(val));
184        });
185    }
186}
187
188fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[rustc_attr_ir::Attribute], name: Symbol, mut f: F) {
189    let attrs = attrs.iter().filter_map(move |attr| {
190        if let rustc_attr_ir::Attribute::Tool(t) = attr
191            && *t.path.segments == [sym::clippy, name]
192        {
193            Some(&**t)
194        } else {
195            None
196        }
197    });
198    for attr in attrs {
199        let AttrArgs::Eq { expr, .. } = attr.args else {
200            sess.dcx().span_err(attr.span, "bad clippy attribute");
201            continue;
202        };
203        let Some(value) = expr.value_as_str() else {
204            sess.dcx().span_err(attr.span, "not a number");
205            continue;
206        };
207        let Ok(value) = u64::from_str(value.as_str()) else {
208            sess.dcx().span_err(attr.span, "not a number");
209            continue;
210        };
211        f(value);
212    }
213}