Skip to content

Commit

Permalink
Treat macros as HIR items
Browse files Browse the repository at this point in the history
  • Loading branch information
inquisitivecrystal committed Aug 28, 2021
1 parent ac50a53 commit 8c62fa0
Show file tree
Hide file tree
Showing 31 changed files with 162 additions and 256 deletions.
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4146,6 +4146,7 @@ dependencies = [
name = "rustc_privacy"
version = "0.0.0"
dependencies = [
"rustc_ast",
"rustc_attr",
"rustc_data_structures",
"rustc_errors",
Expand Down
30 changes: 6 additions & 24 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.lower_item_id_use_tree(use_tree, i.id, &mut vec);
vec
}
ItemKind::MacroDef(..) => SmallVec::new(),
ItemKind::Fn(..) | ItemKind::Impl(box ImplKind { of_trait: None, .. }) => {
smallvec![i.id]
}
Expand Down Expand Up @@ -212,28 +211,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> {
let mut ident = i.ident;
let mut vis = self.lower_visibility(&i.vis, None);

if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind {
if !macro_rules || self.sess.contains_name(&i.attrs, sym::macro_export) {
let hir_id = self.lower_node_id(i.id);
self.lower_attrs(hir_id, &i.attrs);
let body = P(self.lower_mac_args(body));
self.insert_macro_def(hir::MacroDef {
ident,
vis,
def_id: hir_id.expect_owner(),
span: i.span,
ast: MacroDef { body, macro_rules },
});
} else {
for a in i.attrs.iter() {
let a = self.lower_attr(a);
self.non_exported_macro_attrs.push(a);
}
}
return None;
}

let hir_id = self.lower_node_id(i.id);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
Expand Down Expand Up @@ -465,7 +442,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.lower_generics(generics, ImplTraitContext::disallowed()),
self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
),
ItemKind::MacroDef(..) | ItemKind::MacCall(..) => {
ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
let body = P(self.lower_mac_args(body));

hir::ItemKind::Macro(ast::MacroDef { body, macro_rules })
}
ItemKind::MacCall(..) => {
panic!("`TyMac` should have been expanded by now")
}
}
Expand Down
10 changes: 0 additions & 10 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ struct LoweringContext<'a, 'hir: 'a> {
/// The items being lowered are collected here.
owners: IndexVec<LocalDefId, Option<hir::OwnerNode<'hir>>>,
bodies: BTreeMap<hir::BodyId, hir::Body<'hir>>,
non_exported_macro_attrs: Vec<ast::Attribute>,

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

Expand Down Expand Up @@ -330,7 +329,6 @@ pub fn lower_crate<'a, 'hir>(
trait_impls: BTreeMap::new(),
modules: BTreeMap::new(),
attrs: BTreeMap::default(),
non_exported_macro_attrs: Vec::new(),
catch_scopes: Vec::new(),
loop_scopes: Vec::new(),
is_in_loop_condition: false,
Expand Down Expand Up @@ -551,7 +549,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}

let krate = hir::Crate {
non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
owners: self.owners,
bodies: self.bodies,
body_ids,
Expand Down Expand Up @@ -600,13 +597,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
id
}

fn insert_macro_def(&mut self, item: hir::MacroDef<'hir>) {
let def_id = item.def_id;
let item = self.arena.alloc(item);
self.owners.ensure_contains_elem(def_id, || None);
self.owners[def_id] = Some(hir::OwnerNode::MacroDef(item));
}

fn allocate_hir_id_counter(&mut self, owner: NodeId) -> hir::HirId {
// Set up the counter if needed.
self.item_local_id_counters.entry(owner).or_insert(0);
Expand Down
48 changes: 30 additions & 18 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,33 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
}
}

fn print_mac_def(
&mut self,
macro_def: &ast::MacroDef,
ident: &Ident,
sp: &Span,
print_visibility: impl FnOnce(&mut Self),
) {
let (kw, has_bang) = if macro_def.macro_rules {
("macro_rules", true)
} else {
print_visibility(self);
("macro", false)
};
self.print_mac_common(
Some(MacHeader::Keyword(kw)),
has_bang,
Some(*ident),
macro_def.body.delim(),
&macro_def.body.inner_tokens(),
true,
*sp,
);
if macro_def.body.need_semicolon() {
self.word(";");
}
}

fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
self.maybe_print_comment(path.span.lo());

