Skip to content

Commit df50001

Browse files
authored
Rollup merge of #108806 - cjgillot:query-lints, r=davidtwco
Querify register_tools and post-expansion early lints The 2 extra queries correspond to code that happen before and after macro expansion, and don't need the resolver to exist.
2 parents d7372a1 + c90fc10 commit df50001

File tree

11 files changed

+74
-40
lines changed

11 files changed

+74
-40
lines changed

compiler/rustc_ast_lowering/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ fn compute_hir_hash(
436436
pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
437437
let sess = tcx.sess;
438438
tcx.ensure().output_filenames(());
439+
let _ = tcx.early_lint_checks(()); // Borrows `resolver_for_lowering`.
439440
let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal();
440441

441442
let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);

compiler/rustc_driver_impl/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ fn run_compiler(
331331
if let Some(ppm) = &sess.opts.pretty {
332332
if ppm.needs_ast_map() {
333333
queries.global_ctxt()?.enter(|tcx| {
334+
tcx.ensure().early_lint_checks(());
334335
pretty::print_after_hir_lowering(tcx, *ppm);
335336
Ok(())
336337
})?;

compiler/rustc_expand/src/base.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ use rustc_ast::tokenstream::TokenStream;
1212
use rustc_ast::visit::{AssocCtxt, Visitor};
1313
use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
1414
use rustc_attr::{self as attr, Deprecation, Stability};
15-
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
15+
use rustc_data_structures::fx::FxIndexMap;
1616
use rustc_data_structures::sync::{self, Lrc};
1717
use rustc_errors::{
1818
Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
1919
};
2020
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
21-
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
21+
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools};
2222
use rustc_parse::{self, parser, MACRO_ARGUMENTS};
2323
use rustc_session::errors::report_lit_error;
2424
use rustc_session::{parse::ParseSess, Limit, Session};
@@ -947,14 +947,14 @@ pub trait ResolverExpand {
947947
fn declare_proc_macro(&mut self, id: NodeId);
948948

949949
/// Tools registered with `#![register_tool]` and used by tool attributes and lints.
950-
fn registered_tools(&self) -> &FxHashSet<Ident>;
950+
fn registered_tools(&self) -> &RegisteredTools;
951951
}
952952

953953
pub trait LintStoreExpand {
954954
fn pre_expansion_lint(
955955
&self,
956956
sess: &Session,
957-
registered_tools: &FxHashSet<Ident>,
957+
registered_tools: &RegisteredTools,
958958
node_id: NodeId,
959959
attrs: &[Attribute],
960960
items: &[P<Item>],

compiler/rustc_interface/src/passes.rs

+26-19
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_data_structures::parallel;
1111
use rustc_data_structures::steal::Steal;
1212
use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
1313
use rustc_errors::PResult;
14-
use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand};
14+
use rustc_expand::base::{ExtCtxt, LintStoreExpand};
1515
use rustc_hir::def_id::{StableCrateId, LOCAL_CRATE};
1616
use rustc_lint::{unerased_lint_store, BufferedEarlyLint, EarlyCheckNode, LintStore};
1717
use rustc_metadata::creader::CStore;
@@ -178,7 +178,7 @@ fn configure_and_expand(mut krate: ast::Crate, resolver: &mut Resolver<'_, '_>)
178178
let sess = tcx.sess;
179179
let lint_store = unerased_lint_store(tcx);
180180
let crate_name = tcx.crate_name(LOCAL_CRATE);
181-
pre_expansion_lint(sess, lint_store, resolver.registered_tools(), &krate, crate_name);
181+
pre_expansion_lint(sess, lint_store, tcx.registered_tools(()), &krate, crate_name);
182182
rustc_builtin_macros::register_builtin_macros(resolver);
183183

184184
krate = sess.time("crate_injection", || {
@@ -302,6 +302,16 @@ fn configure_and_expand(mut krate: ast::Crate, resolver: &mut Resolver<'_, '_>)
302302

303303
// Done with macro expansion!
304304

305+
resolver.resolve_crate(&krate);
306+
307+
krate
308+
}
309+
310+
fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
311+
let sess = tcx.sess;
312+
let (resolver, krate) = &*tcx.resolver_for_lowering(()).borrow();
313+
let mut lint_buffer = resolver.lint_buffer.steal();
314+
305315
if sess.opts.unstable_opts.input_stats {
306316
eprintln!("Post-expansion node count: {}", count_nodes(&krate));
307317
}
@@ -310,8 +320,6 @@ fn configure_and_expand(mut krate: ast::Crate, resolver: &mut Resolver<'_, '_>)
310320
hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS", "ast-stats-2");
311321
}
312322

313-
resolver.resolve_crate(&krate);
314-
315323
// Needs to go *after* expansion to be able to check the results of macro expansion.
316324
sess.time("complete_gated_feature_checking", || {
317325
rustc_ast_passes::feature_gate::check_crate(&krate, sess);
@@ -321,7 +329,7 @@ fn configure_and_expand(mut krate: ast::Crate, resolver: &mut Resolver<'_, '_>)
321329
sess.parse_sess.buffered_lints.with_lock(|buffered_lints| {
322330
info!("{} parse sess buffered_lints", buffered_lints.len());
323331
for early_lint in buffered_lints.drain(..) {
324-
resolver.lint_buffer().add_early_lint(early_lint);
332+
lint_buffer.add_early_lint(early_lint);
325333
}
326334
});
327335

@@ -340,20 +348,16 @@ fn configure_and_expand(mut krate: ast::Crate, resolver: &mut Resolver<'_, '_>)
340348
}
341349
});
342350

343-
sess.time("early_lint_checks", || {
344-
let lint_buffer = Some(std::mem::take(resolver.lint_buffer()));
345-
rustc_lint::check_ast_node(
346-
sess,
347-
false,
348-
lint_store,
349-
resolver.registered_tools(),
350-
lint_buffer,
351-
rustc_lint::BuiltinCombinedEarlyLintPass::new(),
352-
&krate,
353-
)
354-
});
355-
356-
krate
351+
let lint_store = unerased_lint_store(tcx);
352+
rustc_lint::check_ast_node(
353+
sess,
354+
false,
355+
lint_store,
356+
tcx.registered_tools(()),
357+
Some(lint_buffer),
358+
rustc_lint::BuiltinCombinedEarlyLintPass::new(),
359+
&**krate,
360+
)
357361
}
358362

359363
// Returns all the paths that correspond to generated files.
@@ -557,6 +561,7 @@ fn resolver_for_lowering<'tcx>(
557561
(): (),
558562
) -> &'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)> {
559563
let arenas = Resolver::arenas();
564+
let _ = tcx.registered_tools(()); // Uses `crate_for_resolver`.
560565
let krate = tcx.crate_for_resolver(()).steal();
561566
let mut resolver = Resolver::new(tcx, &krate, &arenas);
562567
let krate = configure_and_expand(krate, &mut resolver);
@@ -629,6 +634,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
629634
providers.hir_crate = rustc_ast_lowering::lower_to_hir;
630635
providers.output_filenames = output_filenames;
631636
providers.resolver_for_lowering = resolver_for_lowering;
637+
providers.early_lint_checks = early_lint_checks;
632638
proc_macro_decls::provide(providers);
633639
rustc_const_eval::provide(providers);
634640
rustc_middle::hir::provide(providers);
@@ -637,6 +643,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
637643
rustc_mir_transform::provide(providers);
638644
rustc_monomorphize::provide(providers);
639645
rustc_privacy::provide(providers);
646+
rustc_resolve::provide(providers);
640647
rustc_hir_analysis::provide(providers);
641648
rustc_hir_typeck::provide(providers);
642649
ty::provide(providers);

