rust/compiler/rustc_plugin_impl/src/build.rs

58 lines
1.8 KiB
Rust
Raw Normal View History

2014-05-26 21:48:54 +00:00
//! Used by `rustc` when compiling a plugin crate.
use rustc_hir as hir;
2021-05-11 10:07:14 +00:00
use rustc_hir::def_id::LocalDefId;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
2020-03-29 15:19:48 +00:00
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::TyCtxt;
2020-01-01 18:30:57 +00:00
use rustc_span::symbol::sym;
use rustc_span::Span;
2013-12-25 18:10:33 +00:00
struct RegistrarFinder<'tcx> {
tcx: TyCtxt<'tcx>,
registrars: Vec<(LocalDefId, Span)>,
2013-12-25 18:10:33 +00:00
}
impl<'v, 'tcx> ItemLikeVisitor<'v> for RegistrarFinder<'tcx> {
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 {
2021-01-24 12:17:54 +00:00
let attrs = self.tcx.hir().attrs(item.hir_id());
if self.tcx.sess.contains_name(attrs, sym::plugin_registrar) {
self.registrars.push((item.def_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<'_>) {}
2020-11-11 20:57:54 +00:00
fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
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.
2021-05-11 10:07:14 +00:00
fn plugin_registrar_fn(tcx: TyCtxt<'_>, (): ()) -> Option<LocalDefId> {
let mut finder = RegistrarFinder { tcx, 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
2021-05-11 10:07:14 +00:00
let (def_id, span) = finder.registrars.pop()?;
if !finder.registrars.is_empty() {
let diagnostic = tcx.sess.diagnostic();
let mut e = diagnostic.struct_err("multiple plugin registration functions found");
e.span_note(span, "one is here");
for &(_, span) in &finder.registrars {
e.span_note(span, "one is here");
2013-12-25 18:10:33 +00:00
}
2021-05-11 10:07:14 +00:00
e.emit();
diagnostic.abort_if_errors();
unreachable!();
2013-12-25 18:10:33 +00:00
}
2021-05-11 10:07:14 +00:00
Some(def_id)
2013-12-25 18:10:33 +00:00
}
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
}