]> git.lizzy.rs Git - rust.git/blob - src/librustc_plugin/build.rs
Rollup merge of #53545 - FelixMcFelix:fix-50865-beta, r=petrochenkov
[rust.git] / src / librustc_plugin / build.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Used by `rustc` when compiling a plugin crate.
12
13 use syntax::ast;
14 use syntax::attr;
15 use errors;
16 use syntax_pos::Span;
17 use rustc::hir::map::Map;
18 use rustc::hir::itemlikevisit::ItemLikeVisitor;
19 use rustc::hir;
20
21 struct RegistrarFinder {
22     registrars: Vec<(ast::NodeId, Span)> ,
23 }
24
25 impl<'v> ItemLikeVisitor<'v> for RegistrarFinder {
26     fn visit_item(&mut self, item: &hir::Item) {
27         if let hir::ItemKind::Fn(..) = item.node {
28             if attr::contains_name(&item.attrs,
29                                    "plugin_registrar") {
30                 self.registrars.push((item.id, item.span));
31             }
32         }
33     }
34
35     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
36     }
37
38     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
39     }
40 }
41
42 /// Find the function marked with `#[plugin_registrar]`, if any.
43 pub fn find_plugin_registrar(diagnostic: &errors::Handler,
44                              hir_map: &Map)
45                              -> Option<ast::NodeId> {
46     let krate = hir_map.krate();
47
48     let mut finder = RegistrarFinder { registrars: Vec::new() };
49     krate.visit_all_item_likes(&mut finder);
50
51     match finder.registrars.len() {
52         0 => None,
53         1 => {
54             let (node_id, _) = finder.registrars.pop().unwrap();
55             Some(node_id)
56         },
57         _ => {
58             let mut e = diagnostic.struct_err("multiple plugin registration functions found");
59             for &(_, span) in &finder.registrars {
60                 e.span_note(span, "one is here");
61             }
62             e.emit();
63             diagnostic.abort_if_errors();
64             unreachable!();
65         }
66     }
67 }