1 //! Proc Macro Expander stub
3 use base_db::{CrateId, ProcMacroExpansionError, ProcMacroId, ProcMacroKind};
5 use crate::{db::AstDatabase, ExpandError, ExpandResult};
7 #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
8 pub struct ProcMacroExpander {
10 proc_macro_id: Option<ProcMacroId>,
13 impl ProcMacroExpander {
14 pub fn new(krate: CrateId, proc_macro_id: ProcMacroId) -> Self {
15 Self { krate, proc_macro_id: Some(proc_macro_id) }
18 pub fn dummy(krate: CrateId) -> Self {
19 // FIXME: Should store the name for better errors
20 Self { krate, proc_macro_id: None }
23 pub fn is_dummy(&self) -> bool {
24 self.proc_macro_id.is_none()
30 calling_crate: CrateId,
32 attr_arg: Option<&tt::Subtree>,
33 ) -> ExpandResult<tt::Subtree> {
34 match self.proc_macro_id {
36 let krate_graph = db.crate_graph();
37 let proc_macro = match krate_graph[self.krate].proc_macro.get(id.0 as usize) {
38 Some(proc_macro) => proc_macro,
40 return ExpandResult::only_err(ExpandError::Other(
41 "No proc-macro found.".into(),
46 // Proc macros have access to the environment variables of the invoking crate.
47 let env = &krate_graph[calling_crate].env;
48 match proc_macro.expander.expand(tt, attr_arg, env) {
49 Ok(t) => ExpandResult::ok(t),
50 Err(err) => match err {
51 // Don't discard the item in case something unexpected happened while expanding attributes
52 ProcMacroExpansionError::System(text)
53 if proc_macro.kind == ProcMacroKind::Attr =>
57 err: Some(ExpandError::Other(text.into())),
60 ProcMacroExpansionError::System(text)
61 | ProcMacroExpansionError::Panic(text) => {
62 ExpandResult::only_err(ExpandError::Other(text.into()))
67 None => ExpandResult::only_err(ExpandError::UnresolvedProcMacro),