]> git.lizzy.rs Git - rust.git/blob - src/librustc_plugin/build.rs
Auto merge of #58406 - Disasm:rv64-support, r=nagisa
[rust.git] / src / librustc_plugin / build.rs
1 //! Used by `rustc` when compiling a plugin crate.
2
3 use syntax::ast;
4 use syntax::attr;
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<(ast::NodeId, 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,
20                                    "plugin_registrar") {
21                 self.registrars.push((item.id, item.span));
22             }
23         }
24     }
25
26     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
27     }
28
29     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
30     }
31 }
32
33 /// Finds the function marked with `#[plugin_registrar]`, if any.
34 pub fn find_plugin_registrar<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) -> Option<DefId> {
35     tcx.plugin_registrar_fn(LOCAL_CRATE)
36 }
37
38 fn plugin_registrar_fn<'tcx>(
39     tcx: TyCtxt<'_, 'tcx, 'tcx>,
40     cnum: CrateNum,
41 ) -> Option<DefId> {
42     assert_eq!(cnum, LOCAL_CRATE);
43
44     let mut finder = RegistrarFinder { registrars: Vec::new() };
45     tcx.hir().krate().visit_all_item_likes(&mut finder);
46
47     match finder.registrars.len() {
48         0 => None,
49         1 => {
50             let (node_id, _) = finder.registrars.pop().unwrap();
51             Some(tcx.hir().local_def_id(node_id))
52         },
53         _ => {
54             let diagnostic = tcx.sess.diagnostic();
55             let mut e = diagnostic.struct_err("multiple plugin registration functions found");
56             for &(_, span) in &finder.registrars {
57                 e.span_note(span, "one is here");
58             }
59             e.emit();
60             diagnostic.abort_if_errors();
61             unreachable!();
62         }
63     }
64 }
65
66
67 pub fn provide(providers: &mut Providers<'_>) {
68     *providers = Providers {
69         plugin_registrar_fn,
70         ..*providers
71     };
72 }