Skip to content

Commit 8c62fa0

Browse files
Treat macros as HIR items
1 parent ac50a53 commit 8c62fa0

File tree

31 files changed

+162
-256
lines changed

31 files changed

+162
-256
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4146,6 +4146,7 @@ dependencies = [
41464146
name = "rustc_privacy"
41474147
version = "0.0.0"
41484148
dependencies = [
4149+
"rustc_ast",
41494150
"rustc_attr",
41504151
"rustc_data_structures",
41514152
"rustc_errors",

compiler/rustc_ast_lowering/src/item.rs

+6-24
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
170170
self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
171171
vec
172172
}
173-
ItemKind::MacroDef(..) => SmallVec::new(),
174173
ItemKind::Fn(..) | ItemKind::Impl(box ImplKind { of_trait: None, .. }) => {
175174
smallvec![i.id]
176175
}
@@ -212,28 +211,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
212211
pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
213212
let mut ident = i.ident;
214213
let mut vis = self.lower_visibility(&i.vis, None);
215-
216-
if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind {
217-
if !macro_rules || self.sess.contains_name(&i.attrs, sym::macro_export) {
218-
let hir_id = self.lower_node_id(i.id);
219-
self.lower_attrs(hir_id, &i.attrs);
220-
let body = P(self.lower_mac_args(body));
221-
self.insert_macro_def(hir::MacroDef {
222-
ident,
223-
vis,
224-
def_id: hir_id.expect_owner(),
225-
span: i.span,
226-
ast: MacroDef { body, macro_rules },
227-
});
228-
} else {
229-
for a in i.attrs.iter() {
230-
let a = self.lower_attr(a);
231-
self.non_exported_macro_attrs.push(a);
232-
}
233-
}
234-
return None;
235-
}
236-
237214
let hir_id = self.lower_node_id(i.id);
238215
let attrs = self.lower_attrs(hir_id, &i.attrs);
239216
let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
@@ -465,7 +442,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
465442
self.lower_generics(generics, ImplTraitContext::disallowed()),
466443
self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
467444
),
468-
ItemKind::MacroDef(..) | ItemKind::MacCall(..) => {
445+
ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
446+
let body = P(self.lower_mac_args(body));
447+
448+
hir::ItemKind::Macro(ast::MacroDef { body, macro_rules })
449+
}
450+
ItemKind::MacCall(..) => {
469451
panic!("`TyMac` should have been expanded by now")
470452
}
471453
}

compiler/rustc_ast_lowering/src/lib.rs

-10
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ struct LoweringContext<'a, 'hir: 'a> {
103103
/// The items being lowered are collected here.
104104
owners: IndexVec<LocalDefId, Option<hir::OwnerNode<'hir>>>,
105105
bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
106-
non_exported_macro_attrs: Vec<ast::Attribute>,
107106

108107
trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
109108

@@ -330,7 +329,6 @@ pub fn lower_crate<'a, 'hir>(
330329
trait_impls: BTreeMap::new(),
331330
modules: BTreeMap::new(),
332331
attrs: BTreeMap::default(),
333-
non_exported_macro_attrs: Vec::new(),
334332
catch_scopes: Vec::new(),
335333
loop_scopes: Vec::new(),
336334
is_in_loop_condition: false,
@@ -551,7 +549,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
551549
}
552550

553551
let krate = hir::Crate {
554-
non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
555552
owners: self.owners,
556553
bodies: self.bodies,
557554
body_ids,
@@ -600,13 +597,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
600597
id
601598
}
602599

603-
fn insert_macro_def(&mut self, item: hir::MacroDef<'hir>) {
604-
let def_id = item.def_id;
605-
let item = self.arena.alloc(item);
606-
self.owners.ensure_contains_elem(def_id, || None);
607-
self.owners[def_id] = Some(hir::OwnerNode::MacroDef(item));
608-
}
609-
610600
fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
611601
// Set up the counter if needed.
612602
self.item_local_id_counters.entry(owner).or_insert(0);

compiler/rustc_ast_pretty/src/pprust/state.rs

+30-18
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,33 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
578578
}
579579
}
580580

