rust/src/librustc_plugin_impl/build.rs

63 lines
1.9 KiB
Rust
Raw Normal View History

2014-05-26 21:48:54 +00:00
//! Used by `rustc` when compiling a plugin crate.
2016-03-29 05:50:44 +00:00
use rustc::hir;
2019-01-13 00:06:50 +00:00
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
2019-12-22 22:42:04 +00:00
use rustc::hir::itemlikevisit::ItemLikeVisitor;
2019-01-13 00:06:50 +00:00
use rustc::ty::query::Providers;
2019-12-22 22:42:04 +00:00
use rustc::ty::TyCtxt;
use rustc_span::Span;
2019-12-22 22:42:04 +00:00
use syntax::attr;
use syntax::symbol::sym;
2013-12-25 18:10:33 +00:00
struct RegistrarFinder {
2019-12-22 22:42:04 +00:00
registrars: Vec<(hir::HirId, Span)>,
2013-12-25 18:10:33 +00:00
}
impl<'v> ItemLikeVisitor<'v> for RegistrarFinder {
2019-11-28 18:28:50 +00:00
fn visit_item(&mut self, item: &hir::Item<'_>) {
2019-09-26 16:51:36 +00:00
if let hir::ItemKind::Fn(..) = item.kind {
if attr::contains_name(&item.attrs, sym::plugin_registrar) {
2019-02-27 16:35:24 +00:00
self.registrars.push((item.hir_id, item.span));
2013-12-25 18:10:33 +00:00
}
}
}
2019-12-22 22:42:04 +00:00
fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
2019-12-22 22:42:04 +00:00
fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
2013-12-25 18:10:33 +00:00
}
2019-02-08 13:53:55 +00:00
/// Finds the function marked with `#[plugin_registrar]`, if any.
2019-06-21 18:27:44 +00:00
pub fn find_plugin_registrar(tcx: TyCtxt<'_>) -> Option<DefId> {
2019-01-13 00:06:50 +00:00
tcx.plugin_registrar_fn(LOCAL_CRATE)
}
2019-06-21 18:27:44 +00:00
fn plugin_registrar_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<DefId> {
2019-01-13 00:06:50 +00:00
assert_eq!(cnum, LOCAL_CRATE);
let mut finder = RegistrarFinder { registrars: Vec::new() };
2019-01-13 00:06:50 +00:00
tcx.hir().krate().visit_all_item_likes(&mut finder);
2013-12-25 18:10:33 +00:00
match finder.registrars.len() {
2013-12-25 18:10:33 +00:00
0 => None,
1 => {
2019-02-27 16:35:24 +00:00
let (hir_id, _) = finder.registrars.pop().unwrap();
Some(tcx.hir().local_def_id(hir_id))
2019-12-22 22:42:04 +00:00
}
2013-12-25 18:10:33 +00:00
_ => {
2019-01-13 00:06:50 +00:00
let diagnostic = tcx.sess.diagnostic();
2015-12-20 21:00:43 +00:00
let mut e = diagnostic.struct_err("multiple plugin registration functions found");
2015-01-31 17:20:46 +00:00
for &(_, span) in &finder.registrars {
2015-12-20 21:00:43 +00:00
e.span_note(span, "one is here");
2013-12-25 18:10:33 +00:00
}
2015-12-20 21:00:43 +00:00
e.emit();
diagnostic.abort_if_errors();
2013-12-25 18:10:33 +00:00
unreachable!();
}
}
}
2019-01-13 00:06:50 +00:00
pub fn provide(providers: &mut Providers<'_>) {
2019-12-22 22:42:04 +00:00
*providers = Providers { plugin_registrar_fn, ..*providers };
2019-01-13 00:06:50 +00:00
}