1
Fork 0

Move lint level computation to rustc_middle::lint.

This commit is contained in:
Camille GILLOT 2022-09-24 16:11:18 +02:00
parent 6977f7dbe9
commit 34bc5c8824
5 changed files with 101 additions and 102 deletions

View file

@ -9,8 +9,8 @@ use rustc_hir::{intravisit, HirId};
use rustc_index::vec::IndexVec; use rustc_index::vec::IndexVec;
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
use rustc_middle::lint::{ use rustc_middle::lint::{
reveal_actual_level, struct_lint_level, LevelAndSource, LintExpectation, LintLevelQueryMap, reveal_actual_level, struct_lint_level, LevelAndSource, LintExpectation, LintLevelSource,
LintLevelSource, ShallowLintLevelMap,
}; };
use rustc_middle::ty::query::Providers; use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{RegisteredTools, TyCtxt}; use rustc_middle::ty::{RegisteredTools, TyCtxt};
@ -99,7 +99,9 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp
let mut builder = LintLevelsBuilder { let mut builder = LintLevelsBuilder {
sess: tcx.sess, sess: tcx.sess,
provider: QueryMapExpectationsWrapper { provider: QueryMapExpectationsWrapper {
map: LintLevelQueryMap { tcx, cur: hir::CRATE_HIR_ID, specs: FxHashMap::default() }, tcx,
cur: hir::CRATE_HIR_ID,
specs: ShallowLintLevelMap::default(),
expectations: Vec::new(), expectations: Vec::new(),
unstable_to_stable_ids: FxHashMap::default(), unstable_to_stable_ids: FxHashMap::default(),
}, },
@ -117,12 +119,12 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp
builder.provider.expectations builder.provider.expectations
} }
fn lint_levels_on(tcx: TyCtxt<'_>, hir_id: HirId) -> FxHashMap<LintId, LevelAndSource> { fn shallow_lint_levels_on(tcx: TyCtxt<'_>, hir_id: HirId) -> ShallowLintLevelMap {
let store = unerased_lint_store(tcx); let store = unerased_lint_store(tcx);
let mut levels = LintLevelsBuilder { let mut levels = LintLevelsBuilder {
sess: tcx.sess, sess: tcx.sess,
provider: LintLevelQueryMap { tcx, cur: hir_id, specs: FxHashMap::default() }, provider: LintLevelQueryMap { tcx, cur: hir_id, specs: ShallowLintLevelMap::default() },
warn_about_weird_lints: false, warn_about_weird_lints: false,
store, store,
registered_tools: &tcx.resolutions(()).registered_tools, registered_tools: &tcx.resolutions(()).registered_tools,
@ -143,12 +145,6 @@ pub struct TopDown {
cur: LintStackIndex, cur: LintStackIndex,
} }
pub struct QueryMapExpectationsWrapper<'tcx> {
map: LintLevelQueryMap<'tcx>,
expectations: Vec<(LintExpectationId, LintExpectation)>,
unstable_to_stable_ids: FxHashMap<LintExpectationId, LintExpectationId>,
}
pub trait LintLevelsProvider { pub trait LintLevelsProvider {
fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource>; fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource>;
fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource>; fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource>;
@ -170,28 +166,42 @@ impl LintLevelsProvider for TopDown {
} }
} }
struct LintLevelQueryMap<'tcx> {
tcx: TyCtxt<'tcx>,
cur: HirId,
specs: ShallowLintLevelMap,
}
impl LintLevelsProvider for LintLevelQueryMap<'_> { impl LintLevelsProvider for LintLevelQueryMap<'_> {
fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> { fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> {
&self.specs &self.specs.specs
} }
fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> { fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> {
&mut self.specs &mut self.specs.specs
} }
fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource { fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource {
self.lint_level(lint) self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur)
} }
} }
struct QueryMapExpectationsWrapper<'tcx> {
tcx: TyCtxt<'tcx>,
cur: HirId,
specs: ShallowLintLevelMap,
expectations: Vec<(LintExpectationId, LintExpectation)>,
unstable_to_stable_ids: FxHashMap<LintExpectationId, LintExpectationId>,
}
impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> { impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> {
fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> { fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> {
&self.map.specs &self.specs.specs
} }
fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> { fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> {
self.map.specs.clear(); self.specs.specs.clear();
&mut self.map.specs &mut self.specs.specs
} }
fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource { fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource {
self.map.lint_level(lint) self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur)
} }
fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) { fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) {
let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id else { bug!("unstable expectation id should already be mapped") }; let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id else { bug!("unstable expectation id should already be mapped") };
@ -210,11 +220,7 @@ impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> {
impl<'tcx> LintLevelsBuilder<'_, QueryMapExpectationsWrapper<'tcx>> { impl<'tcx> LintLevelsBuilder<'_, QueryMapExpectationsWrapper<'tcx>> {
fn add_id(&mut self, hir_id: HirId) { fn add_id(&mut self, hir_id: HirId) {
self.add( self.add(self.provider.tcx.hir().attrs(hir_id), hir_id == hir::CRATE_HIR_ID, Some(hir_id));
self.provider.map.tcx.hir().attrs(hir_id),
hir_id == hir::CRATE_HIR_ID,
Some(hir_id),
);
} }
} }
@ -222,7 +228,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for LintLevelsBuilder<'_, QueryMapExpectati
type NestedFilter = nested_filter::All; type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map { fn nested_visit_map(&mut self) -> Self::Map {
self.provider.map.tcx.hir() self.provider.tcx.hir()
} }
fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
@ -941,6 +947,6 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
} }
} }
pub fn provide(providers: &mut Providers) { pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers { lint_levels_on, lint_expectations, ..*providers }; *providers = Providers { shallow_lint_levels_on, lint_expectations, ..*providers };
} }

