Skip to content

Commit f8efe5d

Browse files
committed
Compute proc_macros in resolutions.
1 parent 6359780 commit f8efe5d

File tree

12 files changed

+52
-54
lines changed

12 files changed

+52
-54
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/lib.rs

-4
Original file line numberDiff line numberDiff line change
@@ -474,9 +474,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
474474
self.owners.ensure_contains_elem(CRATE_DEF_ID, || None);
475475
self.owners[CRATE_DEF_ID] = Some(hir::OwnerNode::Crate(module));
476476

477-
let proc_macros =
478-
c.proc_macros.iter().map(|id| self.node_id_to_hir_id[*id].unwrap()).collect();
479-
480477
let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
481478
for (k, v) in self.resolver.take_trait_map().into_iter() {
482479
if let Some(Some(hir_id)) = self.node_id_to_hir_id.get(k) {
@@ -510,7 +507,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
510507
owners: self.owners,
511508
bodies: self.bodies,
512509
modules: self.modules,
513-
proc_macros,
514510
trait_map,
515511
attrs: self.attrs,
516512
};

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

-3
Original file line numberDiff line numberDiff line change
@@ -676,9 +676,6 @@ pub struct Crate<'hir> {
676676
/// A list of modules written out in the order in which they
677677
/// appear in the crate. This includes the main crate module.
678678
pub modules: BTreeMap<LocalDefId, ModuleItems>,
679-
/// A list of proc macro HirIds, written out in the order in which
680-
/// they are declared in the static array generated by proc_macro_harness.
681-
pub proc_macros: Vec<HirId>,
682679

683680
/// Map indicating what traits are in scope for places where this
684681
/// 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
};

compiler/rustc_metadata/src/rmeta/encoder.rs

+11-9
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
454454
let table = self.tcx.resolutions(()).definitions.def_path_table();
455455
if self.is_proc_macro {
456456
for def_index in std::iter::once(CRATE_DEF_INDEX)
457-
.chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
457+
.chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
458458
{
459459
let def_key = self.lazy(table.def_key(def_index));
460460
let def_path_hash = self.lazy(table.def_path_hash(def_index));
@@ -1630,7 +1630,8 @@ impl EncodeContext<'a, 'tcx> {
16301630

16311631
let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
16321632
let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1633-
let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1633+
let macros =
1634+
self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
16341635
let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
16351636
for (i, span) in spans.into_iter().enumerate() {
16361637
let span = self.lazy(span);
@@ -1649,13 +1650,14 @@ impl EncodeContext<'a, 'tcx> {
16491650
// Normally, this information is encoded when we walk the items
16501651
// defined in this crate. However, we skip doing that for proc-macro crates,
16511652
// so we manually encode just the information that we need
1652-
for proc_macro in &hir.krate().proc_macros {
1653-
let id = proc_macro.owner.local_def_index;
1654-
let mut name = hir.name(*proc_macro);
1655-
let span = hir.span(*proc_macro);
1653+
for &proc_macro in &tcx.resolutions(()).proc_macros {
1654+
let id = proc_macro;
1655+
let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1656+
let mut name = hir.name(proc_macro);
1657+
let span = hir.span(proc_macro);
16561658
// Proc-macros may have attributes like `#[allow_internal_unstable]`,
16571659
// so downstream crates need access to them.
1658-
let attrs = hir.attrs(*proc_macro);
1660+
let attrs = hir.attrs(proc_macro);
16591661
let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
16601662
MacroKind::Bang
16611663
} else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
@@ -1673,10 +1675,10 @@ impl EncodeContext<'a, 'tcx> {
16731675
bug!("Unknown proc-macro type for item {:?}", id);
16741676
};
16751677

1676-
let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1678+
let mut def_key = self.tcx.hir().def_key(id);
16771679
def_key.disambiguated_data.data = DefPathData::MacroNs(name);
16781680

1679-
let def_id = DefId::local(id);
1681+
let def_id = id.to_def_id();
16801682
record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
16811683
record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
16821684
record!(self.tables.attributes[def_id] <- attrs);

compiler/rustc_middle/src/ty/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ pub struct ResolverOutputs {
134134
pub extern_prelude: FxHashMap<Symbol, bool>,
135135
pub main_def: Option<MainDefinition>,
136136
pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
137+
/// A list of proc macro LocalDefIds, written out in the order in which
138+
/// they are declared in the static array generated by proc_macro_harness.
139+
pub proc_macros: Vec<LocalDefId>,
137140
}
138141

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

compiler/rustc_parse/src/parser/item.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ impl<'a> Parser<'a> {
2626
/// Parses a source module as a crate. This is the main entry point for the parser.
2727
pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> {
2828
let (attrs, items, span) = self.parse_mod(&token::Eof)?;
29-
let proc_macros = Vec::new(); // Filled in by `proc_macro_harness::inject()`.
30-
Ok(ast::Crate { attrs, items, span, proc_macros })
29+
Ok(ast::Crate { attrs, items, span })
3130
}
3231

3332
/// Parses a `mod <foo> { ... }` or `mod <foo>;` item.

compiler/rustc_resolve/src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1035,6 +1035,9 @@ pub struct Resolver<'a> {
10351035

10361036
main_def: Option<MainDefinition>,
10371037
trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
1038+
/// A list of proc macro LocalDefIds, written out in the order in which
1039+
/// they are declared in the static array generated by proc_macro_harness.
1040+
proc_macros: Vec<NodeId>,
10381041
}
10391042

10401043
/// Nothing really interesting here; it just provides memory for the rest of the crate.
@@ -1400,6 +1403,7 @@ impl<'a> Resolver<'a> {
14001403
item_generics_num_lifetimes: Default::default(),
14011404
main_def: Default::default(),
14021405
trait_impls: Default::default(),
1406+
proc_macros: Default::default(),
14031407
};
14041408

14051409
let root_parent_scope = ParentScope::module(graph_root, &resolver);
@@ -1434,6 +1438,7 @@ impl<'a> Resolver<'a> {
14341438
}
14351439

14361440
pub fn into_outputs(self) -> ResolverOutputs {
1441+
let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
14371442
let definitions = self.definitions;
14381443
let visibilities = self.visibilities;
14391444
let extern_crate_map = self.extern_crate_map;
@@ -1458,10 +1463,12 @@ impl<'a> Resolver<'a> {
14581463
.collect(),
14591464
main_def,
14601465
trait_impls: self.trait_impls,
1466+
proc_macros,
14611467
}
14621468
}
14631469

14641470
pub fn clone_outputs(&self) -> ResolverOutputs {
1471+
let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
14651472
ResolverOutputs {
14661473
definitions: self.definitions.clone(),
14671474
cstore: Box::new(self.cstore().clone()),
@@ -1478,6 +1485,7 @@ impl<'a> Resolver<'a> {
14781485
.collect(),
14791486
main_def: self.main_def.clone(),
14801487
trait_impls: self.trait_impls.clone(),
1488+
proc_macros,
14811489
}
14821490
}
14831491

compiler/rustc_resolve/src/macros.rs

+4
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,10 @@ impl<'a> ResolverExpand for Resolver<'a> {
466466
fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
467467
self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
468468
}
469+
470+
fn declare_proc_macro(&mut self, id: NodeId) {
471+
self.proc_macros.push(id)
472+
}
469473
}
470474

471475
impl<'a> Resolver<'a> {

0 commit comments

Comments
 (0)