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::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 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<Plugins>) -> 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 let mut plugins = loader.plugins;
85 Some(addl_plugins) => {
86 // Add in the additional plugins requested by the frontend
87 let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins;
88 plugins.macros.extend(addl_macros.into_iter());
89 plugins.registrars.extend(addl_registrars.into_iter());
97 // note that macros aren't expanded yet, and therefore macros can't add plugins.
98 impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
99 fn visit_view_item(&mut self, vi: &ast::ViewItem) {
100 // We're only interested in `extern crate`.
102 ast::ViewItemExternCrate(..) => (),
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 vi.attrs.iter() {
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) {
130 for name in names.iter() {
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");
148 for name in names.iter() {
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 let mut macros = vec![];
164 let mut registrar = None;
166 let load_macros = match macro_selection.as_ref() {
167 Some(sel) => sel.len() != 0 || reexport.len() != 0,
170 let load_registrar = plugin_attr.is_some();
172 if load_macros && !self.span_whitelist.contains(&vi.span) {
173 self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \
177 if load_macros || load_registrar {
178 let pmd = self.reader.read_plugin_metadata(vi);
180 macros = pmd.exported_macros();
183 registrar = pmd.plugin_registrar();
187 for mut def in macros.into_iter() {
188 let name = token::get_ident(def.ident);
189 def.use_locally = match macro_selection.as_ref() {
191 Some(sel) => sel.contains(&name),
193 def.export = reexport.contains(&name);
194 self.plugins.macros.push(def);
197 if let Some((lib, symbol)) = registrar {
198 let fun = self.dylink_registrar(vi, lib, symbol);
199 self.plugins.registrars.push(PluginRegistrar {
201 args: plugin_attr.unwrap(),
206 fn visit_mac(&mut self, _: &ast::Mac) {
207 // bummer... can't see plugins inside macros.
212 impl<'a> PluginLoader<'a> {
213 // Dynamically link a registrar function into the compiler process.
214 fn dylink_registrar(&mut self,
217 symbol: String) -> PluginRegistrarFun {
218 // Make sure the path contains a / or the linker will search for it.
219 let path = os::make_absolute(&path).unwrap();
221 let lib = match DynamicLibrary::open(Some(&path)) {
223 // this is fatal: there are almost certainly macros we need
224 // inside this crate, so continue would spew "macro undefined"
226 Err(err) => self.sess.span_fatal(vi.span, err[])
231 match lib.symbol(symbol[]) {
233 mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
235 // again fatal if we can't register macros
236 Err(err) => self.sess.span_fatal(vi.span, err[])
239 // Intentionally leak the dynamic library. We can't ever unload it
240 // since the library can make things that will live arbitrarily long
241 // (e.g. an @-box cycle or a task).