Auto merge of #88435 - cjgillot:no-walk-crate, r=Aaron1011

Avoid invoking the hir_crate query to traverse the HIR

Walking the HIR tree is done using the `hir_crate` query. However, this is unnecessary, since `hir_owner(CRATE_DEF_ID)` provides the same information. Since depending on `hir_crate` forces dependents to always be executed, this leads to unnecessary work.

By splitting HIR and attributes visits, we can avoid an edge to `hir_crate` when trying to visit the HIR tree.
This commit is contained in:
bors 2021-09-05 21:40:34 +00:00
commit 7849e3e9dd
25 changed files with 117 additions and 132 deletions

View File

@ -32,7 +32,6 @@
//! example generator inference, and possibly also HIR borrowck.
use crate::hir::*;
use crate::hir_id::CRATE_HIR_ID;
use crate::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
use rustc_ast::walk_list;
use rustc_ast::{Attribute, Label};
@ -477,17 +476,6 @@ pub trait Visitor<'v>: Sized {
}
}
/// Walks the contents of a crate. See also `Crate::visit_all_items`.
pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) {
let top_mod = krate.module();
visitor.visit_mod(top_mod, top_mod.inner, CRATE_HIR_ID);
for (&id, attrs) in krate.attrs.iter() {
for a in *attrs {
visitor.visit_attribute(id, a)
}
}
}
pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) {
visitor.visit_id(mod_hir_id);
for &item_id in module.item_ids {

View File

@ -142,7 +142,7 @@ pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) {
krate.visit_all_item_likes(&mut dirty_clean_visitor);
let mut all_attrs = FindAllAttrs { tcx, found_attrs: vec![] };
intravisit::walk_crate(&mut all_attrs, krate);
tcx.hir().walk_attributes(&mut all_attrs);
// Note that we cannot use the existing "unused attribute"-infrastructure
// here, since that is running before codegen. This is also the reason why

View File

@ -464,10 +464,6 @@ pub fn lower_to_hir<'res, 'tcx>(
arena,
);
if sess.opts.debugging_opts.hir_stats {
hir_stats::print_hir_stats(&hir_crate);
}
sess.time("early_lint_checks", || {
rustc_lint::check_ast_crate(
sess,

View File

@ -451,9 +451,8 @@ fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T)
// since the root module isn't visited as an item (because it isn't an
// item), warn for it here.
lint_callback!(cx, check_crate, krate);
hir_visit::walk_crate(cx, krate);
tcx.hir().walk_toplevel_module(cx);
tcx.hir().walk_attributes(cx);
lint_callback!(cx, check_crate_post, krate);
})
}

View File

@ -37,7 +37,7 @@ fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap {
let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), &store, true);
builder.levels.register_id(hir::CRATE_HIR_ID);
intravisit::walk_crate(&mut builder, krate);
tcx.hir().walk_toplevel_module(&mut builder);
builder.levels.pop(push);
builder.levels.build_map()

View File

@ -7,9 +7,9 @@ use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::svh::Svh;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
use rustc_hir::intravisit;
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::*;
use rustc_index::vec::Idx;
@ -519,6 +519,22 @@ impl<'hir> Map<'hir> {
}
}
/// Walks the contents of a crate. See also `Crate::visit_all_items`.
pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
visitor.visit_mod(top_mod, span, hir_id);
}
/// Walks the attributes in a crate.
pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
let krate = self.krate();
for (&id, attrs) in krate.attrs.iter() {
for a in *attrs {
visitor.visit_attribute(id, a)
}
}
}
pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
where
V: ItemLikeVisitor<'hir>,
@ -934,7 +950,8 @@ pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tc
&tcx.untracked_resolutions.definitions,
hcx,
);
intravisit::walk_crate(&mut collector, tcx.untracked_crate);
let top_mod = tcx.untracked_crate.module();
collector.visit_mod(top_mod, top_mod.inner, CRATE_HIR_ID);
let map = collector.finalize_and_compute_crate_hash();
tcx.arena.alloc(map)

View File

@ -775,5 +775,5 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
let krate = tcx.hir().krate();
let live_symbols = find_live(tcx, access_levels, krate);
let mut visitor = DeadVisitor { tcx, live_symbols };
intravisit::walk_crate(&mut visitor, krate);
tcx.hir().walk_toplevel_module(&mut visitor);
}

View File

