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 item in &krate.module.items {
77 if let ast::ItemExternCrate(_) = item.node {
78 loader.span_whitelist.insert(item.span);
82 visit::walk_crate(&mut loader, krate);
84 if let Some(plugins) = addl_plugins {
85 for plugin in &plugins {
86 loader.load_plugin(CrateOrString::Str(plugin.as_slice()),
91 return loader.plugins;
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`.
99 ast::ItemExternCrate(_) => {}
101 visit::walk_item(self, item);
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 {
112 match attr.name().get() {
114 self.sess.span_err(attr.span, "#[phase] is deprecated; use \
115 #[macro_use], #[plugin], and/or #[no_link]");
118 if plugin_attr.is_some() {
119 self.sess.span_err(attr.span, "#[plugin] specified multiple times");
121 plugin_attr = Some(attr.node.value.clone());
124 let names = attr.meta_item_list();
126 // no names => load all
127 macro_selection = None;
129 if let (Some(sel), Some(names)) = (macro_selection.as_mut(), names) {
131 if let ast::MetaWord(ref name) = name.node {
132 sel.insert(name.clone());
134 self.sess.span_err(name.span, "bad macro import");
139 "macro_reexport" => {
140 let names = match attr.meta_item_list() {
141 Some(names) => names,
143 self.sess.span_err(attr.span, "bad macro reexport");
149 if let ast::MetaWord(ref name) = name.node {
150 reexport.insert(name.clone());
152 self.sess.span_err(name.span, "bad macro reexport");
159 attr::mark_used(attr);
163 self.load_plugin(CrateOrString::Krate(item),
169 fn visit_mac(&mut self, _: &ast::Mac) {
170 // bummer... can't see plugins inside macros.
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;
184 let load_macros = match (macro_selection.as_ref(), reexport.as_ref()) {
185 (Some(sel), Some(re)) => sel.len() != 0 || re.len() != 0,
188 let load_registrar = plugin_attr.is_some();
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 \
197 if load_macros || load_registrar {
198 let pmd = self.reader.read_plugin_metadata(c);
200 macros = pmd.exported_macros();
203 registrar = pmd.plugin_registrar();
207 for mut def in macros {
208 let name = token::get_ident(def.ident);
209 def.use_locally = match macro_selection.as_ref() {
211 Some(sel) => sel.contains(&name),
213 def.export = if let Some(ref re) = reexport {
216 false // Don't reexport macros from crates loaded from the command line
218 self.plugins.macros.push(def);
221 if let Some((lib, symbol)) = registrar {
222 let fun = self.dylink_registrar(c, lib, symbol);
223 self.plugins.registrars.push(PluginRegistrar {
225 args: plugin_attr.unwrap(),
230 // Dynamically link a registrar function into the compiler process.
231 fn dylink_registrar<'b>(&mut self,
232 c: CrateOrString<'b>,
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();
238 let lib = match DynamicLibrary::open(Some(&path)) {
240 // this is fatal: there are almost certainly macros we need
241 // inside this crate, so continue would spew "macro undefined"
244 if let CrateOrString::Krate(cr) = c {
245 self.sess.span_fatal(cr.span, &err[])
247 self.sess.fatal(&err[])
254 match lib.symbol(&symbol[]) {
256 mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
258 // again fatal if we can't register macros
260 if let CrateOrString::Krate(cr) = c {
261 self.sess.span_fatal(cr.span, &err[])
263 self.sess.fatal(&err[])
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).