1 use crate::context::{CheckLintNameResult, LintStore};
2 use crate::late::unerased_lint_store;
5 use rustc_ast::unwrap_or;
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{struct_span_err, Applicability};
10 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
11 use rustc_hir::{intravisit, HirId};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::lint::LevelSource;
14 use rustc_middle::lint::LintDiagnosticBuilder;
15 use rustc_middle::lint::{struct_lint_level, LintLevelMap, LintLevelSets, LintSet, LintSource};
16 use rustc_middle::ty::query::Providers;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::lint::{builtin, Level, Lint, LintId};
19 use rustc_session::parse::feature_err;
20 use rustc_session::Session;
21 use rustc_span::symbol::{sym, Symbol};
22 use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP};
26 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> LintLevelMap {
27 assert_eq!(cnum, LOCAL_CRATE);
28 let store = unerased_lint_store(tcx);
29 let levels = LintLevelsBuilder::new(tcx.sess, false, &store);
30 let mut builder = LintLevelMapBuilder { levels, tcx, store };
31 let krate = tcx.hir().krate();
33 builder.levels.id_to_set.reserve(krate.exported_macros.len() + 1);
35 let push = builder.levels.push(&krate.item.attrs, &store, true);
36 builder.levels.register_id(hir::CRATE_HIR_ID);
37 for macro_def in krate.exported_macros {
38 builder.levels.register_id(macro_def.hir_id);
40 intravisit::walk_crate(&mut builder, krate);
41 builder.levels.pop(push);
43 builder.levels.build_map()
46 pub struct LintLevelsBuilder<'s> {
49 id_to_set: FxHashMap<HirId, u32>,
51 warn_about_weird_lints: bool,
54 pub struct BuilderPush {
59 impl<'s> LintLevelsBuilder<'s> {
60 pub fn new(sess: &'s Session, warn_about_weird_lints: bool, store: &LintStore) -> Self {
61 let mut builder = LintLevelsBuilder {
63 sets: LintLevelSets::new(),
65 id_to_set: Default::default(),
66 warn_about_weird_lints,
68 builder.process_command_line(sess, store);
69 assert_eq!(builder.sets.list.len(), 1);
73 fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
74 let mut specs = FxHashMap::default();
75 self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
77 for &(ref lint_name, level) in &sess.opts.lint_opts {
78 store.check_lint_name_cmdline(sess, &lint_name, level);
79 let orig_level = level;
81 // If the cap is less than this specified level, e.g., if we've got
82 // `--cap-lints allow` but we've also got `-D foo` then we ignore
83 // this specification as the lint cap will set it to allow anyway.
84 let level = cmp::min(level, self.sets.lint_cap);
86 let lint_flag_val = Symbol::intern(lint_name);
88 let ids = match store.find_lints(&lint_name) {
90 Err(_) => continue, // errors handled in check_lint_name_cmdline above
93 self.check_gated_lint(id, DUMMY_SP);
94 let src = LintSource::CommandLine(lint_flag_val, orig_level);
95 specs.insert(id, (level, src));
99 self.sets.list.push(LintSet::CommandLine { specs });
102 /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
103 /// (e.g. if a forbid was already inserted on the same scope), then emits a
104 /// diagnostic with no change to `specs`.
107 specs: &mut FxHashMap<LintId, LevelSource>,
109 (level, src): LevelSource,
111 if let Some((old_level, old_src)) = specs.get(&id) {
112 if old_level == &Level::Forbid && level != Level::Forbid {
113 let mut diag_builder = struct_span_err!(
117 "{}({}) incompatible with previous forbid in same scope",
122 LintSource::Default => {}
123 LintSource::Node(_, forbid_source_span, reason) => {
124 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
125 if let Some(rationale) = reason {
126 diag_builder.note(&rationale.as_str());
129 LintSource::CommandLine(_, _) => {
130 diag_builder.note("`forbid` lint level was set on command line");
137 specs.insert(id, (level, src));
140 /// Pushes a list of AST lint attributes onto this context.
142 /// This function will return a `BuilderPush` object which should be passed
143 /// to `pop` when this scope for the attributes provided is exited.
145 /// This function will perform a number of tasks:
147 /// * It'll validate all lint-related attributes in `attrs`
148 /// * It'll mark all lint-related attributes as used
149 /// * Lint levels will be updated based on the attributes provided
150 /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
153 /// Don't forget to call `pop`!
156 attrs: &[ast::Attribute],
160 let mut specs = FxHashMap::default();
161 let sess = self.sess;
162 let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
164 let level = match Level::from_symbol(attr.name_or_empty()) {
169 let meta = unwrap_or!(attr.meta(), continue);
170 self.sess.mark_attr_used(attr);
172 let mut metas = unwrap_or!(meta.meta_item_list(), continue);
174 if metas.is_empty() {
175 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
179 // Before processing the lint names, look for a reason (RFC 2383)
181 let mut reason = None;
182 let tail_li = &metas[metas.len() - 1];
183 if let Some(item) = tail_li.meta_item() {
185 ast::MetaItemKind::Word => {} // actual lint names handled later
186 ast::MetaItemKind::NameValue(ref name_value) => {
187 if item.path == sym::reason {
188 // found reason, reslice meta list to exclude it
189 metas = &metas[0..metas.len() - 1];
190 // FIXME (#55112): issue unused-attributes lint if we thereby
191 // don't have any lint names (`#[level(reason = "foo")]`)
192 if let ast::LitKind::Str(rationale, _) = name_value.kind {
193 if !self.sess.features_untracked().lint_reasons {
195 &self.sess.parse_sess,
198 "lint reasons are experimental",
202 reason = Some(rationale);
204 bad_attr(name_value.span)
205 .span_label(name_value.span, "reason must be a string literal")
210 .span_label(item.span, "bad attribute argument")
214 ast::MetaItemKind::List(_) => {
215 bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
221 let meta_item = match li.meta_item() {
222 Some(meta_item) if meta_item.is_word() => meta_item,
225 let mut err = bad_attr(sp);
226 let mut add_label = true;
227 if let Some(item) = li.meta_item() {
228 if let ast::MetaItemKind::NameValue(_) = item.kind {
229 if item.path == sym::reason {
230 err.span_label(sp, "reason in lint attribute must come last");
236 err.span_label(sp, "bad attribute argument");
242 let tool_name = if meta_item.path.segments.len() > 1 {
243 let tool_ident = meta_item.path.segments[0].ident;
244 if !attr::is_known_lint_tool(tool_ident) {
249 "an unknown tool name found in scoped lint: `{}`",
250 pprust::path_to_string(&meta_item.path),
256 Some(tool_ident.name)
260 let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
261 match store.check_lint_name(&name.as_str(), tool_name) {
262 CheckLintNameResult::Ok(ids) => {
263 let src = LintSource::Node(name, li.span(), reason);
265 self.check_gated_lint(id, attr.span);
266 self.insert_spec(&mut specs, id, (level, src));
270 CheckLintNameResult::Tool(result) => {
273 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
274 let src = LintSource::Node(
275 Symbol::intern(complete_name),
280 self.insert_spec(&mut specs, *id, (level, src));
283 Err((Some(ids), new_lint_name)) => {
284 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
286 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
292 Some(li.span().into()),
295 "lint name `{}` is deprecated \
296 and may not have an effect in the future. \
297 Also `cfg_attr(cargo-clippy)` won't be necessary anymore",
304 new_lint_name.to_string(),
305 Applicability::MachineApplicable,
311 let src = LintSource::Node(
312 Symbol::intern(&new_lint_name),
317 self.insert_spec(&mut specs, *id, (level, src));
321 // If Tool(Err(None, _)) is returned, then either the lint does not
322 // exist in the tool or the code was not compiled with the tool and
323 // therefore the lint was never added to the `LintStore`. To detect
324 // this is the responsibility of the lint tool.
329 _ if !self.warn_about_weird_lints => {}
331 CheckLintNameResult::Warning(msg, renamed) => {
332 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
334 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
340 Some(li.span().into()),
342 let mut err = lint.build(&msg);
343 if let Some(new_name) = renamed {
348 Applicability::MachineApplicable,
355 CheckLintNameResult::NoLint(suggestion) => {
356 let lint = builtin::UNKNOWN_LINTS;
358 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
364 Some(li.span().into()),
366 let mut db = lint.build(&format!("unknown lint: `{}`", name));
367 if let Some(suggestion) = suggestion {
371 suggestion.to_string(),
372 Applicability::MachineApplicable,
384 for (id, &(level, ref src)) in specs.iter() {
385 if !id.lint.crate_level_only {
389 let (lint_attr_name, lint_attr_span) = match *src {
390 LintSource::Node(name, span, _) => (name, span),
394 let lint = builtin::UNUSED_ATTRIBUTES;
395 let (lint_level, lint_src) =
396 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
402 Some(lint_attr_span.into()),
404 let mut db = lint.build(&format!(
405 "{}({}) is ignored unless specified at crate level",
412 // don't set a separate error for every lint in the group
417 for (id, &(level, ref src)) in specs.iter() {
418 if level == Level::Forbid {
421 let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) {
422 (Some(Level::Forbid), src) => src,
425 let forbidden_lint_name = match forbid_src {
426 LintSource::Default => id.to_string(),
427 LintSource::Node(name, _, _) => name.to_string(),
428 LintSource::CommandLine(name, _) => name.to_string(),
430 let (lint_attr_name, lint_attr_span) = match *src {
431 LintSource::Node(name, span, _) => (name, span),
434 let mut diag_builder = struct_span_err!(
438 "{}({}) overruled by outer forbid({})",
443 diag_builder.span_label(lint_attr_span, "overruled by previous forbid");
445 LintSource::Default => {}
446 LintSource::Node(_, forbid_source_span, reason) => {
447 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
448 if let Some(rationale) = reason {
449 diag_builder.note(&rationale.as_str());
452 LintSource::CommandLine(_, _) => {
453 diag_builder.note("`forbid` lint level was set on command line");
457 // don't set a separate error for every lint in the group
462 if !specs.is_empty() {
463 self.cur = self.sets.list.len() as u32;
464 self.sets.list.push(LintSet::Node { specs, parent: prev });
467 BuilderPush { prev, changed: prev != self.cur }
470 /// Checks if the lint is gated on a feature that is not enabled.
471 fn check_gated_lint(&self, lint_id: LintId, span: Span) {
472 if let Some(feature) = lint_id.lint.feature_gate {
473 if !self.sess.features_untracked().enabled(feature) {
475 &self.sess.parse_sess,
478 &format!("the `{}` lint is unstable", lint_id.lint.name_lower()),
485 /// Called after `push` when the scope of a set of attributes are exited.
486 pub fn pop(&mut self, push: BuilderPush) {
487 self.cur = push.prev;
490 /// Find the lint level for a lint.
491 pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintSource) {
492 self.sets.get_lint_level(lint, self.cur, None, self.sess)
495 /// Used to emit a lint-related diagnostic based on the current state of
496 /// this lint context.
500 span: Option<MultiSpan>,
501 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
503 let (level, src) = self.lint_level(lint);
504 struct_lint_level(self.sess, lint, level, src, span, decorate)
507 /// Registers the ID provided with the current set of lints stored in
509 pub fn register_id(&mut self, id: HirId) {
510 self.id_to_set.insert(id, self.cur);
513 pub fn build(self) -> LintLevelSets {
517 pub fn build_map(self) -> LintLevelMap {
518 LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
522 struct LintLevelMapBuilder<'a, 'tcx> {
523 levels: LintLevelsBuilder<'tcx>,
525 store: &'a LintStore,
528 impl LintLevelMapBuilder<'_, '_> {
529 fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
531 F: FnOnce(&mut Self),
533 let is_crate_hir = id == hir::CRATE_HIR_ID;
534 let push = self.levels.push(attrs, self.store, is_crate_hir);
536 self.levels.register_id(id);
539 self.levels.pop(push);
543 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
544 type Map = Map<'tcx>;
546 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
547 intravisit::NestedVisitorMap::All(self.tcx.hir())
550 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
551 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
552 intravisit::walk_param(builder, param);
556 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
557 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
558 intravisit::walk_item(builder, it);
562 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
563 self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
564 intravisit::walk_foreign_item(builder, it);
568 fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) {
569 // We will call `with_lint_attrs` when we walk
570 // the `StmtKind`. The outer statement itself doesn't
571 // define the lint levels.
572 intravisit::walk_stmt(self, e);
575 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
576 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
577 intravisit::walk_expr(builder, e);
581 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
582 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
583 intravisit::walk_struct_field(builder, s);
589 v: &'tcx hir::Variant<'tcx>,
590 g: &'tcx hir::Generics<'tcx>,
593 self.with_lint_attrs(v.id, &v.attrs, |builder| {
594 intravisit::walk_variant(builder, v, g, item_id);
598 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
599 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
600 intravisit::walk_local(builder, l);
604 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
605 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
606 intravisit::walk_arm(builder, a);
610 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
611 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
612 intravisit::walk_trait_item(builder, trait_item);
616 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
617 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
618 intravisit::walk_impl_item(builder, impl_item);
623 pub fn provide(providers: &mut Providers) {
624 providers.lint_levels = lint_levels;