@ -11,6 +11,10 @@ use rustc_middle::ty::TyCtxt;
pub fn check_crate(tcx: TyCtxt<'_>) {
tcx.dep_graph.assert_ignored();
if tcx.sess.opts.debugging_opts.hir_stats {
crate::hir_stats::print_hir_stats(tcx);
}
let errors = Lock::new(Vec::new());
let hir_map = tcx.hir();

View File

@ -9,6 +9,7 @@ use rustc_hir as hir;
use rustc_hir::intravisit as hir_visit;
use rustc_hir::HirId;
use rustc_middle::hir::map::Map;
use rustc_middle::ty::TyCtxt;
use rustc_middle::util::common::to_readable_str;
use rustc_span::Span;
@ -25,18 +26,19 @@ struct NodeData {
}
struct StatCollector<'k> {
krate: Option<&'k hir::Crate<'k>>,
krate: Option<Map<'k>>,
data: FxHashMap<&'static str, NodeData>,
seen: FxHashSet<Id>,
}
pub fn print_hir_stats(krate: &hir::Crate<'_>) {
pub fn print_hir_stats(tcx: TyCtxt<'_>) {
let mut collector = StatCollector {
krate: Some(krate),
krate: Some(tcx.hir()),
data: FxHashMap::default(),
seen: FxHashSet::default(),
};
hir_visit::walk_crate(&mut collector, krate);
tcx.hir().walk_toplevel_module(&mut collector);
tcx.hir().walk_attributes(&mut collector);
collector.print("HIR STATS");
}

View File

@ -6,7 +6,7 @@
use rustc_ast::{Attribute, MetaItem, MetaItemKind};
use rustc_errors::struct_span_err;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
use rustc_middle::hir::map::Map;
use rustc_middle::middle::lib_features::LibFeatures;
use rustc_middle::ty::query::Providers;
@ -126,9 +126,7 @@ impl Visitor<'tcx> for LibFeatureCollector<'tcx> {
fn get_lib_features(tcx: TyCtxt<'_>, (): ()) -> LibFeatures {
let mut collector = LibFeatureCollector::new(tcx);
let krate = tcx.hir().krate();
intravisit::walk_crate(&mut collector, krate);
tcx.hir().walk_attributes(&mut collector);
collector.lib_features
}

View File

@ -8,6 +8,7 @@ use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::hir_id::CRATE_HIR_ID;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{FieldDef, Generics, HirId, Item, TraitRef, Ty, TyKind, Variant};
use rustc_middle::hir::map::Map;
@ -678,7 +679,6 @@ fn stability_index(tcx: TyCtxt<'tcx>, (): ()) -> Index<'tcx> {
.collect();
{
let krate = tcx.hir().krate();
let mut annotator = Annotator {
tcx,
index: &mut index,
@ -711,13 +711,13 @@ fn stability_index(tcx: TyCtxt<'tcx>, (): ()) -> Index<'tcx> {
annotator.annotate(
CRATE_DEF_ID,
krate.module().inner,
tcx.hir().span(CRATE_HIR_ID),
None,
AnnotationKind::Required,
InheritDeprecation::Yes,
InheritConstStability::No,
InheritStability::No,
|v| intravisit::walk_crate(v, krate),
|v| tcx.hir().walk_toplevel_module(v),
);
}
index
@ -908,8 +908,8 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
if tcx.stability().staged_api[&LOCAL_CRATE] {
let krate = tcx.hir().krate();
let mut missing = MissingStabilityAnnotations { tcx, access_levels };
missing.check_missing_stability(CRATE_DEF_ID, krate.module().inner);
intravisit::walk_crate(&mut missing, krate);
missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
tcx.hir().walk_toplevel_module(&mut missing);
krate.visit_all_item_likes(&mut missing.as_deep_visitor());
}

View File

@ -2169,7 +2169,7 @@ fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels {
changed: false,
};
loop {
intravisit::walk_crate(&mut visitor, tcx.hir().krate());
tcx.hir().walk_toplevel_module(&mut visitor);
if visitor.changed {
visitor.changed = false;
} else {
@ -2192,11 +2192,11 @@ fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
in_variant: false,
old_error_set: Default::default(),
};
intravisit::walk_crate(&mut visitor, krate);
tcx.hir().walk_toplevel_module(&mut visitor);
let has_pub_restricted = {
let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false };
intravisit::walk_crate(&mut pub_restricted_visitor, krate);
tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor);
pub_restricted_visitor.has_pub_restricted
};

View File

@ -1122,7 +1122,7 @@ impl<'tcx> DumpVisitor<'tcx> {
attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
},
);
intravisit::walk_crate(self, krate);
self.tcx.hir().walk_toplevel_module(self);
}
fn process_bounds(&mut self, bounds: hir::GenericBounds<'tcx>) {

View File

@ -6,8 +6,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Namespace, Res};
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc_hir::intravisit;
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::lang_items::LangItem;
use rustc_hir::{ExprKind, Node, QPath};
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
@ -1011,9 +1010,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
candidates: Vec<DefId>,
) {
let module_did = self.tcx.parent_module(self.body_id);
let module_id = self.tcx.hir().local_def_id_to_hir_id(module_did);
let krate = self.tcx.hir().krate();
let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
let (span, found_use) = find_use_placement(self.tcx, module_did);
if let Some(span) = span {
let path_strings = candidates.iter().map(|did| {
// Produce an additional newline to separate the new use statement
@ -1606,64 +1603,38 @@ pub fn provide(providers: &mut ty::query::Providers) {
providers.all_traits = compute_all_traits;
}
struct UsePlacementFinder<'tcx> {
target_module: hir::HirId,
span: Option<Span>,
found_use: bool,
tcx: TyCtxt<'tcx>,
}
fn find_use_placement<'tcx>(tcx: TyCtxt<'tcx>, target_module: LocalDefId) -> (Option<Span>, bool) {
let mut span = None;
let mut found_use = false;
let (module, _, _) = tcx.hir().get_module(target_module);
impl UsePlacementFinder<'tcx> {
fn check(
tcx: TyCtxt<'tcx>,
krate: &'tcx hir::Crate<'tcx>,
target_module: hir::HirId,
) -> (Option<Span>, bool) {
let mut finder = UsePlacementFinder { target_module, span: None, found_use: false, tcx };
intravisit::walk_crate(&mut finder, krate);
(finder.span, finder.found_use)
}
}
impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> {
fn visit_mod(&mut self, module: &'tcx hir::Mod<'tcx>, _: Span, hir_id: hir::HirId) {
if self.span.is_some() {
return;
}
if hir_id != self.target_module {
intravisit::walk_mod(self, module, hir_id);
return;
}
// Find a `use` statement.
for &item_id in module.item_ids {
let item = self.tcx.hir().item(item_id);
match item.kind {
hir::ItemKind::Use(..) => {
// Don't suggest placing a `use` before the prelude
// import or other generated ones.
if !item.span.from_expansion() {
self.span = Some(item.span.shrink_to_lo());
self.found_use = true;
return;
}
// Find a `use` statement.
for &item_id in module.item_ids {
let item = tcx.hir().item(item_id);
match item.kind {
hir::ItemKind::Use(..) => {
// Don't suggest placing a `use` before the prelude
// import or other generated ones.
if !item.span.from_expansion() {
span = Some(item.span.shrink_to_lo());
found_use = true;
break;
}
// Don't place `use` before `extern crate`...
hir::ItemKind::ExternCrate(_) => {}
// ...but do place them before the first other item.
_ => {
if self.span.map_or(true, |span| item.span < span) {
if !item.span.from_expansion() {
self.span = Some(item.span.shrink_to_lo());
// Don't insert between attributes and an item.
let attrs = self.tcx.hir().attrs(item.hir_id());
// Find the first attribute on the item.
// FIXME: This is broken for active attributes.
for attr in attrs {
if !attr.span.is_dummy()
&& self.span.map_or(true, |span| attr.span < span)
{
self.span = Some(attr.span.shrink_to_lo());
}
}
// Don't place `use` before `extern crate`...
hir::ItemKind::ExternCrate(_) => {}
// ...but do place them before the first other item.
_ => {
if span.map_or(true, |span| item.span < span) {
if !item.span.from_expansion() {
span = Some(item.span.shrink_to_lo());
// Don't insert between attributes and an item.
let attrs = tcx.hir().attrs(item.hir_id());
// Find the first attribute on the item.
// FIXME: This is broken for active attributes.
for attr in attrs {
if !attr.span.is_dummy() && span.map_or(true, |span| attr.span < span) {
span = Some(attr.span.shrink_to_lo());
}
}
}
@ -1672,11 +1643,7 @@ impl intravisit::Visitor<'tcx> for UsePlacementFinder<'tcx> {
}
}
type Map = intravisit::ErasedMap<'tcx>;
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
intravisit::NestedVisitorMap::None
}
(span, found_use)
}
fn print_disambiguation_help(

View File

@ -691,7 +691,7 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
debug!("find_opaque_ty_constraints: scope={:?}", scope);
if scope == hir::CRATE_HIR_ID {
intravisit::walk_crate(&mut locator, tcx.hir().krate());
tcx.hir().walk_toplevel_module(&mut locator);
} else {
debug!("find_opaque_ty_constraints: scope={:?}", tcx.hir().get(scope));
match tcx.hir().get(scope) {

View File

@ -116,7 +116,6 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
let mut global_ctxt = queries.global_ctxt()?.take();
let collector = global_ctxt.enter(|tcx| {
let krate = tcx.hir().krate();
let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID);
let mut opts = scrape_test_config(crate_attrs);
@ -144,10 +143,8 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
hir_collector.visit_testable(
"".to_string(),
CRATE_HIR_ID,
krate.module().inner,
|this| {
intravisit::walk_crate(this, krate);
},
tcx.hir().span(CRATE_HIR_ID),
|this| tcx.hir().walk_toplevel_module(this),
);
collector

View File

@ -45,7 +45,7 @@ crate fn collect_spans_and_sources(
if include_sources {
if generate_link_to_definition {
intravisit::walk_crate(&mut visitor, tcx.hir().krate());
tcx.hir().walk_toplevel_module(&mut visitor);
}
let (krate, sources) = sources::collect_local_sources(tcx, src_root, krate);
(krate, sources, visitor.matches)

View File

@ -5,8 +5,10 @@ LL | s.the_fn();
| ^^^^^^ method not found in `&TheStruct`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use Lib::TheTrait;`
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use Lib::TheTrait;
|
error: aborting due to previous error

View File

@ -5,8 +5,10 @@ LL | s.the_fn();
| ^^^^^^ method not found in `&TheStruct`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use coherence_inherent_cc_lib::TheTrait;`
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use coherence_inherent_cc_lib::TheTrait;
|
error: aborting due to previous error

View File

@ -23,9 +23,11 @@ LL | ().clone()
| ^^^^^ method not found in `()`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use std::clone::Clone;`
= note: this error originates in the macro `::bar::m` (in Nightly builds, run with -Z macro-backtrace for more info)
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use std::clone::Clone;
|
error: aborting due to 2 previous errors

View File

@ -11,9 +11,11 @@ LL | pub macro m() { ().f() }
| ^ method not found in `()`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use foo::T;`
= note: this error originates in the macro `::baz::m` (in Nightly builds, run with -Z macro-backtrace for more info)
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use foo::T;
|
error: aborting due to previous error

View File

@ -5,8 +5,10 @@ LL | b.foo();
| ^^^ method not found in `&B`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use a::A;`
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use a::A;
|
error: aborting due to previous error

View File

@ -8,8 +8,10 @@ LL | x.foobar();
| ^^^^^^ method not found in `u32`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use crate::foo::foobar::Foobar;`
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use crate::foo::foobar::Foobar;
|
error[E0599]: no method named `bar` found for type `u32` in the current scope
--> $DIR/trait-import-suggestions.rs:28:7

View File

@ -15,9 +15,6 @@ LL | fn try_into(self) -> Result<T, Self::Error>;
| the method is available for `Rc<u8>` here
|
= help: items from traits can only be used if the trait is in scope
= note: the following traits are implemented but not in scope; perhaps add a `use` for one of them:
candidate #1: `use crate::m::TryIntoU32;`
candidate #2: `use std::convert::TryInto;`
help: consider wrapping the receiver expression with the appropriate type
|
LL | let _: u32 = Box::new(3u8).try_into().unwrap();
@ -34,6 +31,12 @@ help: consider wrapping the receiver expression with the appropriate type
|
LL | let _: u32 = Rc::new(3u8).try_into().unwrap();
| ++++++++ +
help: the following traits are implemented but not in scope; perhaps add a `use` for one of them:
|
LL | use crate::m::TryIntoU32;
|
LL | use std::convert::TryInto;
|
error: aborting due to previous error

View File

@ -5,8 +5,10 @@ LL | x.deref();
| ^^^^^ method not found in `&()`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use std::ops::Deref;`
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
LL | use std::ops::Deref;
|
error: aborting due to previous error