581+
fn print_mac_def(
582+
&mut self,
583+
macro_def: &ast::MacroDef,
584+
ident: &Ident,
585+
sp: &Span,
586+
print_visibility: impl FnOnce(&mut Self),
587+
) {
588+
let (kw, has_bang) = if macro_def.macro_rules {
589+
("macro_rules", true)
590+
} else {
591+
print_visibility(self);
592+
("macro", false)
593+
};
594+
self.print_mac_common(
595+
Some(MacHeader::Keyword(kw)),
596+
has_bang,
597+
Some(*ident),
598+
macro_def.body.delim(),
599+
&macro_def.body.inner_tokens(),
600+
true,
601+
*sp,
602+
);
603+
if macro_def.body.need_semicolon() {
604+
self.word(";");
605+
}
606+
}
607+
581608
fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
582609
self.maybe_print_comment(path.span.lo());
583610

@@ -1305,24 +1332,9 @@ impl<'a> State<'a> {
13051332
}
13061333
}
13071334
ast::ItemKind::MacroDef(ref macro_def) => {
1308-
let (kw, has_bang) = if macro_def.macro_rules {
1309-
("macro_rules", true)
1310-
} else {
1311-
self.print_visibility(&item.vis);
1312-
("macro", false)
1313-
};
1314-
self.print_mac_common(
1315-
Some(MacHeader::Keyword(kw)),
1316-
has_bang,
1317-
Some(item.ident),
1318-
macro_def.body.delim(),
1319-
&macro_def.body.inner_tokens(),
1320-
true,
1321-
item.span,
1322-
);
1323-
if macro_def.body.need_semicolon() {
1324-
self.word(";");
1325-
}
1335+
self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1336+
state.print_visibility(&item.vis)
1337+
});
13261338
}
13271339
}
13281340
self.ann.post(self, AnnNode::Item(item))

compiler/rustc_hir/src/arena.rs

-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ macro_rules! arena_types {
3535
[few] inline_asm: rustc_hir::InlineAsm<$tcx>,
3636
[few] llvm_inline_asm: rustc_hir::LlvmInlineAsm<$tcx>,
3737
[] local: rustc_hir::Local<$tcx>,
38-
[few] macro_def: rustc_hir::MacroDef<$tcx>,
3938
[few] mod_: rustc_hir::Mod<$tcx>,
4039
[] param: rustc_hir::Param<$tcx>,
4140
[] pat: rustc_hir::Pat<$tcx>,

compiler/rustc_hir/src/hir.rs

+4-30
Original file line numberDiff line numberDiff line change
@@ -670,9 +670,6 @@ pub struct ModuleItems {
670670
/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
671671
#[derive(Debug)]
672672
pub struct Crate<'hir> {
673-
// Attributes from non-exported macros, kept only for collecting the library feature list.
674-
pub non_exported_macro_attrs: &'hir [Attribute],
675-
676673
pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
677674
pub bodies: BTreeMap<BodyId, Body<'hir>>,
678675
pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
@@ -768,32 +765,6 @@ impl Crate<'_> {
768765
_ => None,
769766
})
770767
}
771-
772-
pub fn exported_macros<'hir>(&'hir self) -> impl Iterator<Item = &'hir MacroDef<'hir>> + 'hir {
773-
self.owners.iter().filter_map(|owner| match owner {
774-
Some(OwnerNode::MacroDef(macro_def)) => Some(*macro_def),
775-
_ => None,
776-
})
777-
}
778-
}
779-
780-
/// A macro definition, in this crate or imported from another.
781-
///
782-
/// Not parsed directly, but created on macro import or `macro_rules!` expansion.
783-
#[derive(Debug)]
784-
pub struct MacroDef<'hir> {
785-
pub ident: Ident,
786-
pub vis: Visibility<'hir>,
787-
pub def_id: LocalDefId,
788-
pub span: Span,
789-
pub ast: ast::MacroDef,
790-
}
791-
792-
impl MacroDef<'_> {
793-
#[inline]
794-
pub fn hir_id(&self) -> HirId {
795-
HirId::make_owner(self.def_id)
796-
}
797768
}
798769

799770
/// A block of statements `{ .. }`, which may have a label (in this case the
@@ -2602,7 +2573,7 @@ pub struct PolyTraitRef<'hir> {
26022573

26032574
pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
26042575

