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, DiagnosticBuilder};
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::LevelAndSource;
14 use rustc_middle::lint::LintDiagnosticBuilder;
15 use rustc_middle::lint::{
16 struct_lint_level, LintLevelMap, LintLevelSets, LintLevelSource, LintSet,
18 use rustc_middle::ty::query::Providers;
19 use rustc_middle::ty::TyCtxt;
20 use rustc_session::lint::{
21 builtin::{self, FORBIDDEN_LINT_GROUPS},
24 use rustc_session::parse::feature_err;
25 use rustc_session::Session;
26 use rustc_span::symbol::{sym, Symbol};
27 use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP};
32 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> LintLevelMap {
33 assert_eq!(cnum, LOCAL_CRATE);
34 let store = unerased_lint_store(tcx);
35 let levels = LintLevelsBuilder::new(tcx.sess, false, &store);
36 let mut builder = LintLevelMapBuilder { levels, tcx, store };
37 let krate = tcx.hir().krate();
39 builder.levels.id_to_set.reserve(krate.exported_macros.len() + 1);
41 let push = builder.levels.push(&krate.item.attrs, &store, true);
42 builder.levels.register_id(hir::CRATE_HIR_ID);
43 for macro_def in krate.exported_macros {
44 builder.levels.register_id(macro_def.hir_id());
46 intravisit::walk_crate(&mut builder, krate);
47 builder.levels.pop(push);
49 builder.levels.build_map()
52 pub struct LintLevelsBuilder<'s> {
55 id_to_set: FxHashMap<HirId, u32>,
57 warn_about_weird_lints: bool,
61 pub struct BuilderPush {
66 impl<'s> LintLevelsBuilder<'s> {
67 pub fn new(sess: &'s Session, warn_about_weird_lints: bool, store: &'s LintStore) -> Self {
68 let mut builder = LintLevelsBuilder {
70 sets: LintLevelSets::new(),
72 id_to_set: Default::default(),
73 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);
87 let orig_level = level;
89 // If the cap is less than this specified level, e.g., if we've got
90 // `--cap-lints allow` but we've also got `-D foo` then we ignore
91 // this specification as the lint cap will set it to allow anyway.
92 let level = cmp::min(level, self.sets.lint_cap);
94 let lint_flag_val = Symbol::intern(lint_name);
96 let ids = match store.find_lints(&lint_name) {
98 Err(_) => continue, // errors handled in check_lint_name_cmdline above
101 self.check_gated_lint(id, DUMMY_SP);
102 let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
103 specs.insert(id, (level, src));
107 self.sets.list.push(LintSet::CommandLine { specs });
110 /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
111 /// (e.g. if a forbid was already inserted on the same scope), then emits a
112 /// diagnostic with no change to `specs`.
115 specs: &mut FxHashMap<LintId, LevelAndSource>,
117 (level, src): LevelAndSource,
119 // Setting to a non-forbid level is an error if the lint previously had
120 // a forbid level. Note that this is not necessarily true even with a
121 // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`.
123 // This means that this only errors if we're truly lowering the lint
124 // level from forbid.
125 if level != Level::Forbid {
126 if let (Level::Forbid, old_src) =
127 self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess)
129 // Backwards compatibility check:
131 // We used to not consider `forbid(lint_group)`
132 // as preventing `allow(lint)` for some lint `lint` in
133 // `lint_group`. For now, issue a future-compatibility
134 // warning for this case.
135 let id_name = id.lint.name_lower();
136 let fcw_warning = match old_src {
137 LintLevelSource::Default => false,
138 LintLevelSource::Node(symbol, _, _) => self.store.is_lint_group(symbol),
139 LintLevelSource::CommandLine(symbol, _) => self.store.is_lint_group(symbol),
142 "fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}",
143 fcw_warning, specs, old_src, id_name
146 let decorate_diag_builder = |mut diag_builder: DiagnosticBuilder<'_>| {
147 diag_builder.span_label(src.span(), "overruled by previous forbid");
149 LintLevelSource::Default => {
150 diag_builder.note(&format!(
151 "`forbid` lint level is the default for {}",
155 LintLevelSource::Node(_, forbid_source_span, reason) => {
156 diag_builder.span_label(forbid_source_span, "`forbid` level set here");
157 if let Some(rationale) = reason {
158 diag_builder.note(&rationale.as_str());
161 LintLevelSource::CommandLine(_, _) => {
162 diag_builder.note("`forbid` lint level was set on command line");
168 let diag_builder = struct_span_err!(
172 "{}({}) incompatible with previous forbid",
176 decorate_diag_builder(diag_builder);
179 FORBIDDEN_LINT_GROUPS,
180 Some(src.span().into()),
182 let diag_builder = diag_builder.build(&format!(
183 "{}({}) incompatible with previous forbid",
187 decorate_diag_builder(diag_builder);
192 // Retain the forbid lint level, unless we are
193 // issuing a FCW. In the FCW case, we want to
194 // respect the new setting.
200 specs.insert(id, (level, src));
203 /// Pushes a list of AST lint attributes onto this context.
205 /// This function will return a `BuilderPush` object which should be passed
206 /// to `pop` when this scope for the attributes provided is exited.
208 /// This function will perform a number of tasks:
210 /// * It'll validate all lint-related attributes in `attrs`
211 /// * It'll mark all lint-related attributes as used
212 /// * Lint levels will be updated based on the attributes provided
213 /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to
216 /// Don't forget to call `pop`!
219 attrs: &[ast::Attribute],
223 let mut specs = FxHashMap::default();
224 let sess = self.sess;
225 let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
227 let level = match Level::from_symbol(attr.name_or_empty()) {
232 let meta = unwrap_or!(attr.meta(), continue);
233 self.sess.mark_attr_used(attr);
235 let mut metas = unwrap_or!(meta.meta_item_list(), continue);
237 if metas.is_empty() {
238 // FIXME (#55112): issue unused-attributes lint for `#[level()]`
242 // Before processing the lint names, look for a reason (RFC 2383)
244 let mut reason = None;
245 let tail_li = &metas[metas.len() - 1];
246 if let Some(item) = tail_li.meta_item() {
248 ast::MetaItemKind::Word => {} // actual lint names handled later
249 ast::MetaItemKind::NameValue(ref name_value) => {
250 if item.path == sym::reason {
251 // found reason, reslice meta list to exclude it
252 metas = &metas[0..metas.len() - 1];
253 // FIXME (#55112): issue unused-attributes lint if we thereby
254 // don't have any lint names (`#[level(reason = "foo")]`)
255 if let ast::LitKind::Str(rationale, _) = name_value.kind {
256 if !self.sess.features_untracked().lint_reasons {
258 &self.sess.parse_sess,
261 "lint reasons are experimental",
265 reason = Some(rationale);
267 bad_attr(name_value.span)
268 .span_label(name_value.span, "reason must be a string literal")
273 .span_label(item.span, "bad attribute argument")
277 ast::MetaItemKind::List(_) => {
278 bad_attr(item.span).span_label(item.span, "bad attribute argument").emit();
284 let meta_item = match li.meta_item() {
285 Some(meta_item) if meta_item.is_word() => meta_item,
288 let mut err = bad_attr(sp);
289 let mut add_label = true;
290 if let Some(item) = li.meta_item() {
291 if let ast::MetaItemKind::NameValue(_) = item.kind {
292 if item.path == sym::reason {
293 err.span_label(sp, "reason in lint attribute must come last");
299 err.span_label(sp, "bad attribute argument");
305 let tool_name = if meta_item.path.segments.len() > 1 {
306 let tool_ident = meta_item.path.segments[0].ident;
307 if !attr::is_known_lint_tool(tool_ident) {
312 "an unknown tool name found in scoped lint: `{}`",
313 pprust::path_to_string(&meta_item.path),
319 Some(tool_ident.name)
323 let name = meta_item.path.segments.last().expect("empty lint name").ident.name;
324 let lint_result = store.check_lint_name(&name.as_str(), tool_name);
326 CheckLintNameResult::Ok(ids) => {
327 let src = LintLevelSource::Node(name, li.span(), reason);
329 self.check_gated_lint(id, attr.span);
330 self.insert_spec(&mut specs, id, (level, src));
334 CheckLintNameResult::Tool(result) => {
337 let complete_name = &format!("{}::{}", tool_name.unwrap(), name);
338 let src = LintLevelSource::Node(
339 Symbol::intern(complete_name),
344 self.insert_spec(&mut specs, *id, (level, src));
347 Err((Some(ids), ref new_lint_name)) => {
348 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
350 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
356 Some(li.span().into()),
359 "lint name `{}` is deprecated \
360 and may not have an effect in the future.",
367 new_lint_name.to_string(),
368 Applicability::MachineApplicable,
374 let src = LintLevelSource::Node(
375 Symbol::intern(&new_lint_name),
380 self.insert_spec(&mut specs, *id, (level, src));
384 // If Tool(Err(None, _)) is returned, then either the lint does not
385 // exist in the tool or the code was not compiled with the tool and
386 // therefore the lint was never added to the `LintStore`. To detect
387 // this is the responsibility of the lint tool.
392 _ if !self.warn_about_weird_lints => {}
394 CheckLintNameResult::Warning(msg, renamed) => {
395 let lint = builtin::RENAMED_AND_REMOVED_LINTS;
396 let (renamed_lint_level, src) =
397 self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
403 Some(li.span().into()),
405 let mut err = lint.build(&msg);
406 if let Some(new_name) = &renamed {
410 new_name.to_string(),
411 Applicability::MachineApplicable,
418 CheckLintNameResult::NoLint(suggestion) => {
419 let lint = builtin::UNKNOWN_LINTS;
421 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
427 Some(li.span().into()),
429 let name = if let Some(tool_name) = tool_name {
430 format!("{}::{}", tool_name, name)
434 let mut db = lint.build(&format!("unknown lint: `{}`", name));
435 if let Some(suggestion) = suggestion {
439 suggestion.to_string(),
440 Applicability::MachineApplicable,
448 // If this lint was renamed, apply the new lint instead of ignoring the attribute.
449 // This happens outside of the match because the new lint should be applied even if
450 // we don't warn about the name change.
451 if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result {
452 // Ignore any errors or warnings that happen because the new name is inaccurate
453 if let CheckLintNameResult::Ok(ids) =
454 store.check_lint_name(&new_name, tool_name)
457 LintLevelSource::Node(Symbol::intern(&new_name), li.span(), reason);
459 self.check_gated_lint(id, attr.span);
460 self.insert_spec(&mut specs, id, (level, src));
468 for (id, &(level, ref src)) in specs.iter() {
469 if !id.lint.crate_level_only {
473 let (lint_attr_name, lint_attr_span) = match *src {
474 LintLevelSource::Node(name, span, _) => (name, span),
478 let lint = builtin::UNUSED_ATTRIBUTES;
479 let (lint_level, lint_src) =
480 self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
486 Some(lint_attr_span.into()),
488 let mut db = lint.build(&format!(
489 "{}({}) is ignored unless specified at crate level",
496 // don't set a separate error for every lint in the group
502 if !specs.is_empty() {
503 self.cur = self.sets.list.len() as u32;
504 self.sets.list.push(LintSet::Node { specs, parent: prev });
507 BuilderPush { prev, changed: prev != self.cur }
510 /// Checks if the lint is gated on a feature that is not enabled.
511 fn check_gated_lint(&self, lint_id: LintId, span: Span) {
512 if let Some(feature) = lint_id.lint.feature_gate {
513 if !self.sess.features_untracked().enabled(feature) {
515 &self.sess.parse_sess,
518 &format!("the `{}` lint is unstable", lint_id.lint.name_lower()),
525 /// Called after `push` when the scope of a set of attributes are exited.
526 pub fn pop(&mut self, push: BuilderPush) {
527 self.cur = push.prev;
530 /// Find the lint level for a lint.
531 pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) {
532 self.sets.get_lint_level(lint, self.cur, None, self.sess)
535 /// Used to emit a lint-related diagnostic based on the current state of
536 /// this lint context.
540 span: Option<MultiSpan>,
541 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
543 let (level, src) = self.lint_level(lint);
544 struct_lint_level(self.sess, lint, level, src, span, decorate)
547 /// Registers the ID provided with the current set of lints stored in
549 pub fn register_id(&mut self, id: HirId) {
550 self.id_to_set.insert(id, self.cur);
553 pub fn build(self) -> LintLevelSets {
557 pub fn build_map(self) -> LintLevelMap {
558 LintLevelMap { sets: self.sets, id_to_set: self.id_to_set }
562 struct LintLevelMapBuilder<'a, 'tcx> {
563 levels: LintLevelsBuilder<'tcx>,
565 store: &'a LintStore,
568 impl LintLevelMapBuilder<'_, '_> {
569 fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F)
571 F: FnOnce(&mut Self),
573 let is_crate_hir = id == hir::CRATE_HIR_ID;
574 let push = self.levels.push(attrs, self.store, is_crate_hir);
576 self.levels.register_id(id);
579 self.levels.pop(push);
583 impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
584 type Map = Map<'tcx>;
586 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
587 intravisit::NestedVisitorMap::All(self.tcx.hir())
590 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
591 self.with_lint_attrs(param.hir_id, ¶m.attrs, |builder| {
592 intravisit::walk_param(builder, param);
596 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
597 self.with_lint_attrs(it.hir_id(), &it.attrs, |builder| {
598 intravisit::walk_item(builder, it);
602 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
603 self.with_lint_attrs(it.hir_id(), &it.attrs, |builder| {
604 intravisit::walk_foreign_item(builder, it);
608 fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) {
609 // We will call `with_lint_attrs` when we walk
610 // the `StmtKind`. The outer statement itself doesn't
611 // define the lint levels.
612 intravisit::walk_stmt(self, e);
615 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
616 self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
617 intravisit::walk_expr(builder, e);
621 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
622 self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
623 intravisit::walk_struct_field(builder, s);
629 v: &'tcx hir::Variant<'tcx>,
630 g: &'tcx hir::Generics<'tcx>,
633 self.with_lint_attrs(v.id, &v.attrs, |builder| {
634 intravisit::walk_variant(builder, v, g, item_id);
638 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
639 self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
640 intravisit::walk_local(builder, l);
644 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
645 self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
646 intravisit::walk_arm(builder, a);
650 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
651 self.with_lint_attrs(trait_item.hir_id(), &trait_item.attrs, |builder| {
652 intravisit::walk_trait_item(builder, trait_item);
656 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
657 self.with_lint_attrs(impl_item.hir_id(), &impl_item.attrs, |builder| {
658 intravisit::walk_impl_item(builder, impl_item);
663 pub fn provide(providers: &mut Providers) {
664 providers.lint_levels = lint_levels;