2020-03-18 09:47:59 +00:00
|
|
|
//! Proc Macro Expander stub
|
|
|
|
|
2020-12-11 13:57:50 +00:00
|
|
|
use crate::db::AstDatabase;
|
2021-08-31 16:14:33 +00:00
|
|
|
use base_db::{CrateId, ProcMacroExpansionError, ProcMacroId};
|
2021-08-20 12:34:46 +00:00
|
|
|
use mbe::ExpandResult;
|
2020-03-18 09:47:59 +00:00
|
|
|
|
|
|
|
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
|
|
|
pub struct ProcMacroExpander {
|
|
|
|
krate: CrateId,
|
2020-09-18 14:43:50 +00:00
|
|
|
proc_macro_id: Option<ProcMacroId>,
|
2020-03-18 09:47:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ProcMacroExpander {
|
2020-09-18 14:43:50 +00:00
|
|
|
pub fn new(krate: CrateId, proc_macro_id: ProcMacroId) -> Self {
|
|
|
|
Self { krate, proc_macro_id: Some(proc_macro_id) }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn dummy(krate: CrateId) -> Self {
|
|
|
|
// FIXME: Should store the name for better errors
|
|
|
|
Self { krate, proc_macro_id: None }
|
2020-03-18 09:47:59 +00:00
|
|
|
}
|
|
|
|
|
2021-05-31 11:37:11 +00:00
|
|
|
pub fn is_dummy(&self) -> bool {
|
|
|
|
self.proc_macro_id.is_none()
|
|
|
|
}
|
|
|
|
|
2020-03-18 09:47:59 +00:00
|
|
|
pub fn expand(
|
2020-05-26 18:12:13 +00:00
|
|
|
self,
|
2020-03-18 09:47:59 +00:00
|
|
|
db: &dyn AstDatabase,
|
2020-12-11 13:57:50 +00:00
|
|
|
calling_crate: CrateId,
|
2020-03-18 12:56:46 +00:00
|
|
|
tt: &tt::Subtree,
|
2021-05-31 11:37:11 +00:00
|
|
|
attr_arg: Option<&tt::Subtree>,
|
2021-08-20 12:34:46 +00:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2020-09-18 14:43:50 +00:00
|
|
|
match self.proc_macro_id {
|
|
|
|
Some(id) => {
|
|
|
|
let krate_graph = db.crate_graph();
|
2021-08-20 12:34:46 +00:00
|
|
|
let proc_macro = match krate_graph[self.krate].proc_macro.get(id.0 as usize) {
|
|
|
|
Some(proc_macro) => proc_macro,
|
|
|
|
None => return ExpandResult::str_err("No derive macro found.".to_string()),
|
|
|
|
};
|
2020-09-18 14:43:50 +00:00
|
|
|
|
2020-12-11 13:57:50 +00:00
|
|
|
// Proc macros have access to the environment variables of the invoking crate.
|
|
|
|
let env = &krate_graph[calling_crate].env;
|
|
|
|
|
2021-08-31 16:14:33 +00:00
|
|
|
proc_macro
|
|
|
|
.expander
|
|
|
|
.expand(tt, attr_arg, env)
|
|
|
|
.map_err(|err| match err {
|
|
|
|
ProcMacroExpansionError::Panic(text) => mbe::ExpandError::Other(text),
|
|
|
|
ProcMacroExpansionError::System(text) => mbe::ExpandError::Other(text),
|
|
|
|
})
|
|
|
|
.into()
|
2020-09-18 14:43:50 +00:00
|
|
|
}
|
2021-08-20 12:34:46 +00:00
|
|
|
None => ExpandResult::only_err(mbe::ExpandError::UnresolvedProcMacro),
|
2020-09-18 14:43:50 +00:00
|
|
|
}
|
2020-03-18 09:47:59 +00:00
|
|
|
}
|
|
|
|
}
|