]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/proc_macro.rs
feat: support concat_bytes
[rust.git] / crates / hir_expand / src / proc_macro.rs
1 //! Proc Macro Expander stub
2
3 use base_db::{CrateId, ProcMacroExpansionError, ProcMacroId, ProcMacroKind};
4
5 use crate::{db::AstDatabase, ExpandError, ExpandResult};
6
7 #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
8 pub struct ProcMacroExpander {
9     krate: CrateId,
10     proc_macro_id: Option<ProcMacroId>,
11 }
12
13 impl ProcMacroExpander {
14     pub fn new(krate: CrateId, proc_macro_id: ProcMacroId) -> Self {
15         Self { krate, proc_macro_id: Some(proc_macro_id) }
16     }
17
18     pub fn dummy(krate: CrateId) -> Self {
19         // FIXME: Should store the name for better errors
20         Self { krate, proc_macro_id: None }
21     }
22
23     pub fn is_dummy(&self) -> bool {
24         self.proc_macro_id.is_none()
25     }
26
27     pub fn expand(
28         self,
29         db: &dyn AstDatabase,
30         calling_crate: CrateId,
31         tt: &tt::Subtree,
32         attr_arg: Option<&tt::Subtree>,
33     ) -> ExpandResult<tt::Subtree> {
34         match self.proc_macro_id {
35             Some(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,
39                     None => {
40                         return ExpandResult::only_err(ExpandError::Other(
41                             "No proc-macro found.".into(),
42                         ))
43                     }
44                 };
45
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 =>
54                         {
55                             ExpandResult {
56                                 value: tt.clone(),
57                                 err: Some(ExpandError::Other(text.into())),
58                             }
59                         }
60                         ProcMacroExpansionError::System(text)
61                         | ProcMacroExpansionError::Panic(text) => {
62                             ExpandResult::only_err(ExpandError::Other(text.into()))
63                         }
64                     },
65                 }
66             }
67             None => ExpandResult::only_err(ExpandError::UnresolvedProcMacro),
68         }
69     }
70 }