]> git.lizzy.rs Git - rust.git/blob - src/librustc/plugin/load.rs
Rollup merge of #21496 - ColonelJ:paatch, r=alexcrichton
[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, or a crate with exported macros.
12
13 use session::Session;
14 use metadata::creader::{CrateOrString, CrateReader};
15 use plugin::registry::Registry;
16
17 use std::mem;
18 use std::os;
19 use std::dynamic_lib::DynamicLibrary;
20 use std::collections::HashSet;
21 use syntax::ast;
22 use syntax::attr;
23 use syntax::codemap::Span;
24 use syntax::parse::token;
25 use syntax::ptr::P;
26 use syntax::visit;
27 use syntax::visit::Visitor;
28 use syntax::attr::AttrMetaMethods;
29
30 /// Pointer to a registrar function.
31 pub type PluginRegistrarFun =
32     fn(&mut Registry);
33
34 pub struct PluginRegistrar {
35     pub fun: PluginRegistrarFun,
36     pub args: P<ast::MetaItem>,
37 }
38
39 /// Information about loaded plugins.
40 pub struct Plugins {
41     /// Imported macros.
42     pub macros: Vec<ast::MacroDef>,
43     /// Registrars, as function pointers.
44     pub registrars: Vec<PluginRegistrar>,
45 }
46
47 pub struct PluginLoader<'a> {
48     sess: &'a Session,
49     span_whitelist: HashSet<Span>,
50     reader: CrateReader<'a>,
51     pub plugins: Plugins,
52 }
53
54 impl<'a> PluginLoader<'a> {
55     fn new(sess: &'a Session) -> PluginLoader<'a> {
56         PluginLoader {
57             sess: sess,
58             reader: CrateReader::new(sess),
59             span_whitelist: HashSet::new(),
60             plugins: Plugins {
61                 macros: vec!(),
62                 registrars: vec!(),
63             },
64         }
65     }
66 }
67
68 /// Read plugin metadata and dynamically load registrar functions.
69 pub fn load_plugins(sess: &Session, krate: &ast::Crate,
70                     addl_plugins: Option<Vec<String>>) -> Plugins {
71     let mut loader = PluginLoader::new(sess);
72
73     // We need to error on `#[macro_use] extern crate` when it isn't at the
74     // crate root, because `$crate` won't work properly. Identify these by
75     // spans, because the crate map isn't set up yet.
76     for item in krate.module.items.iter() {
77         if let ast::ItemExternCrate(_) = item.node {
78             loader.span_whitelist.insert(item.span);
79         }
80     }
81
82     visit::walk_crate(&mut loader, krate);
83
84     if let Some(plugins) = addl_plugins {
85         for plugin in plugins.iter() {
86             loader.load_plugin(CrateOrString::Str(plugin.as_slice()),
87                                                   None, None, None)
88         }
89     }
90
91     return loader.plugins;
92 }
93
94 // note that macros aren't expanded yet, and therefore macros can't add plugins.
95 impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
96     fn visit_item(&mut self, item: &ast::Item) {
97         // We're only interested in `extern crate`.
98         match item.node {
99             ast::ItemExternCrate(_) => {}
100             _ => {
101                 visit::walk_item(self, item);
102                 return;
103             }
104         }
105
106         // Parse the attributes relating to macro / plugin loading.
107         let mut plugin_attr = None;
108         let mut macro_selection = Some(HashSet::new());  // None => load all
109         let mut reexport = HashSet::new();
110         for attr in item.attrs.iter() {
111             let mut used = true;
112             match attr.name().get() {
113                 "phase" => {
114                     self.sess.span_err(attr.span, "#[phase] is deprecated; use \
115                                        #[macro_use], #[plugin], and/or #[no_link]");
116                 }
117                 "plugin" => {
118                     if plugin_attr.is_some() {
119                         self.sess.span_err(attr.span, "#[plugin] specified multiple times");
120                     }
121                     plugin_attr = Some(attr.node.value.clone());
122                 }
123                 "macro_use" => {
124                     let names = attr.meta_item_list();
125                     if names.is_none() {
126                         // no names => load all
127                         macro_selection = None;
128                     }
129                     if let (Some(sel), Some(names)) = (macro_selection.as_mut(), names) {
130                         for name in names.iter() {
131                             if let ast::MetaWord(ref name) = name.node {
132                                 sel.insert(name.clone());
133                             } else {
134                                 self.sess.span_err(name.span, "bad macro import");
135                             }
136                         }
137                     }
138                 }
139                 "macro_reexport" => {
140                     let names = match attr.meta_item_list() {
141                         Some(names) => names,
142                         None => {
143                             self.sess.span_err(attr.span, "bad macro reexport");
144                             continue;
145                         }
146                     };
147
148                     for name in names.iter() {
149                         if let ast::MetaWord(ref name) = name.node {
150                             reexport.insert(name.clone());
151                         } else {
152                             self.sess.span_err(name.span, "bad macro reexport");
153                         }
154                     }
155                 }
156                 _ => used = false,
157             }
158             if used {
159                 attr::mark_used(attr);
160             }
161         }
162
163         self.load_plugin(CrateOrString::Krate(item),
164                          plugin_attr,
165                          macro_selection,
166                          Some(reexport))
167     }
168
169     fn visit_mac(&mut self, _: &ast::Mac) {
170         // bummer... can't see plugins inside macros.
171         // do nothing.
172     }
173 }
174
175 impl<'a> PluginLoader<'a> {
176     pub fn load_plugin<'b>(&mut self,
177                            c: CrateOrString<'b>,
178                            plugin_attr: Option<P<ast::MetaItem>>,
179                            macro_selection: Option<HashSet<token::InternedString>>,
180                            reexport: Option<HashSet<token::InternedString>>) {
181         let mut macros = vec![];
182         let mut registrar = None;
183
184         let load_macros = match (macro_selection.as_ref(), reexport.as_ref()) {
185             (Some(sel), Some(re)) => sel.len() != 0 || re.len() != 0,
186             _ => true,
187         };
188         let load_registrar = plugin_attr.is_some();
189
190         if let CrateOrString::Krate(vi) = c {
191             if load_macros && !self.span_whitelist.contains(&vi.span) {
192                 self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \
193                                              the crate root");
194             }
195        }
196
197         if load_macros || load_registrar {
198             let pmd = self.reader.read_plugin_metadata(c);
199             if load_macros {
200                 macros = pmd.exported_macros();
201             }
202             if load_registrar {
203                 registrar = pmd.plugin_registrar();
204             }
205         }
206
207         for mut def in macros.into_iter() {
208             let name = token::get_ident(def.ident);
209             def.use_locally = match macro_selection.as_ref() {
210                 None => true,
211                 Some(sel) => sel.contains(&name),
212             };
213             def.export = if let Some(ref re) = reexport {
214                 re.contains(&name)
215             } else {
216                 false // Don't reexport macros from crates loaded from the command line
217             };
218             self.plugins.macros.push(def);
219         }
220
221         if let Some((lib, symbol)) = registrar {
222             let fun = self.dylink_registrar(c, lib, symbol);
223             self.plugins.registrars.push(PluginRegistrar {
224                 fun: fun,
225                 args: plugin_attr.unwrap(),
226             });
227         }
228     }
229
230     // Dynamically link a registrar function into the compiler process.
231     fn dylink_registrar<'b>(&mut self,
232                         c: CrateOrString<'b>,
233                         path: Path,
234                         symbol: String) -> PluginRegistrarFun {
235         // Make sure the path contains a / or the linker will search for it.
236         let path = os::make_absolute(&path).unwrap();
237
238         let lib = match DynamicLibrary::open(Some(&path)) {
239             Ok(lib) => lib,
240             // this is fatal: there are almost certainly macros we need
241             // inside this crate, so continue would spew "macro undefined"
242             // errors
243             Err(err) => {
244                 if let CrateOrString::Krate(cr) = c {
245                     self.sess.span_fatal(cr.span, &err[])
246                 } else {
247                     self.sess.fatal(&err[])
248                 }
249             }
250         };
251
252         unsafe {
253             let registrar =
254                 match lib.symbol(&symbol[]) {
255                     Ok(registrar) => {
256                         mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
257                     }
258                     // again fatal if we can't register macros
259                     Err(err) => {
260                         if let CrateOrString::Krate(cr) = c {
261                             self.sess.span_fatal(cr.span, &err[])
262                         } else {
263                             self.sess.fatal(&err[])
264                         }
265                     }
266                 };
267
268             // Intentionally leak the dynamic library. We can't ever unload it
269             // since the library can make things that will live arbitrarily long
270             // (e.g. an @-box cycle or a task).
271             mem::forget(lib);
272
273             registrar
274         }
275     }
276 }