]> git.lizzy.rs Git - rust.git/blob - src/librustc_plugin/load.rs
bf59165a9c4614f010e9ca359f3c9bc59d7dc079
[rust.git] / src / librustc_plugin / load.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 loading a plugin.
12
13 use rustc::session::Session;
14 use rustc_metadata::creader::CrateLoader;
15 use rustc_metadata::cstore::CStore;
16 use registry::Registry;
17
18 use std::borrow::ToOwned;
19 use std::env;
20 use std::mem;
21 use std::path::PathBuf;
22 use syntax::ast;
23 use syntax_pos::{Span, DUMMY_SP};
24
25 /// Pointer to a registrar function.
26 pub type PluginRegistrarFun =
27     fn(&mut Registry);
28
29 pub struct PluginRegistrar {
30     pub fun: PluginRegistrarFun,
31     pub args: Vec<ast::NestedMetaItem>,
32 }
33
34 struct PluginLoader<'a> {
35     sess: &'a Session,
36     reader: CrateLoader<'a>,
37     plugins: Vec<PluginRegistrar>,
38 }
39
40 fn call_malformed_plugin_attribute(a: &Session, b: Span) {
41     span_err!(a, b, E0498, "malformed plugin attribute");
42 }
43
44 /// Read plugin metadata and dynamically load registrar functions.
45 pub fn load_plugins(sess: &Session,
46                     cstore: &CStore,
47                     krate: &ast::Crate,
48                     crate_name: &str,
49                     addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar> {
50     let mut loader = PluginLoader::new(sess, cstore, crate_name);
51
52     // do not report any error now. since crate attributes are
53     // not touched by expansion, every use of plugin without
54     // the feature enabled will result in an error later...
55     if sess.features_untracked().plugin {
56         for attr in &krate.attrs {
57             if !attr.check_name("plugin") {
58                 continue;
59             }
60
61             let plugins = match attr.meta_item_list() {
62                 Some(xs) => xs,
63                 None => {
64                     call_malformed_plugin_attribute(sess, attr.span);
65                     continue;
66                 }
67             };
68
69             for plugin in plugins {
70                 // plugins must have a name and can't be key = value
71                 match plugin.name() {
72                     Some(name) if !plugin.is_value_str() => {
73                         let args = plugin.meta_item_list().map(ToOwned::to_owned);
74                         loader.load_plugin(plugin.span, &name.as_str(), args.unwrap_or_default());
75                     },
76                     _ => call_malformed_plugin_attribute(sess, attr.span),
77                 }
78             }
79         }
80     }
81
82     if let Some(plugins) = addl_plugins {
83         for plugin in plugins {
84             loader.load_plugin(DUMMY_SP, &plugin, vec![]);
85         }
86     }
87
88     loader.plugins
89 }
90
91 impl<'a> PluginLoader<'a> {
92     fn new(sess: &'a Session, cstore: &'a CStore, crate_name: &str) -> Self {
93         PluginLoader {
94             sess,
95             reader: CrateLoader::new(sess, cstore, crate_name),
96             plugins: vec![],
97         }
98     }
99
100     fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) {
101         let registrar = self.reader.find_plugin_registrar(span, name);
102
103         if let Some((lib, disambiguator)) = registrar {
104             let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator);
105             let fun = self.dylink_registrar(span, lib, symbol);
106             self.plugins.push(PluginRegistrar {
107                 fun,
108                 args,
109             });
110         }
111     }
112
113     // Dynamically link a registrar function into the compiler process.
114     fn dylink_registrar(&mut self,
115                         span: Span,
116                         path: PathBuf,
117                         symbol: String) -> PluginRegistrarFun {
118         use rustc_metadata::dynamic_lib::DynamicLibrary;
119
120         // Make sure the path contains a / or the linker will search for it.
121         let path = env::current_dir().unwrap().join(&path);
122
123         let lib = match DynamicLibrary::open(Some(&path)) {
124             Ok(lib) => lib,
125             // this is fatal: there are almost certainly macros we need
126             // inside this crate, so continue would spew "macro undefined"
127             // errors
128             Err(err) => {
129                 self.sess.span_fatal(span, &err)
130             }
131         };
132
133         unsafe {
134             let registrar =
135                 match lib.symbol(&symbol) {
136                     Ok(registrar) => {
137                         mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
138                     }
139                     // again fatal if we can't register macros
140                     Err(err) => {
141                         self.sess.span_fatal(span, &err)
142                     }
143                 };
144
145             // Intentionally leak the dynamic library. We can't ever unload it
146             // since the library can make things that will live arbitrarily long
147             // (e.g. an @-box cycle or a thread).
148             mem::forget(lib);
149
150             registrar
151         }
152     }
153 }