1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#![allow(unreachable_pub)]
mod dylib;
mod abis;
use std::{
collections::{hash_map::Entry, HashMap},
env, fs,
path::{Path, PathBuf},
time::SystemTime,
};
use proc_macro_api::{
msg::{ExpandMacro, FlatTree, PanicMessage},
ProcMacroKind,
};
#[derive(Default)]
pub(crate) struct ProcMacroSrv {
expanders: HashMap<(PathBuf, SystemTime), dylib::Expander>,
}
impl ProcMacroSrv {
pub fn expand(&mut self, task: ExpandMacro) -> Result<FlatTree, PanicMessage> {
let expander = self.expander(task.lib.as_ref()).map_err(|err| {
debug_assert!(false, "should list macros before asking to expand");
PanicMessage(format!("failed to load macro: {}", err))
})?;
let mut prev_env = HashMap::new();
for (k, v) in &task.env {
prev_env.insert(k.as_str(), env::var_os(k));
env::set_var(k, v);
}
let macro_body = task.macro_body.to_subtree();
let attributes = task.attributes.map(|it| it.to_subtree());
let result = expander
.expand(&task.macro_name, ¯o_body, attributes.as_ref())
.map(|it| FlatTree::new(&it));
for (k, _) in &task.env {
match &prev_env[k.as_str()] {
Some(v) => env::set_var(k, v),
None => env::remove_var(k),
}
}
result.map_err(PanicMessage)
}
pub(crate) fn list_macros(
&mut self,
dylib_path: &Path,
) -> Result<Vec<(String, ProcMacroKind)>, String> {
let expander = self.expander(dylib_path)?;
Ok(expander.list_macros())
}
fn expander(&mut self, path: &Path) -> Result<&dylib::Expander, String> {
let time = fs::metadata(path).and_then(|it| it.modified()).map_err(|err| {
format!("Failed to get file metadata for {}: {:?}", path.display(), err)
})?;
Ok(match self.expanders.entry((path.to_path_buf(), time)) {
Entry::Vacant(v) => v.insert(dylib::Expander::new(path).map_err(|err| {
format!("Cannot create expander for {}: {:?}", path.display(), err)
})?),
Entry::Occupied(e) => e.into_mut(),
})
}
}
pub mod cli;
#[cfg(test)]
mod tests;