2605-
#[derive(Debug)]
2576+
#[derive(Copy, Clone, Debug)]
26062577
pub enum VisibilityKind<'hir> {
26072578
Public,
26082579
Crate(CrateSugar),
@@ -2791,6 +2762,8 @@ pub enum ItemKind<'hir> {
27912762
Const(&'hir Ty<'hir>, BodyId),
27922763
/// A function declaration.
27932764
Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2765+
/// A MBE macro definition (`macro_rules!` or `macro`).
2766+
Macro(ast::MacroDef),
27942767
/// A module.
27952768
Mod(Mod<'hir>),
27962769
/// An external module, e.g. `extern { .. }`.
@@ -2856,6 +2829,7 @@ impl ItemKind<'_> {
28562829
ItemKind::Static(..) => "static item",
28572830
ItemKind::Const(..) => "constant item",
28582831
ItemKind::Fn(..) => "function",
2832+
ItemKind::Macro(..) => "macro",
28592833
ItemKind::Mod(..) => "module",
28602834
ItemKind::ForeignMod { .. } => "extern block",
28612835
ItemKind::GlobalAsm(..) => "global asm item",

compiler/rustc_hir/src/intravisit.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -466,9 +466,6 @@ pub trait Visitor<'v>: Sized {
466466
walk_assoc_type_binding(self, type_binding)
467467
}
468468
fn visit_attribute(&mut self, _id: HirId, _attr: &'v Attribute) {}
469-
fn visit_macro_def(&mut self, macro_def: &'v MacroDef<'v>) {
470-
walk_macro_def(self, macro_def)
471-
}
472469
fn visit_vis(&mut self, vis: &'v Visibility<'v>) {
473470
walk_vis(self, vis)
474471
}
@@ -484,19 +481,13 @@ pub trait Visitor<'v>: Sized {
484481
pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) {
485482
let top_mod = krate.module();
486483
visitor.visit_mod(top_mod, top_mod.inner, CRATE_HIR_ID);
487-
walk_list!(visitor, visit_macro_def, krate.exported_macros());
488484
for (&id, attrs) in krate.attrs.iter() {
489485
for a in *attrs {
490486
visitor.visit_attribute(id, a)
491487
}
492488
}
493489
}
494490

495-
pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef<'v>) {
496-
visitor.visit_id(macro_def.hir_id());
497-
visitor.visit_ident(macro_def.ident);
498-
}
499-
500491
pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) {
501492
visitor.visit_id(mod_hir_id);
502493
for &item_id in module.item_ids {
@@ -586,6 +577,9 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) {
586577
item.span,
587578
item.hir_id(),
588579
),
580+
ItemKind::Macro(_) => {
581+
visitor.visit_id(item.hir_id());
582+
}
589583
ItemKind::Mod(ref module) => {
590584
// `visit_mod()` takes care of visiting the `Item`'s `HirId`.
591585
visitor.visit_mod(module, item.span, item.hir_id())

compiler/rustc_hir/src/stable_hash_impls.rs

+2-15
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
22

33
use crate::hir::{
4-
BodyId, Expr, ForeignItem, ForeignItemId, ImplItem, ImplItemId, Item, ItemId, MacroDef, Mod,
5-
TraitItem, TraitItemId, Ty, VisibilityKind,
4+
BodyId, Expr, ForeignItem, ForeignItemId, ImplItem, ImplItemId, Item, ItemId, Mod, TraitItem,
5+
TraitItemId, Ty, VisibilityKind,
66
};
77
use crate::hir_id::{HirId, ItemLocalId};
88
use rustc_span::def_id::DefPathHash;
@@ -190,16 +190,3 @@ impl<HirCtx: crate::HashStableContext> HashStable<HirCtx> for Item<'_> {
190190
});
191191
}
192192
}
193-
194-
impl<HirCtx: crate::HashStableContext> HashStable<HirCtx> for MacroDef<'_> {
195-
fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) {
196-
let MacroDef { ident, def_id: _, ref ast, ref vis, span } = *self;
197-
198-
hcx.hash_hir_item_like(|hcx| {
199-
ident.name.hash_stable(hcx, hasher);
200-
ast.hash_stable(hcx, hasher);
201-
vis.hash_stable(hcx, hasher);
202-
span.hash_stable(hcx, hasher);
203-
});
204-
}
205-
}

