]> git.lizzy.rs Git - rust.git/blob - src/librustc_plugin/build.rs
Rollup merge of #61715 - RalfJung:test-ascii-lowercase, r=varkor
[rust.git] / src / librustc_plugin / 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.node {
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>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> Option<DefId> {
34     tcx.plugin_registrar_fn(LOCAL_CRATE)
35 }
36
37 fn plugin_registrar_fn<'tcx>(
38     tcx: TyCtxt<'_, 'tcx, 'tcx>,
39     cnum: CrateNum,
40 ) -> Option<DefId> {
41     assert_eq!(cnum, LOCAL_CRATE);
42
43     let mut finder = RegistrarFinder { registrars: Vec::new() };
44     tcx.hir().krate().visit_all_item_likes(&mut finder);
45
46     match finder.registrars.len() {
47         0 => None,
48         1 => {
49             let (hir_id, _) = finder.registrars.pop().unwrap();
50             Some(tcx.hir().local_def_id_from_hir_id(hir_id))
51         },
52         _ => {
53             let diagnostic = tcx.sess.diagnostic();
54             let mut e = diagnostic.struct_err("multiple plugin registration functions found");
55             for &(_, span) in &finder.registrars {
56                 e.span_note(span, "one is here");
57             }
58             e.emit();
59             diagnostic.abort_if_errors();
60             unreachable!();
61         }
62     }
63 }
64
65
66 pub fn provide(providers: &mut Providers<'_>) {
67     *providers = Providers {
68         plugin_registrar_fn,
69         ..*providers
70     };
71 }