Skip to content

Commit 89baf0f

Browse files
authored
Rollup merge of #91526 - petrochenkov:earlint, r=cjgillot
rustc_lint: Some early linting refactorings The first one removes and renames some fields and methods from `EarlyContext`. The second one uses the set of registered tools (for tool attributes and tool lints) in a more centralized way. The third one removes creation of a fake `ast::Crate` from `fn pre_expansion_lint`. Pre-expansion linting is done with per-module granularity on freshly loaded modules, and it previously synthesized an `ast::Crate` to visit non-root modules, now they are visited as modules. The node ID used for pre-expansion linting is also made more precise (the loaded module ID is used).
2 parents 84322ef + 67cccaf commit 89baf0f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+285
-229
lines changed

compiler/rustc_expand/src/base.rs

+22-10
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream};
88
use rustc_ast::visit::{AssocCtxt, Visitor};
99
use rustc_ast::{self as ast, AstLike, Attribute, Item, NodeId, PatKind};
1010
use rustc_attr::{self as attr, Deprecation, Stability};
11-
use rustc_data_structures::fx::FxHashMap;
11+
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1212
use rustc_data_structures::sync::{self, Lrc};
1313
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorReported};
1414
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
@@ -920,8 +920,25 @@ pub trait ResolverExpand {
920920
/// we generated proc macros harnesses, so that we can map
921921
/// HIR proc macros items back to their harness items.
922922
fn declare_proc_macro(&mut self, id: NodeId);
923+
924+
/// Tools registered with `#![register_tool]` and used by tool attributes and lints.
925+
fn registered_tools(&self) -> &FxHashSet<Ident>;
923926
}
924927

