1 //! RA Proc Macro Server
3 //! This library is able to call compiled Rust custom derive dynamic libraries on arbitrary code.
4 //! The general idea here is based on <https://github.com/fedochet/rust-proc-macro-expander>.
6 //! But we adapt it to better fit RA needs:
8 //! * We use `tt` for proc-macro `TokenStream` server, it is easier to manipulate and interact with
9 //! RA than `proc-macro2` token stream.
10 //! * By **copying** the whole rustc `lib_proc_macro` code, we are able to build this with `stable`
11 //! rustc rather than `unstable`. (Although in general ABI compatibility is still an issue)…
12 #![allow(unreachable_pub)]
18 collections::{hash_map::Entry, HashMap},
22 path::{Path, PathBuf},
27 msg::{ExpandMacro, FlatTree, PanicMessage},
32 pub(crate) struct ProcMacroSrv {
33 expanders: HashMap<(PathBuf, SystemTime), dylib::Expander>,
37 pub fn expand(&mut self, task: ExpandMacro) -> Result<FlatTree, PanicMessage> {
38 let expander = self.expander(task.lib.as_ref()).map_err(|err| {
39 debug_assert!(false, "should list macros before asking to expand");
40 PanicMessage(format!("failed to load macro: {}", err))
43 let prev_env = EnvSnapshot::new();
44 for (k, v) in &task.env {
47 let prev_working_dir = match task.current_dir {
49 let prev_working_dir = std::env::current_dir().ok();
50 if let Err(err) = std::env::set_current_dir(&dir) {
51 eprintln!("Failed to set the current working dir to {}. Error: {:?}", dir, err)
58 let macro_body = task.macro_body.to_subtree();
59 let attributes = task.attributes.map(|it| it.to_subtree());
61 .expand(&task.macro_name, ¯o_body, attributes.as_ref())
62 .map(|it| FlatTree::new(&it));
66 if let Some(dir) = prev_working_dir {
67 if let Err(err) = std::env::set_current_dir(&dir) {
69 "Failed to set the current working dir to {}. Error: {:?}",
76 result.map_err(PanicMessage)
79 pub(crate) fn list_macros(
82 ) -> Result<Vec<(String, ProcMacroKind)>, String> {
83 let expander = self.expander(dylib_path)?;
84 Ok(expander.list_macros())
87 fn expander(&mut self, path: &Path) -> Result<&dylib::Expander, String> {
88 let time = fs::metadata(path).and_then(|it| it.modified()).map_err(|err| {
89 format!("Failed to get file metadata for {}: {:?}", path.display(), err)
92 Ok(match self.expanders.entry((path.to_path_buf(), time)) {
93 Entry::Vacant(v) => v.insert(dylib::Expander::new(path).map_err(|err| {
94 format!("Cannot create expander for {}: {:?}", path.display(), err)
96 Entry::Occupied(e) => e.into_mut(),
102 vars: HashMap<OsString, OsString>,
106 fn new() -> EnvSnapshot {
107 EnvSnapshot { vars: env::vars_os().collect() }
111 let mut old_vars = self.vars;
112 for (name, value) in env::vars_os() {
113 let old_value = old_vars.remove(&name);
114 if old_value != Some(value) {
116 None => env::remove_var(name),
117 Some(old_value) => env::set_var(name, old_value),
121 for (name, old_value) in old_vars {
122 env::set_var(name, old_value)