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.
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.
11 //! Used by `rustc` when loading a plugin, or a crate with exported macros.
14 use metadata::creader::{CrateOrString, CrateReader};
15 use plugin::registry::Registry;
19 use std::dynamic_lib::DynamicLibrary;
20 use std::collections::HashSet;
23 use syntax::codemap::Span;
24 use syntax::parse::token;
27 use syntax::visit::Visitor;
28 use syntax::attr::AttrMetaMethods;
30 /// Pointer to a registrar function.
31 pub type PluginRegistrarFun =
34 pub struct PluginRegistrar {
35 pub fun: PluginRegistrarFun,
36 pub args: P<ast::MetaItem>,
39 /// Information about loaded plugins.
42 pub macros: Vec<ast::MacroDef>,
43 /// Registrars, as function pointers.
44 pub registrars: Vec<PluginRegistrar>,
47 pub struct PluginLoader<'a> {
49 span_whitelist: HashSet<Span>,
50 reader: CrateReader<'a>,
54 impl<'a> PluginLoader<'a> {
55 fn new(sess: &'a Session) -> PluginLoader<'a> {
58 reader: CrateReader::new(sess),
59 span_whitelist: HashSet::new(),
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);
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 vi in krate.module.view_items.iter() {
77 loader.span_whitelist.insert(vi.span);
80 visit::walk_crate(&mut loader, krate);
82 if let Some(plugins) = addl_plugins {
83 for plugin in plugins.iter() {
84 loader.load_plugin(CrateOrString::Str(plugin.as_slice()),
89 return loader.plugins;
92 // note that macros aren't expanded yet, and therefore macros can't add plugins.
93 impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
94 fn visit_view_item(&mut self, vi: &ast::ViewItem) {
95 // We're only interested in `extern crate`.
97 ast::ViewItemExternCrate(..) => (),
101 // Parse the attributes relating to macro / plugin loading.
102 let mut plugin_attr = None;
103 let mut macro_selection = Some(HashSet::new()); // None => load all
104 let mut reexport = HashSet::new();
105 for attr in vi.attrs.iter() {
107 match attr.name().get() {
109 self.sess.span_err(attr.span, "#[phase] is deprecated; use \
110 #[macro_use], #[plugin], and/or #[no_link]");
113 if plugin_attr.is_some() {
114 self.sess.span_err(attr.span, "#[plugin] specified multiple times");
116 plugin_attr = Some(attr.node.value.clone());
119 let names = attr.meta_item_list();
121 // no names => load all
122 macro_selection = None;
124 if let (Some(sel), Some(names)) = (macro_selection.as_mut(), names) {
125 for name in names.iter() {
126 if let ast::MetaWord(ref name) = name.node {
127 sel.insert(name.clone());
129 self.sess.span_err(name.span, "bad macro import");
134 "macro_reexport" => {
135 let names = match attr.meta_item_list() {
136 Some(names) => names,
138 self.sess.span_err(attr.span, "bad macro reexport");
143 for name in names.iter() {
144 if let ast::MetaWord(ref name) = name.node {
145 reexport.insert(name.clone());
147 self.sess.span_err(name.span, "bad macro reexport");
154 attr::mark_used(attr);
158 self.load_plugin(CrateOrString::Krate(vi), plugin_attr, macro_selection, Some(reexport))
161 fn visit_mac(&mut self, _: &ast::Mac) {
162 // bummer... can't see plugins inside macros.
167 impl<'a> PluginLoader<'a> {
168 pub fn load_plugin<'b>(&mut self,
169 c: CrateOrString<'b>,
170 plugin_attr: Option<P<ast::MetaItem>>,
171 macro_selection: Option<HashSet<token::InternedString>>,
172 reexport: Option<HashSet<token::InternedString>>) {
173 let mut macros = vec![];
174 let mut registrar = None;
176 let load_macros = match (macro_selection.as_ref(), reexport.as_ref()) {
177 (Some(sel), Some(re)) => sel.len() != 0 || re.len() != 0,
180 let load_registrar = plugin_attr.is_some();
182 if let CrateOrString::Krate(vi) = c {
183 if load_macros && !self.span_whitelist.contains(&vi.span) {
184 self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \
189 if load_macros || load_registrar {
190 let pmd = self.reader.read_plugin_metadata(c);
192 macros = pmd.exported_macros();
195 registrar = pmd.plugin_registrar();
199 for mut def in macros.into_iter() {
200 let name = token::get_ident(def.ident);
201 def.use_locally = match macro_selection.as_ref() {
203 Some(sel) => sel.contains(&name),
205 def.export = if let Some(ref re) = reexport {
208 false // Don't reexport macros from crates loaded from the command line
210 self.plugins.macros.push(def);
213 if let Some((lib, symbol)) = registrar {
214 let fun = self.dylink_registrar(c, lib, symbol);
215 self.plugins.registrars.push(PluginRegistrar {
217 args: plugin_attr.unwrap(),
222 // Dynamically link a registrar function into the compiler process.
223 fn dylink_registrar<'b>(&mut self,
224 c: CrateOrString<'b>,
226 symbol: String) -> PluginRegistrarFun {
227 // Make sure the path contains a / or the linker will search for it.
228 let path = os::make_absolute(&path).unwrap();
230 let lib = match DynamicLibrary::open(Some(&path)) {
232 // this is fatal: there are almost certainly macros we need
233 // inside this crate, so continue would spew "macro undefined"
236 if let CrateOrString::Krate(cr) = c {
237 self.sess.span_fatal(cr.span, &err[])
239 self.sess.fatal(&err[])
246 match lib.symbol(&symbol[]) {
248 mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
250 // again fatal if we can't register macros
252 if let CrateOrString::Krate(cr) = c {
253 self.sess.span_fatal(cr.span, &err[])
255 self.sess.fatal(&err[])
260 // Intentionally leak the dynamic library. We can't ever unload it
261 // since the library can make things that will live arbitrarily long
262 // (e.g. an @-box cycle or a task).