]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/eager.rs
More correct `$crate` handling in eager macros
[rust.git] / crates / hir_expand / src / eager.rs
1 //! Eager expansion related utils
2 //!
3 //! Here is a dump of a discussion from Vadim Petrochenkov about Eager Expansion and
4 //! Its name resolution :
5 //!
6 //! > Eagerly expanded macros (and also macros eagerly expanded by eagerly expanded macros,
7 //! > which actually happens in practice too!) are resolved at the location of the "root" macro
8 //! > that performs the eager expansion on its arguments.
9 //! > If some name cannot be resolved at the eager expansion time it's considered unresolved,
10 //! > even if becomes available later (e.g. from a glob import or other macro).
11 //!
12 //! > Eagerly expanded macros don't add anything to the module structure of the crate and
13 //! > don't build any speculative module structures, i.e. they are expanded in a "flat"
14 //! > way even if tokens in them look like modules.
15 //!
16 //! > In other words, it kinda works for simple cases for which it was originally intended,
17 //! > and we need to live with it because it's available on stable and widely relied upon.
18 //!
19 //!
20 //! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros>
21 use std::sync::Arc;
22
23 use base_db::CrateId;
24 use mbe::ExpandResult;
25 use syntax::{ted, SyntaxNode};
26
27 use crate::{
28     ast::{self, AstNode},
29     db::AstDatabase,
30     hygiene::Hygiene,
31     mod_path::ModPath,
32     EagerCallInfo, ExpandTo, InFile, MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId,
33     MacroDefKind, UnresolvedMacro,
34 };
35
36 #[derive(Debug)]
37 pub struct ErrorEmitted {
38     _private: (),
39 }
40
41 pub trait ErrorSink {
42     fn emit(&mut self, err: mbe::ExpandError);
43
44     fn option<T>(
45         &mut self,
46         opt: Option<T>,
47         error: impl FnOnce() -> mbe::ExpandError,
48     ) -> Result<T, ErrorEmitted> {
49         match opt {
50             Some(it) => Ok(it),
51             None => {
52                 self.emit(error());
53                 Err(ErrorEmitted { _private: () })
54             }
55         }
56     }
57
58     fn option_with<T>(
59         &mut self,
60         opt: impl FnOnce() -> Option<T>,
61         error: impl FnOnce() -> mbe::ExpandError,
62     ) -> Result<T, ErrorEmitted> {
63         self.option(opt(), error)
64     }
65
66     fn result<T>(&mut self, res: Result<T, mbe::ExpandError>) -> Result<T, ErrorEmitted> {
67         match res {
68             Ok(it) => Ok(it),
69             Err(e) => {
70                 self.emit(e);
71                 Err(ErrorEmitted { _private: () })
72             }
73         }
74     }
75
76     fn expand_result_option<T>(&mut self, res: ExpandResult<Option<T>>) -> Result<T, ErrorEmitted> {
77         match (res.value, res.err) {
78             (None, Some(err)) => {
79                 self.emit(err);
80                 Err(ErrorEmitted { _private: () })
81             }
82             (Some(value), opt_err) => {
83                 if let Some(err) = opt_err {
84                     self.emit(err);
85                 }
86                 Ok(value)
87             }
88             (None, None) => unreachable!("`ExpandResult` without value or error"),
89         }
90     }
91 }
92
93 impl ErrorSink for &'_ mut dyn FnMut(mbe::ExpandError) {
94     fn emit(&mut self, err: mbe::ExpandError) {
95         self(err);
96     }
97 }
98
99 pub fn expand_eager_macro(
100     db: &dyn AstDatabase,
101     krate: CrateId,
102     macro_call: InFile<ast::MacroCall>,
103     def: MacroDefId,
104     resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
105     diagnostic_sink: &mut dyn FnMut(mbe::ExpandError),
106 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
107     let hygiene = Hygiene::new(db, macro_call.file_id);
108     let parsed_args = macro_call
109         .value
110         .token_tree()
111         .map(|tt| mbe::syntax_node_to_token_tree(tt.syntax()).0)
112         .unwrap_or_default();
113
114     let ast_map = db.ast_id_map(macro_call.file_id);
115     let call_id = InFile::new(macro_call.file_id, ast_map.ast_id(&macro_call.value));
116     let expand_to = ExpandTo::from_call_site(&macro_call.value);
117
118     // Note:
119     // When `lazy_expand` is called, its *parent* file must be already exists.
120     // Here we store an eager macro id for the argument expanded subtree here
121     // for that purpose.
122     let arg_id = db.intern_macro_call(MacroCallLoc {
123         def,
124         krate,
125         eager: Some(EagerCallInfo {
126             arg_or_expansion: Arc::new(parsed_args.clone()),
127             included_file: None,
128         }),
129         kind: MacroCallKind::FnLike { ast_id: call_id, expand_to: ExpandTo::Expr },
130     });
131
132     let parsed_args = mbe::token_tree_to_syntax_node(&parsed_args, mbe::TopEntryPoint::Expr).0;
133     let result = match eager_macro_recur(
134         db,
135         &hygiene,
136         InFile::new(arg_id.as_file(), parsed_args.syntax_node()),
137         krate,
138         resolver,
139         diagnostic_sink,
140     ) {
141         Ok(Ok(it)) => it,
142         Ok(Err(err)) => return Ok(Err(err)),
143         Err(err) => return Err(err),
144     };
145     let subtree = to_subtree(&result);
146
147     if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
148         let res = eager.expand(db, arg_id, &subtree);
149         if let Some(err) = res.err {
150             diagnostic_sink(err);
151         }
152
153         let loc = MacroCallLoc {
154             def,
155             krate,
156             eager: Some(EagerCallInfo {
157                 arg_or_expansion: Arc::new(res.value.subtree),
158                 included_file: res.value.included_file,
159             }),
160             kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
161         };
162
163         Ok(Ok(db.intern_macro_call(loc)))
164     } else {
165         panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
166     }
167 }
168
169 fn to_subtree(node: &SyntaxNode) -> tt::Subtree {
170     let mut subtree = mbe::syntax_node_to_token_tree(node).0;
171     subtree.delimiter = None;
172     subtree
173 }
174
175 fn lazy_expand(
176     db: &dyn AstDatabase,
177     def: &MacroDefId,
178     macro_call: InFile<ast::MacroCall>,
179     krate: CrateId,
180 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
181     let ast_id = db.ast_id_map(macro_call.file_id).ast_id(&macro_call.value);
182
183     let expand_to = ExpandTo::from_call_site(&macro_call.value);
184     let id = def.as_lazy_macro(
185         db,
186         krate,
187         MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), expand_to },
188     );
189
190     let err = db.macro_expand_error(id);
191     let value = db.parse_or_expand(id.as_file()).map(|node| InFile::new(id.as_file(), node));
192
193     ExpandResult { value, err }
194 }
195
196 fn eager_macro_recur(
197     db: &dyn AstDatabase,
198     hygiene: &Hygiene,
199     curr: InFile<SyntaxNode>,
200     krate: CrateId,
201     macro_resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
202     mut diagnostic_sink: &mut dyn FnMut(mbe::ExpandError),
203 ) -> Result<Result<SyntaxNode, ErrorEmitted>, UnresolvedMacro> {
204     let original = curr.value.clone_for_update();
205
206     let children = original.descendants().filter_map(ast::MacroCall::cast);
207     let mut replacements = Vec::new();
208
209     // Collect replacement
210     for child in children {
211         let def = match child.path().and_then(|path| ModPath::from_src(db, path, &hygiene)) {
212             Some(path) => macro_resolver(path.clone()).ok_or_else(|| UnresolvedMacro { path })?,
213             None => {
214                 diagnostic_sink(mbe::ExpandError::Other("malformed macro invocation".into()));
215                 continue;
216             }
217         };
218         let insert = match def.kind {
219             MacroDefKind::BuiltInEager(..) => {
220                 let id = match expand_eager_macro(
221                     db,
222                     krate,
223                     curr.with_value(child.clone()),
224                     def,
225                     macro_resolver,
226                     diagnostic_sink,
227                 ) {
228                     Ok(Ok(it)) => it,
229                     Ok(Err(err)) => return Ok(Err(err)),
230                     Err(err) => return Err(err),
231                 };
232                 db.parse_or_expand(id.as_file())
233                     .expect("successful macro expansion should be parseable")
234                     .clone_for_update()
235             }
236             MacroDefKind::Declarative(_)
237             | MacroDefKind::BuiltIn(..)
238             | MacroDefKind::BuiltInAttr(..)
239             | MacroDefKind::BuiltInDerive(..)
240             | MacroDefKind::ProcMacro(..) => {
241                 let res = lazy_expand(db, &def, curr.with_value(child.clone()), krate);
242                 let val = match diagnostic_sink.expand_result_option(res) {
243                     Ok(it) => it,
244                     Err(err) => return Ok(Err(err)),
245                 };
246
247                 // replace macro inside
248                 let hygiene = Hygiene::new(db, val.file_id);
249                 match eager_macro_recur(db, &hygiene, val, krate, macro_resolver, diagnostic_sink) {
250                     Ok(Ok(it)) => it,
251                     Ok(Err(err)) => return Ok(Err(err)),
252                     Err(err) => return Err(err),
253                 }
254             }
255         };
256
257         // check if the whole original syntax is replaced
258         if child.syntax() == &original {
259             return Ok(Ok(insert));
260         }
261
262         replacements.push((child, insert));
263     }
264
265     replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
266     Ok(Ok(original))
267 }