compiler/rustc_lint/src/levels.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ fn lint_expectations(tcx: TyCtxt<'_>, (): ()) -> Vec<(LintExpectationId, LintExp
128128
},
129129
warn_about_weird_lints: false,
130130
store,
131-
registered_tools: &tcx.resolutions(()).registered_tools,
131+
registered_tools: &tcx.registered_tools(()),
132132
};
133133

134134
builder.add_command_line();
@@ -156,7 +156,7 @@ fn shallow_lint_levels_on(tcx: TyCtxt<'_>, owner: hir::OwnerId) -> ShallowLintLe
156156
},
157157
warn_about_weird_lints: false,
158158
store,
159-
registered_tools: &tcx.resolutions(()).registered_tools,
159+
registered_tools: &tcx.registered_tools(()),
160160
};
161161

162162
if owner == hir::CRATE_OWNER_ID {

compiler/rustc_lint_defs/src/lib.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ extern crate rustc_macros;
88
pub use self::Level::*;
99
use rustc_ast::node_id::NodeId;
1010
use rustc_ast::{AttrId, Attribute};
11-
use rustc_data_structures::fx::FxIndexMap;
11+
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
1212
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
1313
use rustc_error_messages::{DiagnosticMessage, MultiSpan};
1414
use rustc_hir::HashStableContext;
@@ -533,6 +533,7 @@ pub enum BuiltinLintDiagnostics {
533533

534534
/// Lints that are buffered up early on in the `Session` before the
535535
/// `LintLevels` is calculated.
536+
#[derive(Debug)]
536537
pub struct BufferedEarlyLint {
537538
/// The span of code that we are linting on.
538539
pub span: MultiSpan,
@@ -551,7 +552,7 @@ pub struct BufferedEarlyLint {
551552
pub diagnostic: BuiltinLintDiagnostics,
552553
}
553554

554-
#[derive(Default)]
555+
#[derive(Default, Debug)]
555556
pub struct LintBuffer {
556557
pub map: FxIndexMap<NodeId, Vec<BufferedEarlyLint>>,
557558
}
@@ -601,6 +602,8 @@ impl LintBuffer {
601602
}
602603
}
603604

605+
pub type RegisteredTools = FxIndexSet<Ident>;
606+
604607
/// Declares a static item of type `&'static Lint`.
605608
///
606609
/// See <https://rustc-dev-guide.rust-lang.org/diagnostics.html> for

compiler/rustc_middle/src/arena.rs

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ macro_rules! arena_types {
108108
// (during lowering) and the `librustc_middle` arena (for decoding MIR)
109109
[decode] asm_template: rustc_ast::InlineAsmTemplatePiece,
110110
[decode] used_trait_imports: rustc_data_structures::unord::UnordSet<rustc_hir::def_id::LocalDefId>,
111+
[decode] registered_tools: rustc_middle::ty::RegisteredTools,
111112
[decode] is_late_bound_map: rustc_data_structures::fx::FxIndexSet<rustc_hir::ItemLocalId>,
112113
[decode] impl_source: rustc_middle::traits::ImplSource<'tcx, ()>,
113114

compiler/rustc_middle/src/query/mod.rs

+9
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ rustc_queries! {
2626
desc { "triggering a delay span bug" }
2727
}
2828

29+
query registered_tools(_: ()) -> &'tcx ty::RegisteredTools {
30+
arena_cache
31+
desc { "compute registered tools for crate" }
32+
}
33+
34+
query early_lint_checks(_: ()) -> () {
35+
desc { "perform lints prior to macro expansion" }
36+
}
37+
2938
query resolutions(_: ()) -> &'tcx ty::ResolverGlobalCtxt {
3039
feedable
3140
no_hash

compiler/rustc_middle/src/ty/mod.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use rustc_attr as attr;
3434
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
3535
use rustc_data_structures::intern::Interned;
3636
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37+
use rustc_data_structures::steal::Steal;
3738
use rustc_data_structures::tagged_ptr::CopyTaggedPtr;
3839
use rustc_errors::ErrorGuaranteed;
3940
use rustc_hir as hir;
@@ -44,6 +45,8 @@ use rustc_index::vec::IndexVec;
4445
use rustc_macros::HashStable;
4546
use rustc_query_system::ich::StableHashingContext;
4647
use rustc_serialize::{Decodable, Encodable};
48+
use rustc_session::lint::LintBuffer;
49+
pub use rustc_session::lint::RegisteredTools;
4750
use rustc_span::hygiene::MacroKind;
4851
use rustc_span::symbol::{kw, sym, Ident, Symbol};
4952
use rustc_span::{ExpnId, ExpnKind, Span};
@@ -148,8 +151,6 @@ mod typeck_results;
148151

149152
// Data types
150153

151-
pub type RegisteredTools = FxHashSet<Ident>;
152-
153154
pub struct ResolverOutputs {
154155
pub global_ctxt: ResolverGlobalCtxt,
155156
pub ast_lowering: ResolverAstLowering,
@@ -175,7 +176,6 @@ pub struct ResolverGlobalCtxt {
175176
/// Mapping from ident span to path span for paths that don't exist as written, but that
176177
/// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
177178
pub confused_type_with_std_module: FxHashMap<Span, Span>,
178-
pub registered_tools: RegisteredTools,
179179
pub doc_link_resolutions: FxHashMap<LocalDefId, DocLinkResMap>,
180180
pub doc_link_traits_in_scope: FxHashMap<LocalDefId, Vec<DefId>>,
181181
pub all_macro_rules: FxHashMap<Symbol, Res<ast::NodeId>>,
@@ -209,6 +209,9 @@ pub struct ResolverAstLowering {
209209
pub builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
210210
/// List functions and methods for which lifetime elision was successful.
211211
pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
212+
213+
/// Lints that were emitted by the resolver and early lints.
214+
pub lint_buffer: Steal<LintBuffer>,
212215
}
213216

214217
#[derive(Clone, Copy, Debug)]

compiler/rustc_resolve/src/lib.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
2727
use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path};
2828
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
2929
use rustc_data_structures::intern::Interned;
30+
use rustc_data_structures::steal::Steal;
3031
use rustc_data_structures::sync::{Lrc, MappedReadGuard};
3132
use rustc_errors::{
3233
Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, SubdiagnosticMessage,
@@ -965,7 +966,7 @@ pub struct Resolver<'a, 'tcx> {
965966
/// A small map keeping true kinds of built-in macros that appear to be fn-like on
966967
/// the surface (`macro` items in libcore), but are actually attributes or derives.
967968
builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
968-
registered_tools: RegisteredTools,
969+
registered_tools: &'tcx RegisteredTools,
969970
macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
970971
macro_map: FxHashMap<DefId, MacroData>,
971972
dummy_ext_bang: Lrc<SyntaxExtension>,
@@ -1233,7 +1234,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
12331234
}
12341235
}
12351236

1236-
let registered_tools = macros::registered_tools(tcx.sess, &krate.attrs);
1237+
let registered_tools = tcx.registered_tools(());
12371238

12381239
let features = tcx.sess.features_untracked();
12391240

@@ -1408,7 +1409,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14081409
trait_impls: self.trait_impls,
14091410
proc_macros,
14101411
confused_type_with_std_module,
1411-
registered_tools: self.registered_tools,
14121412
doc_link_resolutions: self.doc_link_resolutions,
14131413
doc_link_traits_in_scope: self.doc_link_traits_in_scope,
14141414
all_macro_rules: self.all_macro_rules,
@@ -1426,6 +1426,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14261426
trait_map: self.trait_map,
14271427
builtin_macro_kinds: self.builtin_macro_kinds,
14281428
lifetime_elision_allowed: self.lifetime_elision_allowed,
1429+
lint_buffer: Steal::new(self.lint_buffer),
14291430
};
14301431
ResolverOutputs { global_ctxt, ast_lowering }
14311432
}
@@ -2040,3 +2041,7 @@ impl Finalize {
20402041
Finalize { node_id, path_span, root_span, report_private: true }
20412042
}
20422043
}
2044+
2045+
pub fn provide(providers: &mut ty::query::Providers) {
2046+
providers.registered_tools = macros::registered_tools;
2047+
}