compiler/rustc_hir/src/target.rs

+1
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ impl Target {
111111
ItemKind::Static(..) => Target::Static,
112112
ItemKind::Const(..) => Target::Const,
113113
ItemKind::Fn(..) => Target::Fn,
114+
ItemKind::Macro(..) => Target::MacroDef,
114115
ItemKind::Mod(..) => Target::Mod,
115116
ItemKind::ForeignMod { .. } => Target::ForeignMod,
116117
ItemKind::GlobalAsm(..) => Target::GlobalAsm,

compiler/rustc_hir_pretty/src/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,11 @@ impl<'a> State<'a> {
642642
self.end(); // need to close a box
643643
self.ann.nested(self, Nested::Body(body));
644644
}
645+
hir::ItemKind::Macro(ref macro_def) => {
646+
self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
647+
state.print_visibility(&item.vis)
648+
});
649+
}
645650
hir::ItemKind::Mod(ref _mod) => {
646651
self.head(visibility_qualified(&item.vis, "mod"));
647652
self.print_ident(item.ident);

compiler/rustc_lint/src/builtin.rs

+1-18
Original file line numberDiff line numberDiff line change
@@ -585,24 +585,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
585585

586586
fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) {
587587
self.check_missing_docs_attrs(cx, CRATE_DEF_ID, krate.module().inner, "the", "crate");
588-
589-
for macro_def in krate.exported_macros() {
590-
// Non exported macros should be skipped, since `missing_docs` only
591-
// applies to externally visible items.
592-
if !cx.access_levels.is_exported(macro_def.def_id) {
593-
continue;
594-
}
595-
596-
let attrs = cx.tcx.hir().attrs(macro_def.hir_id());
597-
let has_doc = attrs.iter().any(has_doc);
598-
if !has_doc {
599-
cx.struct_span_lint(
600-
MISSING_DOCS,
601-
cx.tcx.sess.source_map().guess_head_span(macro_def.span),
602-
|lint| lint.build("missing documentation for macro").emit(),
603-
);
604-
}
605-
}
606588
}
607589

608590
fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
@@ -636,6 +618,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {
636618

637619
hir::ItemKind::TyAlias(..)
638620
| hir::ItemKind::Fn(..)
621+
| hir::ItemKind::Macro(..)
639622
| hir::ItemKind::Mod(..)
640623
| hir::ItemKind::Enum(..)
641624
| hir::ItemKind::Struct(..)

compiler/rustc_lint/src/late.rs

-4
Original file line numberDiff line numberDiff line change
@@ -453,10 +453,6 @@ fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T)
453453
lint_callback!(cx, check_crate, krate);
454454

455455
hir_visit::walk_crate(cx, krate);
456-
for attr in krate.non_exported_macro_attrs {
457-
// This HIR ID is a lie, since the macro ID isn't available.
458-
cx.visit_attribute(hir::CRATE_HIR_ID, attr);
459-
}
460456

461457
lint_callback!(cx, check_crate_post, krate);
462458
})

compiler/rustc_lint/src/levels.rs

-3
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,6 @@ fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap {
3737

3838
let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), &store, true);
3939
builder.levels.register_id(hir::CRATE_HIR_ID);
40-
for macro_def in krate.exported_macros() {
41-
builder.levels.register_id(macro_def.hir_id());
42-
}
4340
intravisit::walk_crate(&mut builder, krate);
4441
builder.levels.pop(push);
4542

compiler/rustc_metadata/src/rmeta/decoder.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -1100,7 +1100,13 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
11001100
let vis = self.get_visibility(child_index);
11011101
let def_id = self.local_def_id(child_index);
11021102
let res = Res::Def(kind, def_id);
1103-
callback(Export { res, ident, vis, span });
1103+
1104+
// FIXME: Macros are currently encoded twice, once as items and once as
1105+
// reexports. We ignore the items here and only use the reexports.
1106+
if !matches!(kind, DefKind::Macro(..)) {
1107+
callback(Export { res, ident, vis, span });
1108+
}
1109+
11041110
// For non-re-export structs and variants add their constructors to children.
11051111
// Re-export lists automatically contain constructors when necessary.
11061112
match kind {

0 commit comments

Comments
 (0)