rust-analyzer/crates/ra_proc_macro_srv/src/lib.rs

64 lines
2.1 KiB
Rust
Raw Normal View History

2020-04-01 05:11:26 +00:00
//! RA Proc Macro Server
//!
//! This library is able to call compiled Rust custom derive dynamic libraries on arbitrary code.
//! The general idea here is based on https://github.com/fedochet/rust-proc-macro-expander.
//!
2020-04-20 18:26:10 +00:00
//! But we adapt it to better fit RA needs:
2020-04-01 05:11:26 +00:00
//!
//! * We use `ra_tt` for proc-macro `TokenStream` server, it is easier to manipulate and interact with
2020-04-20 18:26:10 +00:00
//! RA than `proc-macro2` token stream.
2020-04-01 05:11:26 +00:00
//! * By **copying** the whole rustc `lib_proc_macro` code, we are able to build this with `stable`
//! rustc rather than `unstable`. (Although in gerenal ABI compatibility is still an issue)
#[allow(dead_code)]
#[doc(hidden)]
mod proc_macro;
2020-04-04 08:07:22 +00:00
#[doc(hidden)]
mod rustc_server;
2020-04-04 08:09:36 +00:00
mod dylib;
2020-04-04 08:28:32 +00:00
use proc_macro::bridge::client::TokenStream;
2020-04-01 05:11:26 +00:00
use ra_proc_macro::{ExpansionResult, ExpansionTask, ListMacrosResult, ListMacrosTask};
2020-04-24 02:23:01 +00:00
use std::{
collections::{hash_map::Entry, HashMap},
path::{Path, PathBuf},
};
#[derive(Default)]
pub(crate) struct ProcMacroSrv {
expanders: HashMap<PathBuf, dylib::Expander>,
}
2020-04-04 08:10:45 +00:00
2020-04-24 02:23:01 +00:00
impl ProcMacroSrv {
pub fn expand(&mut self, task: &ExpansionTask) -> Result<ExpansionResult, String> {
let expander = self.expander(&task.lib)?;
match expander.expand(&task.macro_name, &task.macro_body, task.attributes.as_ref()) {
Ok(expansion) => Ok(ExpansionResult { expansion }),
Err(msg) => {
Err(format!("Cannot perform expansion for {}: error {:?}", &task.macro_name, msg))
}
2020-04-04 08:10:45 +00:00
}
}
2020-04-24 02:23:01 +00:00
pub fn list_macros(&mut self, task: &ListMacrosTask) -> Result<ListMacrosResult, String> {
let expander = self.expander(&task.lib)?;
Ok(ListMacrosResult { macros: expander.list_macros() })
}
2020-04-20 18:26:10 +00:00
2020-04-24 02:23:01 +00:00
fn expander(&mut self, path: &Path) -> Result<&dylib::Expander, String> {
Ok(match self.expanders.entry(path.to_path_buf()) {
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(),
})
}
2020-04-01 05:11:26 +00:00
}
2020-04-09 17:43:47 +00:00
pub mod cli;
2020-04-09 17:43:47 +00:00
#[cfg(test)]
mod tests;