rust-analyzer/crates/ra_hir_expand/src/proc_macro.rs

58 lines
1.6 KiB
Rust
Raw Normal View History

2020-03-18 09:47:59 +00:00
//! Proc Macro Expander stub
2020-03-18 12:56:46 +00:00
use crate::{db::AstDatabase, LazyMacroId};
use ra_db::{CrateId, ProcMacroId};
2020-03-18 09:47:59 +00:00
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct ProcMacroExpander {
krate: CrateId,
2020-03-18 12:56:46 +00:00
proc_macro_id: ProcMacroId,
2020-03-18 09:47:59 +00:00
}
2020-03-26 20:26:34 +00:00
macro_rules! err {
($fmt:literal, $($tt:tt),*) => {
mbe::ExpandError::ProcMacroError(tt::ExpansionError::Unknown(format!($fmt, $($tt),*)))
};
($fmt:literal) => {
mbe::ExpandError::ProcMacroError(tt::ExpansionError::Unknown($fmt.to_string()))
}
}
2020-03-18 09:47:59 +00:00
impl ProcMacroExpander {
2020-03-18 12:56:46 +00:00
pub fn new(krate: CrateId, proc_macro_id: ProcMacroId) -> ProcMacroExpander {
ProcMacroExpander { krate, proc_macro_id }
2020-03-18 09:47:59 +00:00
}
pub fn expand(
&self,
db: &dyn AstDatabase,
2020-03-18 12:56:46 +00:00
_id: LazyMacroId,
tt: &tt::Subtree,
2020-03-18 09:47:59 +00:00
) -> Result<tt::Subtree, mbe::ExpandError> {
2020-03-18 12:56:46 +00:00
let krate_graph = db.crate_graph();
let proc_macro = krate_graph[self.krate]
.proc_macro
2020-03-26 16:41:44 +00:00
.get(self.proc_macro_id.0 as usize)
2020-03-18 12:56:46 +00:00
.clone()
2020-03-26 20:26:34 +00:00
.ok_or_else(|| err!("No derive macro found."))?;
let tt = remove_derive_atr(tt, &proc_macro.name)
.ok_or_else(|| err!("Fail to remove derive for custom derive"))?;
2020-03-26 16:41:44 +00:00
proc_macro.expander.expand(&tt, None).map_err(mbe::ExpandError::from)
2020-03-18 09:47:59 +00:00
}
}
2020-03-26 20:26:34 +00:00
fn remove_derive_atr(tt: &tt::Subtree, _name: &str) -> Option<tt::Subtree> {
// FIXME: proper handle the remove derive
// We assume the first 2 tokens are #[derive(name)]
if tt.token_trees.len() > 2 {
let mut tt = tt.clone();
tt.token_trees.remove(0);
tt.token_trees.remove(0);
return Some(tt);
}
None
}