928+
pub trait LintStoreExpand {
929+
fn pre_expansion_lint(
930+
&self,
931+
sess: &Session,
932+
registered_tools: &FxHashSet<Ident>,
933+
node_id: NodeId,
934+
attrs: &[Attribute],
935+
items: &[P<Item>],
936+
name: &str,
937+
);
938+
}
939+
940+
type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
941+
925942
#[derive(Clone, Default)]
926943
pub struct ModuleData {
927944
/// Path to the module starting from the crate name, like `my_crate::foo::bar`.
@@ -956,9 +973,6 @@ pub struct ExpansionData {
956973
pub is_trailing_mac: bool,
957974
}
958975

959-
type OnExternModLoaded<'a> =
960-
Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
961-
962976
/// One of these is made during expansion and incrementally updated as we go;
963977
/// when a macro expansion occurs, the resulting nodes have the `backtrace()
964978
/// -> expn_data` of their expansion context stored into their span.
@@ -973,10 +987,8 @@ pub struct ExtCtxt<'a> {
973987
/// (or during eager expansion, but that's a hack).
974988
pub force_mode: bool,
975989
pub expansions: FxHashMap<Span, Vec<String>>,
976-
/// Called directly after having parsed an external `mod foo;` in expansion.
977-
///
978-
/// `Ident` is the module name.
979-
pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
990+
/// Used for running pre-expansion lints on freshly loaded modules.
991+
pub(super) lint_store: LintStoreExpandDyn<'a>,
980992
/// When we 'expand' an inert attribute, we leave it
981993
/// in the AST, but insert it here so that we know
982994
/// not to expand it again.
@@ -988,14 +1000,14 @@ impl<'a> ExtCtxt<'a> {
9881000
sess: &'a Session,
9891001
ecfg: expand::ExpansionConfig<'a>,
9901002
resolver: &'a mut dyn ResolverExpand,
991-
extern_mod_loaded: OnExternModLoaded<'a>,
1003+
lint_store: LintStoreExpandDyn<'a>,
9921004
) -> ExtCtxt<'a> {
9931005
ExtCtxt {
9941006
sess,
9951007
ecfg,
9961008
reduced_recursion_limit: None,
9971009
resolver,
998-
extern_mod_loaded,
1010+
lint_store,
9991011
root_path: PathBuf::new(),
10001012
current_expansion: ExpansionData {
10011013
id: LocalExpnId::ROOT,

compiler/rustc_expand/src/expand.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -1097,7 +1097,7 @@ impl InvocationCollectorNode for P<ast::Item> {
10971097
ModKind::Unloaded => {
10981098
// We have an outline `mod foo;` so we need to parse the file.
10991099
let old_attrs_len = attrs.len();
1100-
let ParsedExternalMod { mut items, inner_span, file_path, dir_path, dir_ownership } =
1100+
let ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership } =
11011101
parse_external_mod(
11021102
&ecx.sess,
11031103
ident,
@@ -1107,8 +1107,15 @@ impl InvocationCollectorNode for P<ast::Item> {
11071107
&mut attrs,
11081108
);
11091109

1110-
if let Some(extern_mod_loaded) = ecx.extern_mod_loaded {
1111-
(attrs, items) = extern_mod_loaded(ident, attrs, items, inner_span);
1110+
if let Some(lint_store) = ecx.lint_store {
1111+
lint_store.pre_expansion_lint(
1112+
ecx.sess,
1113+
ecx.resolver.registered_tools(),
1114+
ecx.current_expansion.lint_node_id,
1115+
&attrs,
1116+
&items,
1117+
ident.name.as_str(),
1118+
);
11121119
}
11131120

11141121
*mod_kind = ModKind::Loaded(items, Inline::No, inner_span);

compiler/rustc_interface/src/passes.rs

+40-27
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,24 @@ use crate::proc_macro_decls;
33
use crate::util;
44

55
use rustc_ast::mut_visit::MutVisitor;
6-
use rustc_ast::{self as ast, visit, DUMMY_NODE_ID};
6+
use rustc_ast::{self as ast, visit};
77
use rustc_borrowck as mir_borrowck;
88
use rustc_codegen_ssa::back::link::emit_metadata;
99
use rustc_codegen_ssa::traits::CodegenBackend;
1010
use rustc_data_structures::parallel;
1111
use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
1212
use rustc_data_structures::temp_dir::MaybeTempDir;
1313
use rustc_errors::{Applicability, ErrorReported, PResult};
14-
use rustc_expand::base::ExtCtxt;
14+
use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand};
1515
use rustc_hir::def_id::{StableCrateId, LOCAL_CRATE};
1616
use rustc_hir::Crate;
17-
use rustc_lint::LintStore;
17+
use rustc_lint::{EarlyCheckNode, LintStore};
1818
use rustc_metadata::creader::CStore;
1919
use rustc_metadata::{encode_metadata, EncodedMetadata};
2020
use rustc_middle::arena::Arena;
2121
use rustc_middle::dep_graph::DepGraph;
2222
use rustc_middle::ty::query::{ExternProviders, Providers};
23-
use rustc_middle::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
23+
use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, ResolverOutputs, TyCtxt};
2424
use rustc_mir_build as mir_build;
2525
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr};
2626
use rustc_passes::{self, hir_stats, layout_test};
@@ -34,7 +34,7 @@ use rustc_session::lint;
3434
use rustc_session::output::{filename_for_input, filename_for_metadata};
3535
use rustc_session::search_paths::PathKind;
3636
use rustc_session::{Limit, Session};
37-
use rustc_span::symbol::{sym, Ident, Symbol};
37+
use rustc_span::symbol::{sym, Symbol};
3838
use rustc_span::{FileName, MultiSpan};
3939
use rustc_trait_selection::traits;
4040
use rustc_typeck as typeck;
@@ -233,26 +233,43 @@ pub fn register_plugins<'a>(
233233
Ok((krate, lint_store))
234234
}
235235

236-
fn pre_expansion_lint(
236+
fn pre_expansion_lint<'a>(
237237
sess: &Session,
238238
lint_store: &LintStore,
239-
krate: &ast::Crate,
240-
crate_attrs: &[ast::Attribute],
241-
crate_name: &str,
239+
registered_tools: &RegisteredTools,
240+
check_node: impl EarlyCheckNode<'a>,
241+
node_name: &str,
242242
) {
243-
sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", crate_name).run(|| {
244-
rustc_lint::check_ast_crate(
243+
sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name).run(|| {
244+
rustc_lint::check_ast_node(
245245
sess,
246-
lint_store,
247-
krate,
248-
crate_attrs,
249246
true,
247+
lint_store,
248+
registered_tools,
250249
None,
251250
rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
251+
check_node,
252252
);
253253
});
254254
}
255255

256+
// Cannot implement directly for `LintStore` due to trait coherence.
257+
struct LintStoreExpandImpl<'a>(&'a LintStore);
258+
259+
impl LintStoreExpand for LintStoreExpandImpl<'_> {
260+
fn pre_expansion_lint(
261+
&self,
262+
sess: &Session,
263+
registered_tools: &RegisteredTools,
264+
node_id: ast::NodeId,
265+
attrs: &[ast::Attribute],
266+
items: &[rustc_ast::ptr::P<ast::Item>],
267+
name: &str,
268+
) {
269+
pre_expansion_lint(sess, self.0, registered_tools, (node_id, attrs, items), name);
270+
}
271+
}
272+
256273
/// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
257274
/// syntax expansion, secondary `cfg` expansion, synthesis of a test
258275
/// harness if one is to be provided, injection of a dependency on the
@@ -265,7 +282,7 @@ pub fn configure_and_expand(
265282
resolver: &mut Resolver<'_>,
266283
) -> Result<ast::Crate> {
267284
tracing::trace!("configure_and_expand");
268-
pre_expansion_lint(sess, lint_store, &krate, &krate.attrs, crate_name);
285+
pre_expansion_lint(sess, lint_store, resolver.registered_tools(), &krate, crate_name);
269286
rustc_builtin_macros::register_builtin_macros(resolver);
270287

271288
krate = sess.time("crate_injection", || {
@@ -321,13 +338,8 @@ pub fn configure_and_expand(
321338
..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string())
322339
};
323340

324-
let crate_attrs = krate.attrs.clone();
325-
let extern_mod_loaded = |ident: Ident, attrs, items, span| {
326-
let krate = ast::Crate { attrs, items, span, id: DUMMY_NODE_ID, is_placeholder: false };
327-
pre_expansion_lint(sess, lint_store, &krate, &crate_attrs, ident.name.as_str());
328-
(krate.attrs, krate.items)
329-
};
330-
let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&extern_mod_loaded));
341+
let lint_store = LintStoreExpandImpl(lint_store);
342+
let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
331343