Expand Down Expand Up @@ -1305,24 +1332,9 @@ impl<'a> State<'a> {
}
}
ast::ItemKind::MacroDef(ref macro_def) => {
let (kw, has_bang) = if macro_def.macro_rules {
("macro_rules", true)
} else {
self.print_visibility(&item.vis);
("macro", false)
};
self.print_mac_common(
Some(MacHeader::Keyword(kw)),
has_bang,
Some(item.ident),
macro_def.body.delim(),
&macro_def.body.inner_tokens(),
true,
item.span,
);
if macro_def.body.need_semicolon() {
self.word(";");
}
self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
state.print_visibility(&item.vis)
});
}
}
self.ann.post(self, AnnNode::Item(item))
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_hir/src/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ macro_rules! arena_types {
[few] inline_asm: rustc_hir::InlineAsm<$tcx>,
[few] llvm_inline_asm: rustc_hir::LlvmInlineAsm<$tcx>,
[] local: rustc_hir::Local<$tcx>,
[few] macro_def: rustc_hir::MacroDef<$tcx>,
[few] mod_: rustc_hir::Mod<$tcx>,
[] param: rustc_hir::Param<$tcx>,
[] pat: rustc_hir::Pat<$tcx>,
Expand Down
34 changes: 4 additions & 30 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,9 +670,6 @@ pub struct ModuleItems {
/// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
#[derive(Debug)]
pub struct Crate<'hir> {
// Attributes from non-exported macros, kept only for collecting the library feature list.
pub non_exported_macro_attrs: &'hir [Attribute],

pub owners: IndexVec<LocalDefId, Option<OwnerNode<'hir>>>,
pub bodies: BTreeMap<BodyId, Body<'hir>>,
pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
Expand Down Expand Up @@ -768,32 +765,6 @@ impl Crate<'_> {
_ => None,
})
}

pub fn exported_macros<'hir>(&'hir self) -> impl Iterator<Item = &'hir MacroDef<'hir>> + 'hir {
self.owners.iter().filter_map(|owner| match owner {
Some(OwnerNode::MacroDef(macro_def)) => Some(*macro_def),
_ => None,
})
}
}

/// A macro definition, in this crate or imported from another.
///
/// Not parsed directly, but created on macro import or `macro_rules!` expansion.
#[derive(Debug)]
pub struct MacroDef<'hir> {
pub ident: Ident,
pub vis: Visibility<'hir>,
pub def_id: LocalDefId,
pub span: Span,
pub ast: ast::MacroDef,
}

impl MacroDef<'_> {
#[inline]
pub fn hir_id(&self) -> HirId {
HirId::make_owner(self.def_id)
}
}

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

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

#[derive(Debug)]
#[derive(Copy, Clone, Debug)]
pub enum VisibilityKind<'hir> {
Public,
Crate(CrateSugar),
Expand Down Expand Up @@ -2791,6 +2762,8 @@ pub enum ItemKind<'hir> {
Const(&'hir Ty<'hir>, BodyId),
/// A function declaration.
Fn(FnSig<'hir>, Generics<'hir>, BodyId),
/// A MBE macro definition (`macro_rules!` or `macro`).
Macro(ast::MacroDef),
/// A module.
Mod(Mod<'hir>),
/// An external module, e.g. `extern { .. }`.
Expand Down Expand Up @@ -2856,6 +2829,7 @@ impl ItemKind<'_> {
ItemKind::Static(..) => "static item",
ItemKind::Const(..) => "constant item",
ItemKind::Fn(..) => "function",
ItemKind::Macro(..) => "macro",
ItemKind::Mod(..) => "module",
ItemKind::ForeignMod { .. } => "extern block",
ItemKind::GlobalAsm(..) => "global asm item",
Expand Down
12 changes: 3 additions & 9 deletions compiler/rustc_hir/src/intravisit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,9 +466,6 @@ pub trait Visitor<'v>: Sized {
walk_assoc_type_binding(self, type_binding)
}
fn visit_attribute(&mut self, _id: HirId, _attr: &'v Attribute) {}
fn visit_macro_def(&mut self, macro_def: &'v MacroDef<'v>) {
walk_macro_def(self, macro_def)
}
fn visit_vis(&mut self, vis: &'v Visibility<'v>) {
walk_vis(self, vis)
}
Expand All @@ -484,19 +481,13 @@ pub trait Visitor<'v>: Sized {
pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) {
let top_mod = krate.module();
visitor.visit_mod(top_mod, top_mod.inner, CRATE_HIR_ID);
walk_list!(visitor, visit_macro_def, krate.exported_macros());
for (&id, attrs) in krate.attrs.iter() {
for a in *attrs {
visitor.visit_attribute(id, a)
}
}
}

pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef<'v>) {
visitor.visit_id(macro_def.hir_id());
visitor.visit_ident(macro_def.ident);
}

pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) {
visitor.visit_id(mod_hir_id);
for &item_id in module.item_ids {
Expand Down Expand Up @@ -586,6 +577,9 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) {
item.span,
item.hir_id(),
),
ItemKind::Macro(_) => {
visitor.visit_id(item.hir_id());
}
ItemKind::Mod(ref module) => {
// `visit_mod()` takes care of visiting the `Item`'s `HirId`.
visitor.visit_mod(module, item.span, item.hir_id())
Expand Down
17 changes: 2 additions & 15 deletions compiler/rustc_hir/src/stable_hash_impls.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};

use crate::hir::{
BodyId, Expr, ForeignItem, ForeignItemId, ImplItem, ImplItemId, Item, ItemId, MacroDef, Mod,
TraitItem, TraitItemId, Ty, VisibilityKind,
BodyId, Expr, ForeignItem, ForeignItemId, ImplItem, ImplItemId, Item, ItemId, Mod, TraitItem,
TraitItemId, Ty, VisibilityKind,
};
use crate::hir_id::{HirId, ItemLocalId};
use rustc_span::def_id::DefPathHash;
Expand Down Expand Up @@ -190,16 +190,3 @@ impl<HirCtx: crate::HashStableContext> HashStable<HirCtx> for Item<'_> {
});
}
}

impl<HirCtx: crate::HashStableContext> HashStable<HirCtx> for MacroDef<'_> {
fn hash_stable(&self, hcx: &mut HirCtx, hasher: &mut StableHasher) {
let MacroDef { ident, def_id: _, ref ast, ref vis, span } = *self;

hcx.hash_hir_item_like(|hcx| {
ident.name.hash_stable(hcx, hasher);
ast.hash_stable(hcx, hasher);
vis.hash_stable(hcx, hasher);
span.hash_stable(hcx, hasher);
});
}
}
1 change: 1 addition & 0 deletions compiler/rustc_hir/src/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ impl Target {
ItemKind::Static(..) => Target::Static,
ItemKind::Const(..) => Target::Const,
ItemKind::Fn(..) => Target::Fn,
ItemKind::Macro(..) => Target::MacroDef,
ItemKind::Mod(..) => Target::Mod,
ItemKind::ForeignMod { .. } => Target::ForeignMod,
ItemKind::GlobalAsm(..) => Target::GlobalAsm,
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,11 @@ impl<'a> State<'a> {
self.end(); // need to close a box
self.ann.nested(self, Nested::Body(body));
}
hir::ItemKind::Macro(ref macro_def) => {
self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
state.print_visibility(&item.vis)
});
}
hir::ItemKind::Mod(ref _mod) => {
self.head(visibility_qualified(&item.vis, "mod"));
self.print_ident(item.ident);
Expand Down
19 changes: 1 addition & 18 deletions compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,24 +585,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc {

fn check_crate(&mut self, cx: &LateContext<'_>, krate: &hir::Crate<'_>) {
self.check_missing_docs_attrs(cx, CRATE_DEF_ID, krate.module().inner, "the", "crate");

for macro_def in krate.exported_macros() {
// Non exported macros should be skipped, since `missing_docs` only
// applies to externally visible items.
if !cx.access_levels.is_exported(macro_def.def_id) {
continue;
}

let attrs = cx.tcx.hir().attrs(macro_def.hir_id());
let has_doc = attrs.iter().any(has_doc);
if !has_doc {
cx.struct_span_lint(
MISSING_DOCS,
cx.tcx.sess.source_map().guess_head_span(macro_def.span),
|lint| lint.build("missing documentation for macro").emit(),
);
}
}
}

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

hir::ItemKind::TyAlias(..)
| hir::ItemKind::Fn(..)
| hir::ItemKind::Macro(..)
| hir::ItemKind::Mod(..)
| hir::ItemKind::Enum(..)
| hir::ItemKind::Struct(..)
Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_lint/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,10 +453,6 @@ fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T)
lint_callback!(cx, check_crate, krate);

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

lint_callback!(cx, check_crate_post, krate);
})
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_lint/src/levels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap {

let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), &store, true);
builder.levels.register_id(hir::CRATE_HIR_ID);
for macro_def in krate.exported_macros() {
builder.levels.register_id(macro_def.hir_id());
}
intravisit::walk_crate(&mut builder, krate);
builder.levels.pop(push);

Expand Down
8 changes: 7 additions & 1 deletion compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1100,7 +1100,13 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
let vis = self.get_visibility(child_index);
let def_id = self.local_def_id(child_index);
let res = Res::Def(kind, def_id);
callback(Export { res, ident, vis, span });

// FIXME: Macros are currently encoded twice, once as items and once as
// reexports. We ignore the items here and only use the reexports.
if !matches!(kind, DefKind::Macro(..)) {
callback(Export { res, ident, vis, span });
}

// For non-re-export structs and variants add their constructors to children.
// Re-export lists automatically contain constructors when necessary.
match kind {
Expand Down
Loading

0 comments on commit 8c62fa0

Please sign in to comment.