]> git.lizzy.rs Git - rust.git/blob - src/librustc_plugin_impl/build.rs
Rollup merge of #67519 - Mark-Simulacrum:any-unsafe, r=Centril
[rust.git] / src / librustc_plugin_impl / build.rs
1 //! Used by `rustc` when compiling a plugin crate.
2
3 use syntax::attr;
4 use syntax::symbol::sym;
5 use syntax_pos::Span;
6 use rustc::hir::itemlikevisit::ItemLikeVisitor;
7 use rustc::hir;
8 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
9 use rustc::ty::TyCtxt;
10 use rustc::ty::query::Providers;
11
12 struct RegistrarFinder {
13     registrars: Vec<(hir::HirId, Span)> ,
14 }
15
16 impl<'v> ItemLikeVisitor<'v> for RegistrarFinder {
17     fn visit_item(&mut self, item: &hir::Item<'_>) {
18         if let hir::ItemKind::Fn(..) = item.kind {
19             if attr::contains_name(&item.attrs, sym::plugin_registrar) {
20                 self.registrars.push((item.hir_id, item.span));
21             }
22         }
23     }
24
25     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {
26     }
27
28     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {
29     }
30 }
31
32 /// Finds the function marked with `#[plugin_registrar]`, if any.
33 pub fn find_plugin_registrar(tcx: TyCtxt<'_>) -> Option<DefId> {
34     tcx.plugin_registrar_fn(LOCAL_CRATE)
35 }
36
37 fn plugin_registrar_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<DefId> {
38     assert_eq!(cnum, LOCAL_CRATE);
39
40     let mut finder = RegistrarFinder { registrars: Vec::new() };
41     tcx.hir().krate().visit_all_item_likes(&mut finder);
42
43     match finder.registrars.len() {
44         0 => None,
45         1 => {
46             let (hir_id, _) = finder.registrars.pop().unwrap();
47             Some(tcx.hir().local_def_id(hir_id))
48         },
49         _ => {
50             let diagnostic = tcx.sess.diagnostic();
51             let mut e = diagnostic.struct_err("multiple plugin registration functions found");
52             for &(_, span) in &finder.registrars {
53                 e.span_note(span, "one is here");
54             }
55             e.emit();
56             diagnostic.abort_if_errors();
57             unreachable!();
58         }
59     }
60 }
61
62
63 pub fn provide(providers: &mut Providers<'_>) {
64     *providers = Providers {
65         plugin_registrar_fn,
66         ..*providers
67     };
68 }