rustc_lint/
levels.rs

1use rustc_ast::attr::AttributeExt;
2use rustc_ast_pretty::pprust;
3use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
4use rustc_errors::{Diag, LintDiagnostic, MultiSpan};
5use rustc_feature::{Features, GateIssue};
6use rustc_hir::intravisit::{self, Visitor};
7use rustc_hir::{CRATE_HIR_ID, HirId};
8use rustc_index::IndexVec;
9use rustc_middle::bug;
10use rustc_middle::hir::nested_filter;
11use rustc_middle::lint::{
12    LevelAndSource, LintExpectation, LintLevelSource, ShallowLintLevelMap, lint_level,
13    reveal_actual_level,
14};
15use rustc_middle::query::Providers;
16use rustc_middle::ty::{RegisteredTools, TyCtxt};
17use rustc_session::Session;
18use rustc_session::lint::builtin::{
19    self, FORBIDDEN_LINT_GROUPS, RENAMED_AND_REMOVED_LINTS, SINGLE_USE_LIFETIMES,
20    UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES,
21};
22use rustc_session::lint::{Level, Lint, LintExpectationId, LintId};
23use rustc_span::{DUMMY_SP, Span, Symbol, sym};
24use tracing::{debug, instrument};
25use {rustc_ast as ast, rustc_hir as hir};
26
27use crate::builtin::MISSING_DOCS;
28use crate::context::{CheckLintNameResult, LintStore};
29use crate::errors::{
30    CheckNameUnknownTool, MalformedAttribute, MalformedAttributeSub, OverruledAttribute,
31    OverruledAttributeSub, RequestedLevel, UnknownToolInScopedLint, UnsupportedGroup,
32};
33use crate::fluent_generated as fluent;
34use crate::late::unerased_lint_store;
35use crate::lints::{
36    DeprecatedLintName, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified,
37    OverruledAttributeLint, RemovedLint, RemovedLintFromCommandLine, RenamedLint,
38    RenamedLintFromCommandLine, RenamedLintSuggestion, UnknownLint, UnknownLintFromCommandLine,
39    UnknownLintSuggestion,
40};
41
42/// Collection of lint levels for the whole crate.
43/// This is used by AST-based lints, which do not
44/// wait until we have built HIR to be emitted.
45#[derive(Debug)]
46struct LintLevelSets {
47    /// Linked list of specifications.
48    list: IndexVec<LintStackIndex, LintSet>,
49}
50
51rustc_index::newtype_index! {
52    struct LintStackIndex {
53        const COMMAND_LINE = 0;
54    }
55}
56
57/// Specifications found at this position in the stack. This map only represents the lints
58/// found for one set of attributes (like `shallow_lint_levels_on` does).
59///
60/// We store the level specifications as a linked list.
61/// Each `LintSet` represents a set of attributes on the same AST node.
62/// The `parent` forms a linked list that matches the AST tree.
63/// This way, walking the linked list is equivalent to walking the AST bottom-up
64/// to find the specifications for a given lint.
65#[derive(Debug)]
66struct LintSet {
67    // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
68    // flag.
69    specs: FxIndexMap<LintId, LevelAndSource>,
70    parent: LintStackIndex,
71}
72
73impl LintLevelSets {
74    fn new() -> Self {
75        LintLevelSets { list: IndexVec::new() }
76    }
77
78    fn get_lint_level(
79        &self,
80        lint: &'static Lint,
81        idx: LintStackIndex,
82        aux: Option<&FxIndexMap<LintId, LevelAndSource>>,
83        sess: &Session,
84    ) -> LevelAndSource {
85        let lint = LintId::of(lint);
86        let (level, mut src) = self.raw_lint_id_level(lint, idx, aux);
87        let level = reveal_actual_level(level, &mut src, sess, lint, |id| {
88            self.raw_lint_id_level(id, idx, aux)
89        });
90        (level, src)
91    }
92
93    fn raw_lint_id_level(
94        &self,
95        id: LintId,
96        mut idx: LintStackIndex,
97        aux: Option<&FxIndexMap<LintId, LevelAndSource>>,
98    ) -> (Option<Level>, LintLevelSource) {
99        if let Some(specs) = aux
100            && let Some(&(level, src)) = specs.get(&id)
101        {
102            return (Some(level), src);
103        }
104
105        loop {
106            let LintSet { ref specs, parent } = self.list[idx];
107            if let Some(&(level, src)) = specs.get(&id) {
108                return (Some(level), src);
109            }
110            if idx == COMMAND_LINE {
111                return (None, LintLevelSource::Default);
112            }
113            idx = parent;
114        }
115    }
116}
117
118fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LintId> {
119    let store = unerased_lint_store(&tcx.sess);
120
121    let map = tcx.shallow_lint_levels_on(rustc_hir::CRATE_OWNER_ID);
122
123    let dont_need_to_run: FxIndexSet<LintId> = store
124        .get_lints()
125        .into_iter()
126        .filter(|lint| {
127            // Lints that show up in future-compat reports must always be run.
128            let has_future_breakage =
129                lint.future_incompatible.is_some_and(|fut| fut.reason.has_future_breakage());
130            !has_future_breakage && !lint.eval_always
131        })
132        .filter_map(|lint| {
133            let lint_level = map.lint_level_id_at_node(tcx, LintId::of(lint), CRATE_HIR_ID);
134            if matches!(lint_level, (Level::Allow, ..))
135                || (matches!(lint_level, (.., LintLevelSource::Default)))
136                    && lint.default_level(tcx.sess.edition()) == Level::Allow
137            {
138                Some(LintId::of(lint))
139            } else {
140                None
141            }
142        })
143        .collect();
144
145    let mut visitor = LintLevelMaximum { tcx, dont_need_to_run };
146    visitor.process_opts();
147    tcx.hir().walk_attributes(&mut visitor);
148
149    visitor.dont_need_to_run
150}
151
152#[instrument(level = "trace", skip(tcx), ret)]
153fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLevelMap {
154    let store = unerased_lint_store(tcx.sess);
155    let attrs = tcx.hir_attrs(owner);
156
157    let mut levels = LintLevelsBuilder {
158        sess: tcx.sess,
159        features: tcx.features(),
160        provider: LintLevelQueryMap {
161            tcx,
162            cur: owner.into(),
163            specs: ShallowLintLevelMap::default(),
164            empty: FxIndexMap::default(),
165            attrs,
166        },
167        lint_added_lints: false,
168        store,
169        registered_tools: tcx.registered_tools(()),
170    };
171
172    if owner == hir::CRATE_OWNER_ID {
173        levels.add_command_line();
174    }
175
176    match attrs.map.range(..) {
177        // There is only something to do if there are attributes at all.
178        [] => {}
179        // Most of the time, there is only one attribute. Avoid fetching HIR in that case.
180        &[(local_id, _)] => levels.add_id(HirId { owner, local_id }),
181        // Otherwise, we need to visit the attributes in source code order, so we fetch HIR and do
182        // a standard visit.
183        // FIXME(#102522) Just iterate on attrs once that iteration order matches HIR's.
184        _ => match tcx.hir_owner_node(owner) {
185            hir::OwnerNode::Item(item) => levels.visit_item(item),
186            hir::OwnerNode::ForeignItem(item) => levels.visit_foreign_item(item),
187            hir::OwnerNode::TraitItem(item) => levels.visit_trait_item(item),
188            hir::OwnerNode::ImplItem(item) => levels.visit_impl_item(item),
189            hir::OwnerNode::Crate(mod_) => {
190                levels.add_id(hir::CRATE_HIR_ID);
191                levels.visit_mod(mod_, mod_.spans.inner_span, hir::CRATE_HIR_ID)
192            }
193            hir::OwnerNode::Synthetic => unreachable!(),
194        },
195    }
196
197    let specs = levels.provider.specs;
198
199    #[cfg(debug_assertions)]
200    for (_, v) in specs.specs.iter() {
201        debug_assert!(!v.is_empty());
202    }
203
204    specs
205}
206
207pub struct TopDown {
208    sets: LintLevelSets,
209    cur: LintStackIndex,
210}
211
212pub trait LintLevelsProvider {
213    fn current_specs(&self) -> &FxIndexMap<LintId, LevelAndSource>;
214    fn insert(&mut self, id: LintId, lvl: LevelAndSource);
215    fn get_lint_level(&self, lint: &'static Lint, sess: &Session) -> LevelAndSource;
216    fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation);
217}
218
219impl LintLevelsProvider for TopDown {
220    fn current_specs(&self) -> &FxIndexMap<LintId, LevelAndSource> {
221        &self.sets.list[self.cur].specs
222    }
223
224    fn insert(&mut self, id: LintId, lvl: LevelAndSource) {
225        self.sets.list[self.cur].specs.insert(id, lvl);
226    }
227
228    fn get_lint_level(&self, lint: &'static Lint, sess: &Session) -> LevelAndSource {
229        self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), sess)
230    }
231
232    fn push_expectation(&mut self, _: LintExpectationId, _: LintExpectation) {}
233}
234
235struct LintLevelQueryMap<'tcx> {
236    tcx: TyCtxt<'tcx>,
237    cur: HirId,
238    specs: ShallowLintLevelMap,
239    /// Empty hash map to simplify code.
240    empty: FxIndexMap<LintId, LevelAndSource>,
241    attrs: &'tcx hir::AttributeMap<'tcx>,
242}
243
244impl LintLevelsProvider for LintLevelQueryMap<'_> {
245    fn current_specs(&self) -> &FxIndexMap<LintId, LevelAndSource> {
246        self.specs.specs.get(&self.cur.local_id).unwrap_or(&self.empty)
247    }
248    fn insert(&mut self, id: LintId, lvl: LevelAndSource) {
249        self.specs.specs.get_mut_or_insert_default(self.cur.local_id).insert(id, lvl);
250    }
251    fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource {
252        self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur)
253    }
254    fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) {
255        self.specs.expectations.push((id, expectation))
256    }
257}
258
259impl<'tcx> LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> {
260    fn add_id(&mut self, hir_id: HirId) {
261        self.provider.cur = hir_id;
262        self.add(
263            self.provider.attrs.get(hir_id.local_id),
264            hir_id == hir::CRATE_HIR_ID,
265            Some(hir_id),
266        );
267    }
268}
269
270impl<'tcx> Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> {
271    type NestedFilter = nested_filter::OnlyBodies;
272
273    fn nested_visit_map(&mut self) -> Self::Map {
274        self.provider.tcx.hir()
275    }
276
277    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
278        self.add_id(param.hir_id);
279        intravisit::walk_param(self, param);
280    }
281
282    fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
283        self.add_id(it.hir_id());
284        intravisit::walk_item(self, it);
285    }
286
287    fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
288        self.add_id(it.hir_id());
289        intravisit::walk_foreign_item(self, it);
290    }
291
292    fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
293        self.add_id(s.hir_id);
294        intravisit::walk_stmt(self, s);
295    }
296
297    fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
298        self.add_id(e.hir_id);
299        intravisit::walk_expr(self, e);
300    }
301
302    fn visit_expr_field(&mut self, f: &'tcx hir::ExprField<'tcx>) {
303        self.add_id(f.hir_id);
304        intravisit::walk_expr_field(self, f);
305    }
306
307    fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
308        self.add_id(s.hir_id);
309        intravisit::walk_field_def(self, s);
310    }
311
312    fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
313        self.add_id(v.hir_id);
314        intravisit::walk_variant(self, v);
315    }
316
317    fn visit_local(&mut self, l: &'tcx hir::LetStmt<'tcx>) {
318        self.add_id(l.hir_id);
319        intravisit::walk_local(self, l);
320    }
321
322    fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
323        self.add_id(a.hir_id);
324        intravisit::walk_arm(self, a);
325    }
326
327    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
328        self.add_id(trait_item.hir_id());
329        intravisit::walk_trait_item(self, trait_item);
330    }
331
332    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
333        self.add_id(impl_item.hir_id());
334        intravisit::walk_impl_item(self, impl_item);
335    }
336}
337
338/// Visitor with the only function of visiting every item-like in a crate and
339/// computing the highest level that every lint gets put to.
340///
341/// E.g., if a crate has a global #![allow(lint)] attribute, but a single item
342/// uses #[warn(lint)], this visitor will set that lint level as `Warn`
343struct LintLevelMaximum<'tcx> {
344    tcx: TyCtxt<'tcx>,
345    /// The actual list of detected lints.
346    dont_need_to_run: FxIndexSet<LintId>,
347}
348
349impl<'tcx> LintLevelMaximum<'tcx> {
350    fn process_opts(&mut self) {
351        let store = unerased_lint_store(self.tcx.sess);
352        for (lint_group, level) in &self.tcx.sess.opts.lint_opts {
353            if *level != Level::Allow {
354                let Ok(lints) = store.find_lints(lint_group) else {
355                    return;
356                };
357                for lint in lints {
358                    self.dont_need_to_run.swap_remove(&lint);
359                }
360            }
361        }
362    }
363}
364
365impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> {
366    type NestedFilter = nested_filter::All;
367
368    fn nested_visit_map(&mut self) -> Self::Map {
369        self.tcx.hir()
370    }
371
372    /// FIXME(blyxyas): In a future revision, we should also graph #![allow]s,
373    /// but that is handled with more care
374    fn visit_attribute(&mut self, attribute: &'tcx hir::Attribute) {
375        if matches!(
376            Level::from_attr(attribute),
377            Some(
378                Level::Warn
379                    | Level::Deny
380                    | Level::Forbid
381                    | Level::Expect(..)
382                    | Level::ForceWarn(..),
383            )
384        ) {
385            let store = unerased_lint_store(self.tcx.sess);
386            // Lint attributes are always a metalist inside a
387            // metalist (even with just one lint).
388            let Some(meta_item_list) = attribute.meta_item_list() else { return };
389
390            for meta_list in meta_item_list {
391                // Convert Path to String
392                let Some(meta_item) = meta_list.meta_item() else { return };
393                let ident: &str = &meta_item
394                    .path
395                    .segments
396                    .iter()
397                    .map(|segment| segment.ident.as_str())
398                    .collect::<Vec<&str>>()
399                    .join("::");
400                let Ok(lints) = store.find_lints(
401                    // Lint attributes can only have literals
402                    ident,
403                ) else {
404                    return;
405                };
406                for lint in lints {
407                    self.dont_need_to_run.swap_remove(&lint);
408                }
409            }
410        }
411    }
412}
413
414pub struct LintLevelsBuilder<'s, P> {
415    sess: &'s Session,
416    features: &'s Features,
417    provider: P,
418    lint_added_lints: bool,
419    store: &'s LintStore,
420    registered_tools: &'s RegisteredTools,
421}
422
423pub(crate) struct BuilderPush {
424    prev: LintStackIndex,
425}
426
427impl<'s> LintLevelsBuilder<'s, TopDown> {
428    pub(crate) fn new(
429        sess: &'s Session,
430        features: &'s Features,
431        lint_added_lints: bool,
432        store: &'s LintStore,
433        registered_tools: &'s RegisteredTools,
434    ) -> Self {
435        let mut builder = LintLevelsBuilder {
436            sess,
437            features,
438            provider: TopDown { sets: LintLevelSets::new(), cur: COMMAND_LINE },
439            lint_added_lints,
440            store,
441            registered_tools,
442        };
443        builder.process_command_line();
444        assert_eq!(builder.provider.sets.list.len(), 1);
445        builder
446    }
447
448    fn process_command_line(&mut self) {
449        self.provider.cur = self
450            .provider
451            .sets
452            .list
453            .push(LintSet { specs: FxIndexMap::default(), parent: COMMAND_LINE });
454        self.add_command_line();
455    }
456
457    /// Pushes a list of AST lint attributes onto this context.
458    ///
459    /// This function will return a `BuilderPush` object which should be passed
460    /// to `pop` when this scope for the attributes provided is exited.
461    ///
462    /// This function will perform a number of tasks:
463    ///
464    /// * It'll validate all lint-related attributes in `attrs`
465    /// * It'll mark all lint-related attributes as used
466    /// * Lint levels will be updated based on the attributes provided
467    /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
468    ///   `#[allow]`
469    ///
470    /// Don't forget to call `pop`!
471    pub(crate) fn push(
472        &mut self,
473        attrs: &[ast::Attribute],
474        is_crate_node: bool,
475        source_hir_id: Option<HirId>,
476    ) -> BuilderPush {
477        let prev = self.provider.cur;
478        self.provider.cur =
479            self.provider.sets.list.push(LintSet { specs: FxIndexMap::default(), parent: prev });
480
481        self.add(attrs, is_crate_node, source_hir_id);
482
483        if self.provider.current_specs().is_empty() {
484            self.provider.sets.list.pop();
485            self.provider.cur = prev;
486        }
487
488        BuilderPush { prev }
489    }
490
491    /// Called after `push` when the scope of a set of attributes are exited.
492    pub(crate) fn pop(&mut self, push: BuilderPush) {
493        self.provider.cur = push.prev;
494        std::mem::forget(push);
495    }
496}
497
498#[cfg(debug_assertions)]
499impl Drop for BuilderPush {
500    fn drop(&mut self) {
501        panic!("Found a `push` without a `pop`.");
502    }
503}
504
505impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
506    pub(crate) fn sess(&self) -> &Session {
507        self.sess
508    }
509
510    pub(crate) fn features(&self) -> &Features {
511        self.features
512    }
513
514    fn current_specs(&self) -> &FxIndexMap<LintId, LevelAndSource> {
515        self.provider.current_specs()
516    }
517
518    fn insert(&mut self, id: LintId, lvl: LevelAndSource) {
519        self.provider.insert(id, lvl)
520    }
521
522    fn add_command_line(&mut self) {
523        for &(ref lint_name, level) in &self.sess.opts.lint_opts {
524            // Checks the validity of lint names derived from the command line.
525            let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
526            if lint_name_only == crate::WARNINGS.name_lower()
527                && matches!(level, Level::ForceWarn(_))
528            {
529                self.sess
530                    .dcx()
531                    .emit_err(UnsupportedGroup { lint_group: crate::WARNINGS.name_lower() });
532            }
533            match self.store.check_lint_name(lint_name_only, tool_name, self.registered_tools) {
534                CheckLintNameResult::Renamed(ref replace) => {
535                    let name = lint_name.as_str();
536                    let suggestion = RenamedLintSuggestion::WithoutSpan { replace };
537                    let requested_level = RequestedLevel { level, lint_name };
538                    let lint = RenamedLintFromCommandLine { name, suggestion, requested_level };
539                    self.emit_lint(RENAMED_AND_REMOVED_LINTS, lint);
540                }
541                CheckLintNameResult::Removed(ref reason) => {
542                    let name = lint_name.as_str();
543                    let requested_level = RequestedLevel { level, lint_name };
544                    let lint = RemovedLintFromCommandLine { name, reason, requested_level };
545                    self.emit_lint(RENAMED_AND_REMOVED_LINTS, lint);
546                }
547                CheckLintNameResult::NoLint(suggestion) => {
548                    let name = lint_name.clone();
549                    let suggestion = suggestion.map(|(replace, from_rustc)| {
550                        UnknownLintSuggestion::WithoutSpan { replace, from_rustc }
551                    });
552                    let requested_level = RequestedLevel { level, lint_name };
553                    let lint = UnknownLintFromCommandLine { name, suggestion, requested_level };
554                    self.emit_lint(UNKNOWN_LINTS, lint);
555                }
556                CheckLintNameResult::Tool(_, Some(ref replace)) => {
557                    let name = lint_name.clone();
558                    let requested_level = RequestedLevel { level, lint_name };
559                    let lint = DeprecatedLintNameFromCommandLine { name, replace, requested_level };
560                    self.emit_lint(RENAMED_AND_REMOVED_LINTS, lint);
561                }
562                CheckLintNameResult::NoTool => {
563                    self.sess.dcx().emit_err(CheckNameUnknownTool {
564                        tool_name: tool_name.unwrap(),
565                        sub: RequestedLevel { level, lint_name },
566                    });
567                }
568                _ => {}
569            };
570
571            let orig_level = level;
572            let lint_flag_val = Symbol::intern(lint_name);
573
574            let Ok(ids) = self.store.find_lints(lint_name) else {
575                // errors already handled above
576                continue;
577            };
578            for id in ids {
579                // ForceWarn and Forbid cannot be overridden
580                if let Some((Level::ForceWarn(_) | Level::Forbid, _)) =
581                    self.current_specs().get(&id)
582                {
583                    continue;
584                }
585
586                if self.check_gated_lint(id, DUMMY_SP, true) {
587                    let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
588                    self.insert(id, (level, src));
589                }
590            }
591        }
592    }
593
594    /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
595    /// (e.g. if a forbid was already inserted on the same scope), then emits a
596    /// diagnostic with no change to `specs`.
597    fn insert_spec(&mut self, id: LintId, (level, src): LevelAndSource) {
598        let (old_level, old_src) = self.provider.get_lint_level(id.lint, self.sess);
599
600        // Setting to a non-forbid level is an error if the lint previously had
601        // a forbid level. Note that this is not necessarily true even with a
602        // `#[forbid(..)]` attribute present, as that is overridden by `--cap-lints`.
603        //
604        // This means that this only errors if we're truly lowering the lint
605        // level from forbid.
606        if self.lint_added_lints && level == Level::Deny && old_level == Level::Forbid {
607            // Having a deny inside a forbid is fine and is ignored, so we skip this check.
608            return;
609        } else if self.lint_added_lints && level != Level::Forbid && old_level == Level::Forbid {
610            // Backwards compatibility check:
611            //
612            // We used to not consider `forbid(lint_group)`
613            // as preventing `allow(lint)` for some lint `lint` in
614            // `lint_group`. For now, issue a future-compatibility
615            // warning for this case.
616            let id_name = id.lint.name_lower();
617            let fcw_warning = match old_src {
618                LintLevelSource::Default => false,
619                LintLevelSource::Node { name, .. } => self.store.is_lint_group(name),
620                LintLevelSource::CommandLine(symbol, _) => self.store.is_lint_group(symbol),
621            };
622            debug!(
623                "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}",
624                fcw_warning,
625                self.current_specs(),
626                old_src,
627                id_name
628            );
629            let sub = match old_src {
630                LintLevelSource::Default => {
631                    OverruledAttributeSub::DefaultSource { id: id.to_string() }
632                }
633                LintLevelSource::Node { span, reason, .. } => {
634                    OverruledAttributeSub::NodeSource { span, reason }
635                }
636                LintLevelSource::CommandLine(_, _) => OverruledAttributeSub::CommandLineSource,
637            };
638            if !fcw_warning {
639                self.sess.dcx().emit_err(OverruledAttribute {
640                    span: src.span(),
641                    overruled: src.span(),
642                    lint_level: level.as_str(),
643                    lint_source: src.name(),
644                    sub,
645                });
646            } else {
647                self.emit_span_lint(
648                    FORBIDDEN_LINT_GROUPS,
649                    src.span().into(),
650                    OverruledAttributeLint {
651                        overruled: src.span(),
652                        lint_level: level.as_str(),
653                        lint_source: src.name(),
654                        sub,
655                    },
656                );
657            }
658
659            // Retain the forbid lint level, unless we are
660            // issuing a FCW. In the FCW case, we want to
661            // respect the new setting.
662            if !fcw_warning {
663                return;
664            }
665        }
666
667        // The lint `unfulfilled_lint_expectations` can't be expected, as it would suppress itself.
668        // Handling expectations of this lint would add additional complexity with little to no
669        // benefit. The expect level for this lint will therefore be ignored.
670        if let Level::Expect(_) = level
671            && id == LintId::of(UNFULFILLED_LINT_EXPECTATIONS)
672        {
673            return;
674        }
675
676        match (old_level, level) {
677            // If the new level is an expectation store it in `ForceWarn`
678            (Level::ForceWarn(_), Level::Expect(expectation_id)) => {
679                self.insert(id, (Level::ForceWarn(Some(expectation_id)), old_src))
680            }
681            // Keep `ForceWarn` level but drop the expectation
682            (Level::ForceWarn(_), _) => self.insert(id, (Level::ForceWarn(None), old_src)),
683            // Set the lint level as normal
684            _ => self.insert(id, (level, src)),
685        };
686    }
687
688    fn add(
689        &mut self,
690        attrs: &[impl AttributeExt],
691        is_crate_node: bool,
692        source_hir_id: Option<HirId>,
693    ) {
694        let sess = self.sess;
695        for (attr_index, attr) in attrs.iter().enumerate() {
696            if attr.has_name(sym::automatically_derived) {
697                self.insert(
698                    LintId::of(SINGLE_USE_LIFETIMES),
699                    (Level::Allow, LintLevelSource::Default),
700                );
701                continue;
702            }
703
704            // `#[doc(hidden)]` disables missing_docs check.
705            if attr.has_name(sym::doc)
706                && attr
707                    .meta_item_list()
708                    .is_some_and(|l| ast::attr::list_contains_name(&l, sym::hidden))
709            {
710                self.insert(LintId::of(MISSING_DOCS), (Level::Allow, LintLevelSource::Default));
711                continue;
712            }
713
714            let level = match Level::from_attr(attr) {
715                None => continue,
716                // This is the only lint level with a `LintExpectationId` that can be created from
717                // an attribute.
718                Some(Level::Expect(unstable_id)) if let Some(hir_id) = source_hir_id => {
719                    let LintExpectationId::Unstable { lint_index: None, attr_id: _ } = unstable_id
720                    else {
721                        bug!("stable id Level::from_attr")
722                    };
723
724                    let stable_id = LintExpectationId::Stable {
725                        hir_id,
726                        attr_index: attr_index.try_into().unwrap(),
727                        lint_index: None,
728                    };
729
730                    Level::Expect(stable_id)
731                }
732                Some(lvl) => lvl,
733            };
734
735            let Some(mut metas) = attr.meta_item_list() else { continue };
736
737            // Check whether `metas` is empty, and get its last element.
738            let Some(tail_li) = metas.last() else {
739                // This emits the unused_attributes lint for `#[level()]`
740                continue;
741            };
742
743            // Before processing the lint names, look for a reason (RFC 2383)
744            // at the end.
745            let mut reason = None;
746            if let Some(item) = tail_li.meta_item() {
747                match item.kind {
748                    ast::MetaItemKind::Word => {} // actual lint names handled later
749                    ast::MetaItemKind::NameValue(ref name_value) => {
750                        if item.path == sym::reason {
751                            if let ast::LitKind::Str(rationale, _) = name_value.kind {
752                                reason = Some(rationale);
753                            } else {
754                                sess.dcx().emit_err(MalformedAttribute {
755                                    span: name_value.span,
756                                    sub: MalformedAttributeSub::ReasonMustBeStringLiteral(
757                                        name_value.span,
758                                    ),
759                                });
760                            }
761                            // found reason, reslice meta list to exclude it
762                            metas.pop().unwrap();
763                        } else {
764                            sess.dcx().emit_err(MalformedAttribute {
765                                span: item.span,
766                                sub: MalformedAttributeSub::BadAttributeArgument(item.span),
767                            });
768                        }
769                    }
770                    ast::MetaItemKind::List(_) => {
771                        sess.dcx().emit_err(MalformedAttribute {
772                            span: item.span,
773                            sub: MalformedAttributeSub::BadAttributeArgument(item.span),
774                        });
775                    }
776                }
777            }
778
779            for (lint_index, li) in metas.iter_mut().enumerate() {
780                let level = match level {
781                    Level::Expect(mut id) => {
782                        id.set_lint_index(Some(lint_index as u16));
783                        Level::Expect(id)
784                    }
785                    level => level,
786                };
787
788                let sp = li.span();
789                let meta_item = match li {
790                    ast::MetaItemInner::MetaItem(meta_item) if meta_item.is_word() => meta_item,
791                    _ => {
792                        let sub = if let Some(item) = li.meta_item()
793                            && let ast::MetaItemKind::NameValue(_) = item.kind
794                            && item.path == sym::reason
795                        {
796                            MalformedAttributeSub::ReasonMustComeLast(sp)
797                        } else {
798                            MalformedAttributeSub::BadAttributeArgument(sp)
799                        };
800
801                        sess.dcx().emit_err(MalformedAttribute { span: sp, sub });
802                        continue;
803                    }
804                };
805                let tool_ident = if meta_item.path.segments.len() > 1 {
806                    Some(meta_item.path.segments.remove(0).ident)
807                } else {
808                    None
809                };
810                let tool_name = tool_ident.map(|ident| ident.name);
811                let name = pprust::path_to_string(&meta_item.path);
812                let lint_result =
813                    self.store.check_lint_name(&name, tool_name, self.registered_tools);
814
815                let (ids, name) = match lint_result {
816                    CheckLintNameResult::Ok(ids) => {
817                        let name =
818                            meta_item.path.segments.last().expect("empty lint name").ident.name;
819                        (ids, name)
820                    }
821
822                    CheckLintNameResult::Tool(ids, new_lint_name) => {
823                        let name = match new_lint_name {
824                            None => {
825                                let complete_name =
826                                    &format!("{}::{}", tool_ident.unwrap().name, name);
827                                Symbol::intern(complete_name)
828                            }
829                            Some(new_lint_name) => {
830                                self.emit_span_lint(
831                                    builtin::RENAMED_AND_REMOVED_LINTS,
832                                    sp.into(),
833                                    DeprecatedLintName {
834                                        name,
835                                        suggestion: sp,
836                                        replace: &new_lint_name,
837                                    },
838                                );
839                                Symbol::intern(&new_lint_name)
840                            }
841                        };
842                        (ids, name)
843                    }
844
845                    CheckLintNameResult::MissingTool => {
846                        // If `MissingTool` is returned, then either the lint does not
847                        // exist in the tool or the code was not compiled with the tool and
848                        // therefore the lint was never added to the `LintStore`. To detect
849                        // this is the responsibility of the lint tool.
850                        continue;
851                    }
852
853                    CheckLintNameResult::NoTool => {
854                        sess.dcx().emit_err(UnknownToolInScopedLint {
855                            span: tool_ident.map(|ident| ident.span),
856                            tool_name: tool_name.unwrap(),
857                            lint_name: pprust::path_to_string(&meta_item.path),
858                            is_nightly_build: sess.is_nightly_build(),
859                        });
860                        continue;
861                    }
862
863                    CheckLintNameResult::Renamed(ref replace) => {
864                        if self.lint_added_lints {
865                            let suggestion =
866                                RenamedLintSuggestion::WithSpan { suggestion: sp, replace };
867                            let name =
868                                tool_ident.map(|tool| format!("{tool}::{name}")).unwrap_or(name);
869                            let lint = RenamedLint { name: name.as_str(), suggestion };
870                            self.emit_span_lint(RENAMED_AND_REMOVED_LINTS, sp.into(), lint);
871                        }
872
873                        // If this lint was renamed, apply the new lint instead of ignoring the
874                        // attribute. Ignore any errors or warnings that happen because the new
875                        // name is inaccurate.
876                        // NOTE: `new_name` already includes the tool name, so we don't
877                        // have to add it again.
878                        let CheckLintNameResult::Ok(ids) =
879                            self.store.check_lint_name(replace, None, self.registered_tools)
880                        else {
881                            panic!("renamed lint does not exist: {replace}");
882                        };
883
884                        (ids, Symbol::intern(&replace))
885                    }
886
887                    CheckLintNameResult::Removed(ref reason) => {
888                        if self.lint_added_lints {
889                            let name =
890                                tool_ident.map(|tool| format!("{tool}::{name}")).unwrap_or(name);
891                            let lint = RemovedLint { name: name.as_str(), reason };
892                            self.emit_span_lint(RENAMED_AND_REMOVED_LINTS, sp.into(), lint);
893                        }
894                        continue;
895                    }
896
897                    CheckLintNameResult::NoLint(suggestion) => {
898                        if self.lint_added_lints {
899                            let name =
900                                tool_ident.map(|tool| format!("{tool}::{name}")).unwrap_or(name);
901                            let suggestion = suggestion.map(|(replace, from_rustc)| {
902                                UnknownLintSuggestion::WithSpan {
903                                    suggestion: sp,
904                                    replace,
905                                    from_rustc,
906                                }
907                            });
908                            let lint = UnknownLint { name, suggestion };
909                            self.emit_span_lint(UNKNOWN_LINTS, sp.into(), lint);
910                        }
911                        continue;
912                    }
913                };
914
915                let src = LintLevelSource::Node { name, span: sp, reason };
916                for &id in ids {
917                    if self.check_gated_lint(id, sp, false) {
918                        self.insert_spec(id, (level, src));
919                    }
920                }
921
922                // This checks for instances where the user writes
923                // `#[expect(unfulfilled_lint_expectations)]` in that case we want to avoid
924                // overriding the lint level but instead add an expectation that can't be
925                // fulfilled. The lint message will include an explanation, that the
926                // `unfulfilled_lint_expectations` lint can't be expected.
927                if let Level::Expect(expect_id) = level {
928                    // The `unfulfilled_lint_expectations` lint is not part of any lint
929                    // groups. Therefore. we only need to check the slice if it contains a
930                    // single lint.
931                    let is_unfulfilled_lint_expectations = match ids {
932                        [lint] => *lint == LintId::of(UNFULFILLED_LINT_EXPECTATIONS),
933                        _ => false,
934                    };
935                    self.provider.push_expectation(
936                        expect_id,
937                        LintExpectation::new(
938                            reason,
939                            sp,
940                            is_unfulfilled_lint_expectations,
941                            tool_name,
942                        ),
943                    );
944                }
945            }
946        }
947
948        if self.lint_added_lints && !is_crate_node {
949            for (id, &(level, ref src)) in self.current_specs().iter() {
950                if !id.lint.crate_level_only {
951                    continue;
952                }
953
954                let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src
955                else {
956                    continue;
957                };
958
959                self.emit_span_lint(
960                    UNUSED_ATTRIBUTES,
961                    lint_attr_span.into(),
962                    IgnoredUnlessCrateSpecified { level: level.as_str(), name: lint_attr_name },
963                );
964                // don't set a separate error for every lint in the group
965                break;
966            }
967        }
968    }
969
970    /// Checks if the lint is gated on a feature that is not enabled.
971    ///
972    /// Returns `true` if the lint's feature is enabled.
973    #[track_caller]
974    fn check_gated_lint(&self, lint_id: LintId, span: Span, lint_from_cli: bool) -> bool {
975        let feature = if let Some(feature) = lint_id.lint.feature_gate
976            && !self.features.enabled(feature)
977        {
978            // Lint is behind a feature that is not enabled; eventually return false.
979            feature
980        } else {
981            // Lint is ungated or its feature is enabled; exit early.
982            return true;
983        };
984
985        if self.lint_added_lints {
986            let lint = builtin::UNKNOWN_LINTS;
987            let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS);
988            // FIXME: make this translatable
989            #[allow(rustc::diagnostic_outside_of_impl)]
990            lint_level(self.sess, lint, level, src, Some(span.into()), |lint| {
991                lint.primary_message(fluent::lint_unknown_gated_lint);
992                lint.arg("name", lint_id.lint.name_lower());
993                lint.note(fluent::lint_note);
994                rustc_session::parse::add_feature_diagnostics_for_issue(
995                    lint,
996                    &self.sess,
997                    feature,
998                    GateIssue::Language,
999                    lint_from_cli,
1000                    None,
1001                );
1002            });
1003        }
1004
1005        false
1006    }
1007
1008    /// Find the lint level for a lint.
1009    pub fn lint_level(&self, lint: &'static Lint) -> LevelAndSource {
1010        self.provider.get_lint_level(lint, self.sess)
1011    }
1012
1013    /// Used to emit a lint-related diagnostic based on the current state of
1014    /// this lint context.
1015    ///
1016    /// [`lint_level`]: rustc_middle::lint::lint_level#decorate-signature
1017    #[rustc_lint_diagnostics]
1018    #[track_caller]
1019    pub(crate) fn opt_span_lint(
1020        &self,
1021        lint: &'static Lint,
1022        span: Option<MultiSpan>,
1023        decorate: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
1024    ) {
1025        let (level, src) = self.lint_level(lint);
1026        lint_level(self.sess, lint, level, src, span, decorate)
1027    }
1028
1029    #[track_caller]
1030    pub fn emit_span_lint(
1031        &self,
1032        lint: &'static Lint,
1033        span: MultiSpan,
1034        decorate: impl for<'a> LintDiagnostic<'a, ()>,
1035    ) {
1036        let (level, src) = self.lint_level(lint);
1037        lint_level(self.sess, lint, level, src, Some(span), |lint| {
1038            decorate.decorate_lint(lint);
1039        });
1040    }
1041
1042    #[track_caller]
1043    pub fn emit_lint(&self, lint: &'static Lint, decorate: impl for<'a> LintDiagnostic<'a, ()>) {
1044        let (level, src) = self.lint_level(lint);
1045        lint_level(self.sess, lint, level, src, None, |lint| {
1046            decorate.decorate_lint(lint);
1047        });
1048    }
1049}
1050
1051pub(crate) fn provide(providers: &mut Providers) {
1052    *providers = Providers { shallow_lint_levels_on, lints_that_dont_need_to_run, ..*providers };
1053}
1054
1055pub(crate) fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1056    match lint_name.split_once("::") {
1057        Some((tool_name, lint_name)) => {
1058            let tool_name = Symbol::intern(tool_name);
1059
1060            (Some(tool_name), lint_name)
1061        }
1062        None => (None, lint_name),
1063    }
1064}