332344
// Expand macros now!
333345
let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
@@ -499,14 +511,15 @@ pub fn lower_to_hir<'res, 'tcx>(
499511
);
500512

501513
sess.time("early_lint_checks", || {
502-
rustc_lint::check_ast_crate(
514+
let lint_buffer = Some(std::mem::take(resolver.lint_buffer()));
515+
rustc_lint::check_ast_node(
503516
sess,
504-
lint_store,
505-
&krate,
506-
&krate.attrs,
507517
false,
508-
Some(std::mem::take(resolver.lint_buffer())),
518+
lint_store,
519+
resolver.registered_tools(),
520+
lint_buffer,
509521
rustc_lint::BuiltinCombinedEarlyLintPass::new(),
522+
&*krate,
510523
)
511524
});
512525

compiler/rustc_lint/src/builtin.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -912,7 +912,7 @@ declare_lint_pass!(
912912

913913
impl EarlyLintPass for AnonymousParameters {
914914
fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
915-
if cx.sess.edition() != Edition::Edition2015 {
915+
if cx.sess().edition() != Edition::Edition2015 {
916916
// This is a hard error in future editions; avoid linting and erroring
917917
return;
918918
}
@@ -921,7 +921,7 @@ impl EarlyLintPass for AnonymousParameters {
921921
if let ast::PatKind::Ident(_, ident, None) = arg.pat.kind {
922922
if ident.name == kw::Empty {
923923
cx.struct_span_lint(ANONYMOUS_PARAMETERS, arg.pat.span, |lint| {
924-
let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span);
924+
let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
925925

926926
let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
927927
(snip.as_str(), Applicability::MachineApplicable)
@@ -1775,7 +1775,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns {
17751775
};
17761776
if join.edition() >= Edition::Edition2021 {
17771777
let mut err =
1778-
rustc_errors::struct_span_err!(cx.sess, pat.span, E0783, "{}", msg,);
1778+
rustc_errors::struct_span_err!(cx.sess(), pat.span, E0783, "{}", msg,);
17791779
err.span_suggestion(
17801780
pat.span,
17811781
suggestion,
@@ -1799,7 +1799,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns {
17991799
let replace = "..=".to_owned();
18001800
if join.edition() >= Edition::Edition2021 {
18011801
let mut err =
1802-
rustc_errors::struct_span_err!(cx.sess, pat.span, E0783, "{}", msg,);
1802+
rustc_errors::struct_span_err!(cx.sess(), pat.span, E0783, "{}", msg,);
18031803
err.span_suggestion_short(
18041804
join,
18051805
suggestion,
@@ -1983,7 +1983,7 @@ impl KeywordIdents {
19831983
UnderMacro(under_macro): UnderMacro,
19841984
ident: Ident,
19851985
) {
1986-
let next_edition = match cx.sess.edition() {
1986+
let next_edition = match cx.sess().edition() {
19871987
Edition::Edition2015 => {
19881988
match ident.name {
19891989
kw::Async | kw::Await | kw::Try => Edition::Edition2018,
@@ -2011,7 +2011,7 @@ impl KeywordIdents {
20112011
};
20122012

20132013
// Don't lint `r#foo`.
2014-
if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
2014+
if cx.sess().parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
20152015
return;
20162016
}
20172017

@@ -2379,7 +2379,7 @@ declare_lint_pass!(
23792379

23802380
impl EarlyLintPass for IncompleteFeatures {
23812381
fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2382-
let features = cx.sess.features_untracked();
2382+
let features = cx.sess().features_untracked();
23832383
features
23842384
.declared_lang_features
23852385
.iter()

0 commit comments

Comments
 (0)