View file

@ -56,15 +56,27 @@ impl LintLevelSource {
/// A tuple of a lint level and its source. /// A tuple of a lint level and its source.
pub type LevelAndSource = (Level, LintLevelSource); pub type LevelAndSource = (Level, LintLevelSource);
/// Return type for the `shallow_lint_levels_on` query.
///
/// This map represents the set of allowed lints and allowance levels given
/// by the attributes for *a single HirId*.
#[derive(Default, Debug, HashStable)]
pub struct ShallowLintLevelMap {
pub specs: FxHashMap<LintId, LevelAndSource>,
}
/// From an initial level and source, verify the effect of special annotations:
/// `warnings` lint level and lint caps.
///
/// The return of this function is suitable for diagnostics.
pub fn reveal_actual_level( pub fn reveal_actual_level(
level: Option<Level>, level: Option<Level>,
src: &mut LintLevelSource, src: &mut LintLevelSource,
sess: &Session, sess: &Session,
lint: LintId, lint: LintId,
get_lint_id_level: impl FnOnce(LintId) -> (Option<Level>, LintLevelSource), probe_for_lint_level: impl FnOnce(LintId) -> (Option<Level>, LintLevelSource),
) -> Level { ) -> Level {
// If `level` is none then we actually assume the default level for this // If `level` is none then we actually assume the default level for this lint.
// lint.
let mut level = level.unwrap_or_else(|| lint.lint.default_level(sess.edition())); let mut level = level.unwrap_or_else(|| lint.lint.default_level(sess.edition()));
// If we're about to issue a warning, check at the last minute for any // If we're about to issue a warning, check at the last minute for any
@ -76,7 +88,7 @@ pub fn reveal_actual_level(
// and so if we turned that into an error, it'd defeat the purpose of the // and so if we turned that into an error, it'd defeat the purpose of the
// future compatibility warning. // future compatibility warning.
if level == Level::Warn && lint != LintId::of(FORBIDDEN_LINT_GROUPS) { if level == Level::Warn && lint != LintId::of(FORBIDDEN_LINT_GROUPS) {
let (warnings_level, warnings_src) = get_lint_id_level(LintId::of(builtin::WARNINGS)); let (warnings_level, warnings_src) = probe_for_lint_level(LintId::of(builtin::WARNINGS));
if let Some(configured_warning_level) = warnings_level { if let Some(configured_warning_level) = warnings_level {
if configured_warning_level != Level::Warn { if configured_warning_level != Level::Warn {
level = configured_warning_level; level = configured_warning_level;
@ -85,8 +97,7 @@ pub fn reveal_actual_level(
} }
} }
// Ensure that we never exceed the `--cap-lints` argument // Ensure that we never exceed the `--cap-lints` argument unless the source is a --force-warn
// unless the source is a --force-warn
level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src { level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src {
level level
} else { } else {
@ -101,59 +112,76 @@ pub fn reveal_actual_level(
level level
} }
pub struct LintLevelQueryMap<'tcx> { impl ShallowLintLevelMap {
pub tcx: TyCtxt<'tcx>, /// Perform a deep probe in the HIR tree looking for the actual level for the lint.
pub cur: HirId, /// This lint level is not usable for diagnostics, it needs to be corrected by
pub specs: FxHashMap<LintId, LevelAndSource>, /// `reveal_actual_level` beforehand.
} fn probe_for_lint_level(
&self,
impl<'tcx> LintLevelQueryMap<'tcx> { tcx: TyCtxt<'_>,
pub fn lint_id_level(&self, id: LintId) -> (Option<Level>, LintLevelSource) {
Self::get_lint_id_level(id, self.cur, self.tcx, &self.specs)
}
pub fn lint_level(&self, lint: &'static Lint) -> LevelAndSource {
Self::get_lint_level(LintId::of(lint), self.cur, self.tcx, &self.specs)
}
pub fn get_lint_id_level(
id: LintId, id: LintId,
cur: HirId, start: HirId,
tcx: TyCtxt<'tcx>,
specs: &FxHashMap<LintId, LevelAndSource>,
) -> (Option<Level>, LintLevelSource) { ) -> (Option<Level>, LintLevelSource) {
if let Some(&(level, src)) = specs.get(&id) { if let Some(&(level, src)) = self.specs.get(&id) {
return (Some(level), src); return (Some(level), src);
} }
let mut cur = cur; let mut cur = start;
loop { loop {
let parent = tcx.hir().get_parent_node(cur); let parent = tcx.hir().get_parent_node(cur);
if cur == parent { if cur == parent {
return (None, LintLevelSource::Default); return (None, LintLevelSource::Default);
} }
let specs = tcx.lint_levels_on(parent); let specs = tcx.shallow_lint_levels_on(parent);
if let Some(&(level, src)) = specs.get(&id) { if let Some(&(level, src)) = specs.specs.get(&id) {
return (Some(level), src); return (Some(level), src);
} }
cur = parent cur = parent
} }
} }
pub fn get_lint_level( /// Fetch and return the user-visible lint level for the given lint at the given HirId.
id: LintId, pub fn lint_level_id_at_node(
&self,
tcx: TyCtxt<'_>,
lint: LintId,
cur: HirId, cur: HirId,
tcx: TyCtxt<'tcx>,
specs: &FxHashMap<LintId, LevelAndSource>,
) -> (Level, LintLevelSource) { ) -> (Level, LintLevelSource) {
let (level, mut src) = Self::get_lint_id_level(id, cur, tcx, specs); let (level, mut src) = self.probe_for_lint_level(tcx, lint, cur);
let level = reveal_actual_level(level, &mut src, tcx.sess, id, |id| { let level = reveal_actual_level(level, &mut src, tcx.sess, lint, |lint| {
Self::get_lint_id_level(id, cur, tcx, specs) self.probe_for_lint_level(tcx, lint, cur)
}); });
(level, src) (level, src)
} }
} }
impl TyCtxt<'_> {
/// Fetch and return the user-visible lint level for the given lint at the given HirId.
pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) {
self.shallow_lint_levels_on(id).lint_level_id_at_node(self, LintId::of(lint), id)
}
/// Walks upwards from `id` to find a node which might change lint levels with attributes.
/// It stops at `bound` and just returns it if reached.
pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
let hir = self.hir();
loop {
if id == bound {
return bound;
}
if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
return id;
}
let next = hir.get_parent_node(id);
if next == id {
bug!("lint traversal reached the root of the crate");
}
id = next;
}
}
}
/// This struct represents a lint expectation and holds all required information /// This struct represents a lint expectation and holds all required information
/// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after /// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after
/// the `LateLintPass` has completed. /// the `LateLintPass` has completed.

View file

@ -274,7 +274,7 @@ rustc_queries! {
separate_provide_extern separate_provide_extern
} }
query lint_levels_on(key: HirId) -> FxHashMap<LintId, LevelAndSource> { query shallow_lint_levels_on(key: HirId) -> rustc_middle::lint::ShallowLintLevelMap {
arena_cache arena_cache
desc { |tcx| "looking up lint levels for `{}`", key } desc { |tcx| "looking up lint levels for `{}`", key }
} }

View file

@ -4,7 +4,7 @@ use crate::arena::Arena;
use crate::dep_graph::{DepGraph, DepKindStruct}; use crate::dep_graph::{DepGraph, DepKindStruct};
use crate::hir::place::Place as HirPlace; use crate::hir::place::Place as HirPlace;
use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos}; use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
use crate::lint::{struct_lint_level, LintLevelSource}; use crate::lint::struct_lint_level;
use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
use crate::middle::resolve_lifetime; use crate::middle::resolve_lifetime;
use crate::middle::stability; use crate::middle::stability;
@ -57,7 +57,7 @@ use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
use rustc_session::config::{CrateType, OutputFilenames}; use rustc_session::config::{CrateType, OutputFilenames};
use rustc_session::cstore::CrateStoreDyn; use rustc_session::cstore::CrateStoreDyn;
use rustc_session::errors::TargetDataLayoutErrorsWrapper; use rustc_session::errors::TargetDataLayoutErrorsWrapper;
use rustc_session::lint::{Level, Lint, LintId}; use rustc_session::lint::Lint;
use rustc_session::Limit; use rustc_session::Limit;
use rustc_session::Session; use rustc_session::Session;
use rustc_span::def_id::{DefPathHash, StableCrateId}; use rustc_span::def_id::{DefPathHash, StableCrateId};
@ -2812,41 +2812,6 @@ impl<'tcx> TyCtxt<'tcx> {
iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs))
} }
/// Walks upwards from `id` to find a node which might change lint levels with attributes.
/// It stops at `bound` and just returns it if reached.
pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
let hir = self.hir();
loop {
if id == bound {
return bound;
}
if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
return id;
}
let next = hir.get_parent_node(id);
if next == id {
bug!("lint traversal reached the root of the crate");
}
id = next;
}
}
pub fn lint_level_at_node(
self,
lint: &'static Lint,
id: hir::HirId,
) -> (Level, LintLevelSource) {
let level_and_src = crate::lint::LintLevelQueryMap::get_lint_level(
LintId::of(lint),
id,
self,
self.lint_levels_on(id),
);
debug!(?id, ?level_and_src);
level_and_src
}
/// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`, /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
/// typically generated by `#[derive(LintDiagnostic)]`). /// typically generated by `#[derive(LintDiagnostic)]`).
pub fn emit_spanned_lint( pub fn emit_spanned_lint(

View file

@ -1,6 +1,6 @@
use crate::dep_graph; use crate::dep_graph;
use crate::infer::canonical::{self, Canonical}; use crate::infer::canonical::{self, Canonical};
use crate::lint::{LevelAndSource, LintExpectation}; use crate::lint::LintExpectation;
use crate::metadata::ModChild; use crate::metadata::ModChild;
use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
@ -51,7 +51,7 @@ use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
use rustc_session::cstore::{CrateDepKind, CrateSource}; use rustc_session::cstore::{CrateDepKind, CrateSource};
use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib}; use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib};
use rustc_session::lint::{LintExpectationId, LintId}; use rustc_session::lint::LintExpectationId;
use rustc_session::utils::NativeLibKind; use rustc_session::utils::NativeLibKind;
use rustc_session::Limits; use rustc_session::Limits;
use rustc_span::symbol::Symbol; use rustc_span::symbol::Symbol;