Skip to main content

rustc_attr_parsing/attributes/
lint.rs

1use rustc_ast::join_path_syms;
2use rustc_attr_ir::AttributeKind;
3use rustc_attr_ir::lint::{LintCheck, LintCheckKind};
4use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
5use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES};
6use rustc_lint_defs::{CheckLintNameResult, LintId, LintName};
7use rustc_span::{Span, Symbol, sym};
8use thin_vec::ThinVec;
9
10use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability};
11use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext};
12use crate::diagnostics::{
13    DeprecatedLintName, MalformedLintAttributeInput, MalformedLintAttributeInputHelp, RemovedLint,
14    RenamedLint, RenamedLintSuggestion, UnknownLint, UnknownLintSuggestion,
15    UnknownToolInScopedLint,
16};
17use crate::parser::{ArgParser, MetaItemOrLitParser};
18use crate::target_checking::AllowedTargets;
19use crate::target_checking::Policy::{Allow, Warn};
20use crate::{AttributeTemplate, diagnostics, template};
21
22const LINT_TEMPLATE: AttributeTemplate = crate::AttributeTemplate {
    word: false,
    list: Some(&["lint1", "lint1, lint2, ...",
                    r#"lint1, lint2, lint3, reason = "...""#]),
    one_of: &[],
    name_value_str: None,
    docs: Some("https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"),
}template!(
23    List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
24    "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
25);
26
27#[derive(#[automatically_derived]impl ::core::default::Default for LintParser {
    #[inline]
    fn default() -> Self {
        LintParser { lints: ::core::default::Default::default() }
    }
}Default, #[automatically_derived]impl ::core::fmt::Debug for LintParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "LintParser lints", &&self.lints)
    }
}Debug)]
28pub(crate) struct LintParser {
29    lints: ThinVec<LintCheck>,
30}
31
32impl LintParser {
33    fn parse(&mut self, kind: LintCheckKind, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) {
34        let attr_span = cx.attr_span;
35        let attr_id = cx.attr_id.expect("no `AttrId` for lint attribute");
36        let mut has_invalid_reason_key = false;
37
38        if let Some(list) = cx.expect_list(args, cx.attr_span) {
39            let mut parsers = list.sub_parsers();
40            // Optionally, the last (and only the last)
41            // element can be `reason = "reason"`
42            let reason = try {
43                let p = parsers.last()?.meta_item()?;
44                let nv = p.args().as_name_value()?;
45                if !p.path().word_is(sym::reason) {
46                    has_invalid_reason_key = true;
47                    cx.emit_err(MalformedLintAttributeInput {
48                        span: p.span(),
49                        help: MalformedLintAttributeInputHelp::Reason {
50                            reason_span: p.path().span(),
51                        },
52                        kind: kind.sym(),
53                    });
54                }
55                parsers = &parsers[..(parsers.len() - 1)];
56                let reason = nv.expect_string_literal(cx)?;
57                reason
58            };
59
60            for item in parsers {
61                match item {
62                    MetaItemOrLitParser::MetaItemParser(p) => {
63                        match p.args() {
64                            ArgParser::NoArgs => {
65                                let (tool, lint_name) = match &*p.path().0.segments {
66                                    [] => ::core::panicking::unreachable_default_msg()unreachable!(),
67                                    [lint_name] => (None, lint_name.ident.name),
68                                    [tool, lint_name] => (Some(tool.ident), lint_name.ident.name),
69                                    // Not reachable for any builtin lints,
70                                    // but reachable using `register_tool`.
71                                    [tool, multi_segment_lint_name @ ..] => (
72                                        Some(tool.ident),
73                                        Symbol::intern(&join_path_syms(
74                                            multi_segment_lint_name
75                                                .iter()
76                                                .map(|seg| seg.ident.name),
77                                        )),
78                                    ),
79                                };
80                                let lint_name =
81                                    LintName { tool: tool.map(|tool| tool.name), name: lint_name };
82
83                                let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) =
84                                    LintParser::check_lint_name(
85                                        lint_name,
86                                        tool.map(|tool| tool.span),
87                                        p.span(),
88                                        cx,
89                                    ) {
90                                    new_lint_name
91                                } else {
92                                    // Discard lint attributes with unknown lints in them
93                                    continue;
94                                };
95
96                                self.lints.push(LintCheck {
97                                    lint_name_normalized,
98                                    lint_span: p.span(),
99                                    kind,
100                                    attr_id,
101                                    reason,
102                                    attr_span,
103                                })
104                            }
105                            // We've found a `reason = "reason"` but we're not the last element.
106                            ArgParser::NameValue(nv) if p.path().word_is(sym::reason) => {
107                                cx.emit_err(diagnostics::MalformedAttribute {
108                                    span: p.span(),
109                                    kind: diagnostics::MalformedAttributeKind::ReasonMustComeLast(
110                                        item.span(),
111                                    ),
112                                });
113                                nv.expect_string_literal(cx);
114                            }
115                            ArgParser::NameValue(_) | ArgParser::List(_) => {
116                                cx.emit_err(MalformedLintAttributeInput {
117                                    span: p.span(),
118                                    help: MalformedLintAttributeInputHelp::Other {
119                                        kind: kind.sym(),
120                                    },
121                                    kind: kind.sym(),
122                                });
123                            }
124                        }
125                    }
126                    MetaItemOrLitParser::Lit(lit) => {
127                        cx.emit_err(MalformedLintAttributeInput {
128                            span: item.span(),
129                            help: if lit.kind.is_str() {
130                                MalformedLintAttributeInputHelp::StrLit {
131                                    sym: lit.symbol,
132                                    kind: kind.sym(),
133                                }
134                            } else {
135                                MalformedLintAttributeInputHelp::Other { kind: kind.sym() }
136                            },
137                            kind: kind.sym(),
138                        });
139                    }
140                }
141            }
142
143            // FIXME(164898) Lint attributes are unique because they're parsed twice with `ShouldEmit::ErrorsAndLints`
144            // To avoid emitting the lint twice, we check `cx.parse_filter`, which will be `Some` during AST linting
145            if parsers.is_empty() && cx.parse_filter.is_none() && !has_invalid_reason_key {
146                cx.emit_lint(
147                    UNUSED_ATTRIBUTES,
148                    diagnostics::Unused {
149                        attr_span,
150                        note: if list.is_empty() {
151                            diagnostics::UnusedNote::EmptyList { name: kind.sym() }
152                        } else {
153                            diagnostics::UnusedNote::NoLints { name: kind.sym() }
154                        },
155                    },
156                    attr_span,
157                );
158            }
159        }
160    }
161
162    fn check_lint_name<'sess>(
163        lint_name: LintName,
164        tool_span: Option<Span>,
165        lint_span: Span,
166        cx: &mut AcceptContext<'_, 'sess>,
167    ) -> Option<(&'sess [LintId], LintName)> {
168        let lint_result = cx
169            .sess
170            .lint_store
171            .as_ref()
172            .unwrap()
173            .check_attribute_lint_name(lint_name, cx.lint_tools.unwrap());
174
175        // FIXME(164898) Lint attributes are parsed twice, once on the AST and once on the HIR
176        // Both times emit diagnostics, for historic reasons
177        // We only want to emit these lints once, on the HIR.
178        // On the AST the parse filter will be `Some` (since we're only parsing lint attributes then)
179        // #164898 will fix this, after that PR this check can be removed
180        let should_lint = cx.parse_filter.is_none();
181
182        let (ids, name) = match lint_result {
183            CheckLintNameResult::Ok(ids) => (ids, lint_name),
184
185            CheckLintNameResult::Tool(ids, new_lint_name) => {
186                let name = match new_lint_name {
187                    None => lint_name,
188                    Some(replacement) => {
189                        if should_lint {
190                            cx.emit_lint(
191                                RENAMED_AND_REMOVED_LINTS,
192                                DeprecatedLintName {
193                                    lint_name,
194                                    suggestion: lint_span,
195                                    replacement,
196                                },
197                                lint_span,
198                            );
199                        }
200                        replacement
201                    }
202                };
203                (ids, name)
204            }
205
206            CheckLintNameResult::MissingTool => {
207                // If `MissingTool` is returned, then either the lint does not
208                // exist in the tool or the code was not compiled with the tool and
209                // therefore the lint was never added to the `LintStore`. To detect
210                // this is the responsibility of the lint tool.
211                return None;
212            }
213
214            CheckLintNameResult::NoTool(tool_name) => {
215                if should_lint {
216                    cx.emit_err(UnknownToolInScopedLint {
217                        span: Some(tool_span.unwrap()),
218                        tool_name,
219                        lint_name,
220                        is_nightly_build: cx.sess.is_nightly_build(),
221                    });
222                }
223                return None;
224            }
225
226            CheckLintNameResult::Renamed(replacement) => {
227                if should_lint {
228                    let suggestion =
229                        RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement };
230                    cx.emit_lint(
231                        RENAMED_AND_REMOVED_LINTS,
232                        RenamedLint { name: lint_name, replacement, suggestion },
233                        lint_span,
234                    );
235                }
236
237                // If this lint was renamed, apply the new lint instead of ignoring the
238                // attribute. Ignore any errors or warnings that happen because the new
239                // name is inaccurate.
240                let replace_check = cx
241                    .sess
242                    .lint_store
243                    .as_ref()
244                    .unwrap()
245                    .check_attribute_lint_name(replacement, cx.lint_tools.unwrap());
246                let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) =
247                    replace_check
248                else {
249                    {
    ::core::panicking::panic_fmt(format_args!("renamed lint does not exist: {0} => {1}\n{2:?}",
            lint_name, replacement, replace_check));
};panic!(
250                        "renamed lint does not exist: {lint_name} => {replacement}\n{replace_check:?}"
251                    );
252                };
253
254                (ids, replacement)
255            }
256
257            CheckLintNameResult::Removed(reason) => {
258                if should_lint {
259                    cx.emit_lint(
260                        RENAMED_AND_REMOVED_LINTS,
261                        RemovedLint { name: lint_name, reason },
262                        lint_span,
263                    );
264                }
265                return None;
266            }
267
268            CheckLintNameResult::NoLint(suggestion) => {
269                if should_lint {
270                    let suggestion = suggestion.map(|(replacement, from_rustc)| {
271                        UnknownLintSuggestion::WithSpan {
272                            suggestion: lint_span,
273                            replacement,
274                            from_rustc,
275                        }
276                    });
277                    cx.emit_lint(
278                        UNKNOWN_LINTS,
279                        UnknownLint { name: lint_name, suggestion },
280                        lint_span,
281                    );
282                }
283                return None;
284            }
285        };
286        Some((ids, name))
287    }
288}
289
290impl AttributeParser for LintParser {
291    const ATTRIBUTES: AcceptMapping<Self> = &[
292        (&[sym::allow], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
293            this.parse(LintCheckKind::Allow, cx, args)
294        }),
295        (&[sym::warn], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
296            this.parse(LintCheckKind::Warn, cx, args)
297        }),
298        (&[sym::deny], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
299            this.parse(LintCheckKind::Deny, cx, args)
300        }),
301        (&[sym::forbid], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
302            this.parse(LintCheckKind::Forbid, cx, args)
303        }),
304        (&[sym::expect], LINT_TEMPLATE, AttributeStability::Stable, |this, cx, args| {
305            this.parse(LintCheckKind::Expect, cx, args)
306        }),
307    ];
308    const ALLOWED_TARGETS: AllowedTargets<'_> = {
309        AllowedTargets::AllowList(&[
310            Allow(Target::ExternCrate),
311            Allow(Target::Use),
312            Allow(Target::Static),
313            Allow(Target::Const),
314            Allow(Target::Fn),
315            Allow(Target::Closure),
316            Allow(Target::Mod),
317            Allow(Target::ForeignMod),
318            Allow(Target::GlobalAsm),
319            Allow(Target::TyAlias),
320            Allow(Target::Enum),
321            Allow(Target::Variant),
322            Allow(Target::Struct),
323            Allow(Target::Field),
324            Allow(Target::Union),
325            Allow(Target::Trait),
326            Allow(Target::TraitAlias),
327            Allow(Target::Impl { of_trait: false }),
328            Allow(Target::Impl { of_trait: true }),
329            Allow(Target::Expression),
330            Allow(Target::Statement),
331            Allow(Target::Arm),
332            Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
333            Allow(Target::AssocConst(AssocCtxt::Trait)),
334            Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
335            Allow(Target::Method(MethodKind::Inherent)),
336            Allow(Target::Method(MethodKind::Trait { body: false })),
337            Allow(Target::Method(MethodKind::Trait { body: true })),
338            Allow(Target::Method(MethodKind::TraitImpl)),
339            Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })),
340            Allow(Target::AssocTy(AssocCtxt::Trait)),
341            Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })),
342            Allow(Target::ForeignFn),
343            Allow(Target::ForeignStatic),
344            Allow(Target::ForeignTy),
345            Allow(Target::MacroDef),
346            Allow(Target::Param),
347            Allow(Target::PatField),
348            Allow(Target::ExprField),
349            Allow(Target::Crate),
350            Allow(Target::Delegation { mac: false }),
351            Allow(Target::Delegation { mac: true }),
352            Allow(Target::ConstParam),
353            Allow(Target::LifetimeParam),
354            Allow(Target::TypeParam),
355            Allow(Target::Loop),
356            Allow(Target::ForLoop),
357            Allow(Target::While),
358            Allow(Target::Break),
359            Warn(Target::MacroCall),
360        ])
361    };
362    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
363        if self.lints.is_empty() { None } else { Some(AttributeKind::LintCheck(self.lints)) }
364    }
365}