compiler/rustc_resolve/src/macros.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment};
88
use rustc_ast::{self as ast, Inline, ItemKind, ModKind, NodeId};
99
use rustc_ast_pretty::pprust;
1010
use rustc_attr::StabilityLevel;
11-
use rustc_data_structures::fx::FxHashSet;
1211
use rustc_data_structures::intern::Interned;
1312
use rustc_data_structures::sync::Lrc;
1413
use rustc_errors::{struct_span_err, Applicability};
@@ -20,11 +19,11 @@ use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
2019
use rustc_hir::def_id::{CrateNum, LocalDefId};
2120
use rustc_middle::middle::stability;
2221
use rustc_middle::ty::RegisteredTools;
22+
use rustc_middle::ty::TyCtxt;
2323
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
2424
use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
2525
use rustc_session::lint::BuiltinLintDiagnostics;
2626
use rustc_session::parse::feature_err;
27-
use rustc_session::Session;
2827
use rustc_span::edition::Edition;
2928
use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
3029
use rustc_span::hygiene::{AstPass, MacroKind};
@@ -111,23 +110,28 @@ fn fast_print_path(path: &ast::Path) -> Symbol {
111110
}
112111
}
113112

114-
pub(crate) fn registered_tools(sess: &Session, attrs: &[ast::Attribute]) -> FxHashSet<Ident> {
115-
let mut registered_tools = FxHashSet::default();
116-
for attr in sess.filter_by_name(attrs, sym::register_tool) {
113+
pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
114+
let mut registered_tools = RegisteredTools::default();
115+
let krate = tcx.crate_for_resolver(()).borrow();
116+
for attr in tcx.sess.filter_by_name(&krate.attrs, sym::register_tool) {
117117
for nested_meta in attr.meta_item_list().unwrap_or_default() {
118118
match nested_meta.ident() {
119119
Some(ident) => {
120120
if let Some(old_ident) = registered_tools.replace(ident) {
121121
let msg = format!("{} `{}` was already registered", "tool", ident);
122-
sess.struct_span_err(ident.span, &msg)
122+
tcx.sess
123+
.struct_span_err(ident.span, &msg)
123124
.span_label(old_ident.span, "already registered here")
124125
.emit();
125126
}
126127
}
127128
None => {
128129
let msg = format!("`{}` only accepts identifiers", sym::register_tool);
129130
let span = nested_meta.span();
130-
sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
131+
tcx.sess
132+
.struct_span_err(span, &msg)
133+
.span_label(span, "not an identifier")
134+
.emit();
131135
}
132136
}
133137
}

0 commit comments

Comments
 (0)