Skip to content

Commit 577a76f

Browse files
committed
Auto merge of #88597 - cjgillot:lower-global, r=petrochenkov
Move global analyses from lowering to resolution Split off #87234 r? `@petrochenkov`
2 parents c5799b2 + 5e3cd6a commit 577a76f

File tree

33 files changed

+231
-279
lines changed

33 files changed

+231
-279
lines changed

compiler/rustc_ast/src/ast.rs

-7
Original file line numberDiff line numberDiff line change
@@ -502,13 +502,6 @@ pub struct Crate {
502502
pub attrs: Vec<Attribute>,
503503
pub items: Vec<P<Item>>,
504504
pub span: Span,
505-
/// The order of items in the HIR is unrelated to the order of
506-
/// items in the AST. However, we generate proc macro harnesses
507-
/// based on the AST order, and later refer to these harnesses
508-
/// from the HIR. This field keeps track of the order in which
509-
/// we generated proc macros harnesses, so that we can map
510-
/// HIR proc macros items back to their harness items.
511-
pub proc_macros: Vec<NodeId>,
512505
}
513506

514507
/// Possible values inside of compile-time attribute lists.

compiler/rustc_ast/src/mut_visit.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -1059,7 +1059,7 @@ pub fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) {
10591059
// FIXME: Avoid visiting the crate as a `Mod` item, flat map only the inner items if possible,
10601060
// or make crate visiting first class if necessary.
10611061
pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) {
1062-
visit_clobber(krate, |Crate { attrs, items, span, proc_macros }| {
1062+
visit_clobber(krate, |Crate { attrs, items, span }| {
10631063
let item_vis =
10641064
Visibility { kind: VisibilityKind::Public, span: span.shrink_to_lo(), tokens: None };
10651065
let item = P(Item {
@@ -1075,13 +1075,11 @@ pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) {
10751075

10761076
let len = items.len();
10771077
if len == 0 {
1078-
Crate { attrs: vec![], items: vec![], span, proc_macros }
1078+
Crate { attrs: vec![], items: vec![], span }
10791079
} else if len == 1 {
10801080
let Item { attrs, span, kind, .. } = items.into_iter().next().unwrap().into_inner();
10811081
match kind {
1082-
ItemKind::Mod(_, ModKind::Loaded(items, ..)) => {
1083-
Crate { attrs, items, span, proc_macros }
1084-
}
1082+
ItemKind::Mod(_, ModKind::Loaded(items, ..)) => Crate { attrs, items, span },
10851083
_ => panic!("visitor converted a module to not a module"),
10861084
}
10871085
} else {

compiler/rustc_ast_lowering/src/item.rs

-9
Original file line numberDiff line numberDiff line change
@@ -378,15 +378,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
378378
this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed())
379379
});
380380

381-
if let Some(ref trait_ref) = trait_ref {
382-
if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res {
383-
this.trait_impls
384-
.entry(def_id)
385-
.or_default()
386-
.push(lowered_trait_def_id);
387-
}
388-
}
389-
390381
let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed());
391382

392383
(trait_ref, lowered_ty)

compiler/rustc_ast_lowering/src/lib.rs

+4-61
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ use rustc_ast::node_id::NodeMap;
3939
use rustc_ast::token::{self, Token};
4040
use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream, TokenTree};
4141
use rustc_ast::visit::{self, AssocCtxt, Visitor};
42-
use rustc_ast::walk_list;
4342
use rustc_ast::{self as ast, *};
4443
use rustc_ast_pretty::pprust;
4544
use rustc_data_structures::captures::Captures;
@@ -48,7 +47,7 @@ use rustc_data_structures::sync::Lrc;
4847
use rustc_errors::{struct_span_err, Applicability};
4948
use rustc_hir as hir;
5049
use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res};
51-
use rustc_hir::def_id::{DefId, DefIdMap, DefPathHash, LocalDefId, CRATE_DEF_ID};
50+
use rustc_hir::def_id::{DefId, DefPathHash, LocalDefId, CRATE_DEF_ID};
5251
use rustc_hir::definitions::{DefKey, DefPathData, Definitions};
5352
use rustc_hir::intravisit;
5453
use rustc_hir::{ConstArg, GenericArg, InferKind, ParamName};
@@ -104,8 +103,6 @@ struct LoweringContext<'a, 'hir: 'a> {
104103
owners: IndexVec<LocalDefId, Option<hir::OwnerNode<'hir>>>,
105104
bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
106105

107-
trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
108-
109106
modules: BTreeMap<LocalDefId, hir::ModuleItems>,
110107

111108
generator_kind: Option<hir::GeneratorKind>,
@@ -158,8 +155,6 @@ struct LoweringContext<'a, 'hir: 'a> {
158155

159156
current_module: LocalDefId,
160157

161-
type_def_lifetime_params: DefIdMap<usize>,
162-
163158
current_hir_id_owner: (LocalDefId, u32),
164159
item_local_id_counters: NodeMap<u32>,
165160
node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
@@ -171,7 +166,7 @@ struct LoweringContext<'a, 'hir: 'a> {
171166
pub trait ResolverAstLowering {
172167
fn def_key(&mut self, id: DefId) -> DefKey;
173168

174-
fn item_generics_num_lifetimes(&self, def: DefId, sess: &Session) -> usize;
169+
fn item_generics_num_lifetimes(&self, def: DefId) -> usize;
175170

176171
fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>>;
177172

@@ -326,7 +321,6 @@ pub fn lower_crate<'a, 'hir>(
326321
arena,
327322
owners: IndexVec::default(),
328323
bodies: BTreeMap::new(),
329-
trait_impls: BTreeMap::new(),
330324
modules: BTreeMap::new(),
331325
attrs: BTreeMap::default(),
332326
catch_scopes: Vec::new(),
@@ -335,7 +329,6 @@ pub fn lower_crate<'a, 'hir>(
335329
is_in_trait_impl: false,
336330
is_in_dyn_type: false,
337331
anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
338-
type_def_lifetime_params: Default::default(),
339332
current_module: CRATE_DEF_ID,
340333
current_hir_id_owner: (CRATE_DEF_ID, 0),
341334
item_local_id_counters: Default::default(),
@@ -451,26 +444,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
451444
fn visit_item(&mut self, item: &'tcx Item) {
452445
self.lctx.allocate_hir_id_counter(item.id);
453446

454-
match item.kind {
455-
ItemKind::Struct(_, ref generics)
456-
| ItemKind::Union(_, ref generics)
457-
| ItemKind::Enum(_, ref generics)
458-
| ItemKind::TyAlias(box TyAliasKind(_, ref generics, ..))
459-
| ItemKind::Trait(box TraitKind(_, _, ref generics, ..)) => {
460-
let def_id = self.lctx.resolver.local_def_id(item.id);
461-
let count = generics
462-
.params
463-
.iter()
464-
.filter(|param| {
465-
matches!(param.kind, ast::GenericParamKind::Lifetime { .. })
466-
})
467-
.count();
468-
self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
469-
}
470-
ItemKind::Use(ref use_tree) => {
471-
self.allocate_use_tree_hir_id_counters(use_tree);
472-
}
473-
_ => {}
447+
if let ItemKind::Use(ref use_tree) = item.kind {
448+
self.allocate_use_tree_hir_id_counters(use_tree);
474449
}
475450

476451
visit::walk_item(self, item);
@@ -485,23 +460,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
485460
self.lctx.allocate_hir_id_counter(item.id);
486461
visit::walk_foreign_item(self, item);
487462
}
488-
489-
fn visit_ty(&mut self, t: &'tcx Ty) {
490-
match t.kind {
491-
// Mirrors the case in visit::walk_ty
492-
TyKind::BareFn(ref f) => {
493-
walk_list!(self, visit_generic_param, &f.generic_params);
494-
// Mirrors visit::walk_fn_decl
495-
for parameter in &f.decl.inputs {
496-
// We don't lower the ids of argument patterns
497-
self.visit_pat(&parameter.pat);
498-
self.visit_ty(&parameter.ty)
499-
}
500-
self.visit_fn_ret_ty(&f.decl.output)
501-
}
502-
_ => visit::walk_ty(self, t),
503-
}
504-
}
505463
}
506464

507465
self.lower_node_id(CRATE_NODE_ID);
@@ -515,10 +473,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
515473
self.owners.ensure_contains_elem(CRATE_DEF_ID, || None);
516474
self.owners[CRATE_DEF_ID] = Some(hir::OwnerNode::Crate(module));
517475

518-
let body_ids = body_ids(&self.bodies);
519-
let proc_macros =
520-
c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
521-
522476
let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
523477
for (k, v) in self.resolver.take_trait_map().into_iter() {
524478
if let Some(Some(hir_id)) = self.node_id_to_hir_id.get(k) {
@@ -551,10 +505,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
551505
let krate = hir::Crate {
552506
owners: self.owners,
553507
bodies: self.bodies,
554-
body_ids,
555-
trait_impls: self.trait_impls,
556508
modules: self.modules,
557-
proc_macros,
558509
trait_map,
559510
attrs: self.attrs,
560511
};
@@ -2749,14 +2700,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
27492700
}
27502701
}
27512702

2752-
fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body<'_>>) -> Vec<hir::BodyId> {
2753-
// Sorting by span ensures that we get things in order within a
2754-
// file, and also puts the files in a sensible order.
2755-
let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
2756-
body_ids.sort_by_key(|b| bodies[b].value.span);
2757-
body_ids
2758-
}
2759-
27602703
/// Helper struct for delayed construction of GenericArgs.
27612704
struct GenericArgsCtor<'hir> {
27622705
args: SmallVec<[hir::GenericArg<'hir>; 4]>,

compiler/rustc_ast_lowering/src/path.rs

+2-9
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
9090
_ => ParenthesizedGenericArgs::Err,
9191
};
9292

93-
let num_lifetimes = type_def_id.map_or(0, |def_id| {
94-
if let Some(&n) = self.type_def_lifetime_params.get(&def_id) {
95-
return n;
96-
}
97-
assert!(!def_id.is_local());
98-
let n = self.resolver.item_generics_num_lifetimes(def_id, self.sess);
99-
self.type_def_lifetime_params.insert(def_id, n);
100-
n
101-
});
93+
let num_lifetimes = type_def_id
94+
.map_or(0, |def_id| self.resolver.item_generics_num_lifetimes(def_id));
10295
self.lower_path_segment(
10396
p.span,
10497
segment,

compiler/rustc_builtin_macros/src/proc_macro_harness.rs

+13-23
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use rustc_span::source_map::SourceMap;
1313
use rustc_span::symbol::{kw, sym, Ident, Symbol};
1414
use rustc_span::{Span, DUMMY_SP};
1515
use smallvec::smallvec;
16-
use std::cell::RefCell;
1716

1817
struct ProcMacroDerive {
1918
id: NodeId,
@@ -90,7 +89,7 @@ pub fn inject(
9089
return krate;
9190
}
9291

93-
let decls = mk_decls(&mut krate, &mut cx, &macros);
92+
let decls = mk_decls(&mut cx, &macros);
9493
krate.items.push(decls);
9594

9695
krate
@@ -289,15 +288,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
289288
// // ...
290289
// ];
291290
// }
292-
fn mk_decls(
293-
ast_krate: &mut ast::Crate,
294-
cx: &mut ExtCtxt<'_>,
295-
macros: &[ProcMacro],
296-
) -> P<ast::Item> {
297-
// We're the ones filling in this Vec,
298-
// so it should be empty to start with
299-
assert!(ast_krate.proc_macros.is_empty());
300-
291+
fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
301292
let expn_id = cx.resolver.expansion_for_ast_pass(
302293
DUMMY_SP,
303294
AstPass::ProcMacroHarness,
@@ -316,26 +307,25 @@ fn mk_decls(
316307
let attr = Ident::new(sym::attr, span);
317308
let bang = Ident::new(sym::bang, span);
318309

319-
let krate_ref = RefCell::new(ast_krate);
320-
321-
// We add NodeIds to 'krate.proc_macros' in the order
310+
// We add NodeIds to 'resolver.proc_macros' in the order
322311
// that we generate expressions. The position of each NodeId
323312
// in the 'proc_macros' Vec corresponds to its position
324313
// in the static array that will be generated
325314
let decls = {
326-
let local_path =
327-
|sp: Span, name| cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]));
328-
let proc_macro_ty_method_path = |method| {
315+
let local_path = |cx: &ExtCtxt<'_>, sp: Span, name| {
316+
cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]))
317+
};
318+
let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| {
329319
cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method]))
330320
};
331321
macros
332322
.iter()
333323
.map(|m| match m {
334324
ProcMacro::Derive(cd) => {
335-
krate_ref.borrow_mut().proc_macros.push(cd.id);
325+
cx.resolver.declare_proc_macro(cd.id);
336326
cx.expr_call(
337327
span,
338-
proc_macro_ty_method_path(custom_derive),
328+
proc_macro_ty_method_path(cx, custom_derive),
339329
vec![
340330
cx.expr_str(cd.span, cd.trait_name),
341331
cx.expr_vec_slice(
@@ -345,23 +335,23 @@ fn mk_decls(
345335
.map(|&s| cx.expr_str(cd.span, s))
346336
.collect::<Vec<_>>(),
347337
),
348-
local_path(cd.span, cd.function_name),
338+
local_path(cx, cd.span, cd.function_name),
349339
],
350340
)
351341
}
352342
ProcMacro::Def(ca) => {
353-
krate_ref.borrow_mut().proc_macros.push(ca.id);
343+
cx.resolver.declare_proc_macro(ca.id);
354344
let ident = match ca.def_type {
355345
ProcMacroDefType::Attr => attr,
356346
ProcMacroDefType::Bang => bang,
357347
};
358348

359349
cx.expr_call(
360350
span,
361-
proc_macro_ty_method_path(ident),
351+
proc_macro_ty_method_path(cx, ident),
362352
vec![
363353
cx.expr_str(ca.span, ca.function_name.name),
364-
local_path(ca.span, ca.function_name),
354+
local_path(cx, ca.span, ca.function_name),
365355
],
366356
)
367357
}

compiler/rustc_expand/src/base.rs

+8
Original file line numberDiff line numberDiff line change
@@ -894,6 +894,14 @@ pub trait ResolverExpand {
894894
/// Decodes the proc-macro quoted span in the specified crate, with the specified id.
895895
/// No caching is performed.
896896
fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
897+
898+
/// The order of items in the HIR is unrelated to the order of
899+
/// items in the AST. However, we generate proc macro harnesses
900+
/// based on the AST order, and later refer to these harnesses
901+
/// from the HIR. This field keeps track of the order in which
902+
/// we generated proc macros harnesses, so that we can map
903+
/// HIR proc macros items back to their harness items.
904+
fn declare_proc_macro(&mut self, id: NodeId);
897905
}
898906

899907
#[derive(Clone, Default)]

compiler/rustc_hir/src/hir.rs

-10
Original file line numberDiff line numberDiff line change
@@ -672,20 +672,10 @@ pub struct ModuleItems {
672672
pub struct Crate<'hir> {
673673
pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
674674
pub bodies: BTreeMap<BodyId, Body<'hir>>,
675-
pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
676-
677-
/// A list of the body ids written out in the order in which they
678-
/// appear in the crate. If you're going to process all the bodies
679-
/// in the crate, you should iterate over this list rather than the keys
680-
/// of bodies.
681-
pub body_ids: Vec<BodyId>,
682675

683676
/// A list of modules written out in the order in which they
684677
/// appear in the crate. This includes the main crate module.
685678
pub modules: BTreeMap<LocalDefId, ModuleItems>,
686-
/// A list of proc macro HirIds, written out in the order in which
687-
/// they are declared in the static array generated by proc_macro_harness.
688-
pub proc_macros: Vec<HirId>,
689679

690680
/// Map indicating what traits are in scope for places where this
691681
/// is relevant; generated by resolve.

compiler/rustc_interface/src/passes.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ pub fn configure_and_expand(
324324
};
325325

326326
let extern_mod_loaded = |ident: Ident, attrs, items, span| {
327-
let krate = ast::Crate { attrs, items, span, proc_macros: vec![] };
327+
let krate = ast::Crate { attrs, items, span };
328328
pre_expansion_lint(sess, lint_store, &krate, &ident.name.as_str());
329329
(krate.attrs, krate.items)
330330
};

0 commit comments

Comments
 (0)