1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
4 use rustc_ast_pretty::pprust;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
8 use rustc_hir::{intravisit, HirId, CRATE_HIR_ID};
9 use rustc_middle::hir::map::Map;
10 use rustc_middle::lint::LevelAndSource;
11 use rustc_middle::lint::LintDiagnosticBuilder;
12 use rustc_middle::lint::{
13 struct_lint_level, LintLevelMap, LintLevelSets, LintLevelSource, LintSet, LintStackIndex,
16 use rustc_middle::ty::query::Providers;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::lint::{
19 builtin::{self, FORBIDDEN_LINT_GROUPS},
22 use rustc_session::parse::feature_err;
23 use rustc_session::Session;
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP};
28 fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap {
29 let store = unerased_lint_store(tcx);
30 let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID);
31 let levels = LintLevelsBuilder::new(tcx.sess, false, &store, crate_attrs);
32 let mut builder = LintLevelMapBuilder { levels, tcx, store };
33 let krate = tcx.hir().krate();
35 builder.levels.id_to_set.reserve(krate.owners.len() + 1);
37 let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), &store, true);
38 builder.levels.register_id(hir::CRATE_HIR_ID);
39 tcx.hir().walk_toplevel_module(&mut builder);
40 builder.levels.pop(push);
42 builder.levels.build_map()
45 pub struct LintLevelsBuilder<'s> {
48 id_to_set: FxHashMap<HirId, LintStackIndex>,
50 warn_about_weird_lints: bool,
52 crate_attrs: &'s [ast::Attribute],
55 pub struct BuilderPush {
60 impl<'s> LintLevelsBuilder<'s> {
63 warn_about_weird_lints: bool,
65 crate_attrs: &'s [ast::Attribute],
67 let mut builder = LintLevelsBuilder {
69 sets: LintLevelSets::new(),
71 id_to_set: Default::default(),
72 warn_about_weird_lints,
76 builder.process_command_line(sess, store);
77 assert_eq!(builder.sets.list.len(), 1);
81 fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
82 let mut specs = FxHashMap::default();
83 self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
85 for &(ref lint_name, level) in &sess.opts.lint_opts {
86 store.check_lint_name_cmdline(sess, &lint_name, level, self.crate_attrs);
87 let orig_level = level;
88 let lint_flag_val = Symbol::intern(lint_name);
90 let ids = match store.find_lints(&lint_name) {
92 Err(_) => continue, // errors handled in check_lint_name_cmdline above
95 // ForceWarn and Forbid cannot be overriden
96 if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) {
100 self.check_gated_lint(id, DUMMY_SP);
101 let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
102 specs.insert(id, (level, src));
106 self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE });
109 /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
110 /// (e.g. if a forbid was already inserted on the same scope), then emits a
111 /// diagnostic with no change to `specs`.
114 specs: &mut FxHashMap<LintId, LevelAndSource>,
116 (level, src): LevelAndSource,
118 let (old_level, old_src) =
119 self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess);
120 // Setting to a non-forbid level is an error if the lint previously had
121 // a forbid level. Note that this is not necessarily true even with a
122 // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`.
124 // This means that this only errors if we're truly lowering the lint
125 // level from forbid.
126 if level != Level::Forbid {
127 if let Level::Forbid = old_level {
128 // Backwards compatibility check:
130 // We used to not consider `forbid(lint_group)`
131 // as preventing `allow(lint)` for some lint `lint` in
132 // `lint_group`. For now, issue a future-compatibility
133 // warning for this case.
134 let id_name = id.lint.name_lower();
135 let fcw_warning = match old_src {
136 LintLevelSource::Default => false,
137 LintLevelSource::Node(symbol, _, _) => self.store.is_lint_group(symbol),
138 LintLevelSource::CommandLine(symbol, _) => self.store.is_lint_group(symbol),
141 "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}",
142 fcw_warning, specs, old_src, id_name
145 let decorate_diag_builder = |mut diag_builder: DiagnosticBuilder<'_>| {
146 diag_builder.span_label(src.span(), "overruled by previous forbid");
148 LintLevelSource::Default => {
149 diag_builder.note(&format!(
150 "`forbid` lint level is the default for {}",
154 LintLevelSource::Node(_, forbid_source_span, reason) => {
155 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
156 if let Some(rationale) = reason {
157 diag_builder.note(&rationale.as_str());
160 LintLevelSource::CommandLine(_, _) => {
161 diag_builder.note("`forbid` lint level was set on command line");
167 let diag_builder = struct_span_err!(
171 "{}({}) incompatible with previous forbid",
175 decorate_diag_builder(diag_builder);
178 FORBIDDEN_LINT_GROUPS,
179 Some(src.span().into()),
181 let diag_builder = diag_builder.build(&format!(
182 "{}({}) incompatible with previous forbid",
186 decorate_diag_builder(diag_builder);
191 // Retain the forbid lint level, unless we are
192 // issuing a FCW. In the FCW case, we want to
193 // respect the new setting.
199 if let Level::ForceWarn = old_level {
200 specs.insert(id, (old_level, old_src));
202 specs.insert(id, (level, src));
206 /// Pushes a list of AST lint attributes onto this context.
208 /// This function will return a `BuilderPush` object which should be passed
209 /// to `pop` when this scope for the attributes provided is exited.
211 /// This function will perform a number of tasks:
213 /// * It'll validate all lint-related attributes in `attrs`
214 /// * It'll mark all lint-related attributes as used
215 /// * Lint levels will be updated based on the attributes provided
216 /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
219 /// Don't forget to call `pop`!
222 attrs: &[ast::Attribute],
226 let mut specs = FxHashMap::default();
227 let sess = self.sess;
228 let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
230 let Some(level) = Level::from_symbol(attr.name_or_empty()) else {
234 let Some(mut metas) = attr.meta_item_list() else {
238 if metas.is_empty() {
239 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
243 // Before processing the lint names, look for a reason (RFC 2383)
245 let mut reason = None;
246 let tail_li = &metas[metas.len() - 1];
247 if let Some(item) = tail_li.meta_item() {
249 ast::MetaItemKind::Word => {} // actual lint names handled later
250 ast::MetaItemKind::NameValue(ref name_value) => {
251 if item.path == sym::reason {
252 // FIXME (#55112): issue unused-attributes lint if we thereby
253 // don't have any lint names (`#[level(reason = "foo")]`)
254 if let ast::LitKind::Str(rationale, _) = name_value.kind {
255 if !self.sess.features_untracked().lint_reasons {
257 &self.sess.parse_sess,
260 "lint reasons are experimental",
264 reason = Some(rationale);
266 bad_attr(name_value.span)
267 .span_label(name_value.span, "reason must be a string literal")
270 // found reason, reslice meta list to exclude it
271 metas.pop().unwrap();
274 .span_label(item.span, "bad attribute argument")
278 ast::MetaItemKind::List(_) => {
279 bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
286 let mut meta_item = match li {
287 ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item,
289 let mut err = bad_attr(sp);
290 let mut add_label = true;
291 if let Some(item) = li.meta_item() {
292 if let ast::MetaItemKind::NameValue(_) = item.kind {
293 if item.path == sym::reason {
294 err.span_label(sp, "reason in lint attribute must come last");
300 err.span_label(sp, "bad attribute argument");
306 let tool_ident = if meta_item.path.segments.len() > 1 {
307 Some(meta_item.path.segments.remove(0).ident)
311 let tool_name = tool_ident.map(|ident| ident.name);
312 let name = pprust::path_to_string(&meta_item.path);
313 let lint_result = store.check_lint_name(sess, &name, tool_name, self.crate_attrs);
315 CheckLintNameResult::Ok(ids) => {
316 let src = LintLevelSource::Node(
317 meta_item.path.segments.last().expect("empty lint name").ident.name,
322 self.check_gated_lint(id, attr.span);
323 self.insert_spec(&mut specs, id, (level, src));
327 CheckLintNameResult::Tool(result) => {
331 &format!("{}::{}", tool_ident.unwrap().name, name);
332 let src = LintLevelSource::Node(
333 Symbol::intern(complete_name),
338 self.insert_spec(&mut specs, *id, (level, src));
341 Err((Some(ids), ref new_lint_name)) => {
342 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
344 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
353 "lint name `{}` is deprecated \
354 and may not have an effect in the future.",
361 new_lint_name.to_string(),
362 Applicability::MachineApplicable,
368 let src = LintLevelSource::Node(
369 Symbol::intern(&new_lint_name),
374 self.insert_spec(&mut specs, *id, (level, src));
378 // If Tool(Err(None, _)) is returned, then either the lint does not
379 // exist in the tool or the code was not compiled with the tool and
380 // therefore the lint was never added to the `LintStore`. To detect
381 // this is the responsibility of the lint tool.
386 &CheckLintNameResult::NoTool => {
387 let mut err = struct_span_err!(
389 tool_ident.map_or(DUMMY_SP, |ident| ident.span),
391 "unknown tool name `{}` found in scoped lint: `{}::{}`",
394 pprust::path_to_string(&meta_item.path),
396 if sess.is_nightly_build() {
398 "add `#![register_tool({})]` to the crate root",
406 _ if !self.warn_about_weird_lints => {}
408 CheckLintNameResult::Warning(msg, renamed) => {
409 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
410 let (renamed_lint_level, src) =
411 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
419 let mut err = lint.build(&msg);
420 if let Some(new_name) = &renamed {
424 new_name.to_string(),
425 Applicability::MachineApplicable,
432 CheckLintNameResult::NoLint(suggestion) => {
433 let lint = builtin::UNKNOWN_LINTS;
435 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
436 struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| {
437 let name = if let Some(tool_ident) = tool_ident {
438 format!("{}::{}", tool_ident.name, name)
442 let mut db = lint.build(&format!("unknown lint: `{}`", name));
443 if let Some(suggestion) = suggestion {
447 suggestion.to_string(),
448 Applicability::MachineApplicable,
455 // If this lint was renamed, apply the new lint instead of ignoring the attribute.
456 // This happens outside of the match because the new lint should be applied even if
457 // we don't warn about the name change.
458 if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result {
459 // Ignore any errors or warnings that happen because the new name is inaccurate
460 // NOTE: `new_name` already includes the tool name, so we don't have to add it again.
461 if let CheckLintNameResult::Ok(ids) =
462 store.check_lint_name(sess, &new_name, None, self.crate_attrs)
464 let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason);
466 self.check_gated_lint(id, attr.span);
467 self.insert_spec(&mut specs, id, (level, src));
470 panic!("renamed lint does not exist: {}", new_name);
477 for (id, &(level, ref src)) in specs.iter() {
478 if !id.lint.crate_level_only {
482 let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else {
486 let lint = builtin::UNUSED_ATTRIBUTES;
487 let (lint_level, lint_src) =
488 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
494 Some(lint_attr_span.into()),
496 let mut db = lint.build(&format!(
497 "{}({}) is ignored unless specified at crate level",
504 // don't set a separate error for every lint in the group
510 if !specs.is_empty() {
511 self.cur = self.sets.list.push(LintSet { specs, parent: prev });
514 BuilderPush { prev, changed: prev != self.cur }
517 /// Checks if the lint is gated on a feature that is not enabled.
518 fn check_gated_lint(&self, lint_id: LintId, span: Span) {
519 if let Some(feature) = lint_id.lint.feature_gate {
520 if !self.sess.features_untracked().enabled(feature) {
522 &self.sess.parse_sess,
525 &format!("the `{}` lint is unstable", lint_id.lint.name_lower()),
532 /// Called after `push` when the scope of a set of attributes are exited.
533 pub fn pop(&mut self, push: BuilderPush) {
534 self.cur = push.prev;
537 /// Find the lint level for a lint.
538 pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) {
539 self.sets.get_lint_level(lint, self.cur, None, self.sess)
542 /// Used to emit a lint-related diagnostic based on the current state of
543 /// this lint context.
547 span: Option<MultiSpan>,
548 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
550 let (level, src) = self.lint_level(lint);
551 struct_lint_level(self.sess, lint, level, src, span, decorate)
554 /// Registers the ID provided with the current set of lints stored in
556 pub fn register_id(&mut self, id: HirId) {
557 self.id_to_set.insert(id, self.cur);
560 pub fn build_map(self) -> LintLevelMap {
561 LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
565 pub fn is_known_lint_tool(m_item: Symbol, sess: &Session, attrs: &[ast::Attribute]) -> bool {
566 if [sym::clippy, sym::rustc, sym::rustdoc].contains(&m_item) {
569 // Look for registered tools
570 // NOTE: does no error handling; error handling is done by rustc_resolve.
571 sess.filter_by_name(attrs, sym::register_tool)
572 .filter_map(|attr| attr.meta_item_list())
574 .filter_map(|nested_meta| nested_meta.ident())
575 .map(|ident| ident.name)
576 .any(|name| name == m_item)
579 struct LintLevelMapBuilder<'a, 'tcx> {
580 levels: LintLevelsBuilder<'tcx>,
582 store: &'a LintStore,
585 impl LintLevelMapBuilder<'_, '_> {
586 fn with_lint_attrs<F>(&mut self, id: hir::HirId, f: F)
588 F: FnOnce(&mut Self),
590 let is_crate_hir = id == hir::CRATE_HIR_ID;
591 let attrs = self.tcx.hir().attrs(id);
592 let push = self.levels.push(attrs, self.store, is_crate_hir);
594 self.levels.register_id(id);
597 self.levels.pop(push);
601 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
602 type Map = Map<'tcx>;
604 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
605 intravisit::NestedVisitorMap::All(self.tcx.hir())
608 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
609 self.with_lint_attrs(param.hir_id, |builder| {
610 intravisit::walk_param(builder, param);
614 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
615 self.with_lint_attrs(it.hir_id(), |builder| {
616 intravisit::walk_item(builder, it);
620 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
621 self.with_lint_attrs(it.hir_id(), |builder| {
622 intravisit::walk_foreign_item(builder, it);
626 fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) {
627 // We will call `with_lint_attrs` when we walk
628 // the `StmtKind`. The outer statement itself doesn't
629 // define the lint levels.
630 intravisit::walk_stmt(self, e);
633 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
634 self.with_lint_attrs(e.hir_id, |builder| {
635 intravisit::walk_expr(builder, e);
639 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
640 self.with_lint_attrs(s.hir_id, |builder| {
641 intravisit::walk_field_def(builder, s);
647 v: &'tcx hir::Variant<'tcx>,
648 g: &'tcx hir::Generics<'tcx>,
651 self.with_lint_attrs(v.id, |builder| {
652 intravisit::walk_variant(builder, v, g, item_id);
656 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
657 self.with_lint_attrs(l.hir_id, |builder| {
658 intravisit::walk_local(builder, l);
662 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
663 self.with_lint_attrs(a.hir_id, |builder| {
664 intravisit::walk_arm(builder, a);
668 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
669 self.with_lint_attrs(trait_item.hir_id(), |builder| {
670 intravisit::walk_trait_item(builder, trait_item);
674 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
675 self.with_lint_attrs(impl_item.hir_id(), |builder| {
676 intravisit::walk_impl_item(builder, impl_item);
681 pub fn provide(providers: &mut Providers) {
682 providers.lint_levels = lint_levels;