]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/eager.rs
internal: Split unresolve proc-macro error out of mbe
[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 syntax::{ted, SyntaxNode};
25
26 use crate::{
27     ast::{self, AstNode},
28     db::AstDatabase,
29     hygiene::Hygiene,
30     mod_path::ModPath,
31     EagerCallInfo, ExpandError, ExpandResult, ExpandTo, InFile, MacroCallId, MacroCallKind,
32     MacroCallLoc, MacroDefId, MacroDefKind, UnresolvedMacro,
33 };
34
35 #[derive(Debug)]
36 pub struct ErrorEmitted {
37     _private: (),
38 }
39
40 pub trait ErrorSink {
41     fn emit(&mut self, err: ExpandError);
42
43     fn option<T>(
44         &mut self,
45         opt: Option<T>,
46         error: impl FnOnce() -> ExpandError,
47     ) -> Result<T, ErrorEmitted> {
48         match opt {
49             Some(it) => Ok(it),
50             None => {
51                 self.emit(error());
52                 Err(ErrorEmitted { _private: () })
53             }
54         }
55     }
56
57     fn option_with<T>(
58         &mut self,
59         opt: impl FnOnce() -> Option<T>,
60         error: impl FnOnce() -> ExpandError,
61     ) -> Result<T, ErrorEmitted> {
62         self.option(opt(), error)
63     }
64
65     fn result<T>(&mut self, res: Result<T, ExpandError>) -> Result<T, ErrorEmitted> {
66         match res {
67             Ok(it) => Ok(it),
68             Err(e) => {
69                 self.emit(e);
70                 Err(ErrorEmitted { _private: () })
71             }
72         }
73     }
74
75     fn expand_result_option<T>(&mut self, res: ExpandResult<Option<T>>) -> Result<T, ErrorEmitted> {
76         match (res.value, res.err) {
77             (None, Some(err)) => {
78                 self.emit(err);
79                 Err(ErrorEmitted { _private: () })
80             }
81             (Some(value), opt_err) => {
82                 if let Some(err) = opt_err {
83                     self.emit(err);
84                 }
85                 Ok(value)
86             }
87             (None, None) => unreachable!("`ExpandResult` without value or error"),
88         }
89     }
90 }
91
92 impl ErrorSink for &'_ mut dyn FnMut(ExpandError) {
93     fn emit(&mut self, err: ExpandError) {
94         self(err);
95     }
96 }
97
98 pub fn expand_eager_macro(
99     db: &dyn AstDatabase,
100     krate: CrateId,
101     macro_call: InFile<ast::MacroCall>,
102     def: MacroDefId,
103     resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
104     diagnostic_sink: &mut dyn FnMut(ExpandError),
105 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
106     let hygiene = Hygiene::new(db, macro_call.file_id);
107     let parsed_args = macro_call
108         .value
109         .token_tree()
110         .map(|tt| mbe::syntax_node_to_token_tree(tt.syntax()).0)
111         .unwrap_or_default();
112
113     let ast_map = db.ast_id_map(macro_call.file_id);
114     let call_id = InFile::new(macro_call.file_id, ast_map.ast_id(&macro_call.value));
115     let expand_to = ExpandTo::from_call_site(&macro_call.value);
116
117     // Note:
118     // When `lazy_expand` is called, its *parent* file must be already exists.
119     // Here we store an eager macro id for the argument expanded subtree here
120     // for that purpose.
121     let arg_id = db.intern_macro_call(MacroCallLoc {
122         def,
123         krate,
124         eager: Some(EagerCallInfo {
125             arg_or_expansion: Arc::new(parsed_args.clone()),
126             included_file: None,
127         }),
128         kind: MacroCallKind::FnLike { ast_id: call_id, expand_to: ExpandTo::Expr },
129     });
130
131     let parsed_args = mbe::token_tree_to_syntax_node(&parsed_args, mbe::TopEntryPoint::Expr).0;
132     let result = match eager_macro_recur(
133         db,
134         &hygiene,
135         InFile::new(arg_id.as_file(), parsed_args.syntax_node()),
136         krate,
137         resolver,
138         diagnostic_sink,
139     ) {
140         Ok(Ok(it)) => it,
141         Ok(Err(err)) => return Ok(Err(err)),
142         Err(err) => return Err(err),
143     };
144     let subtree = to_subtree(&result);
145
146     if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
147         let res = eager.expand(db, arg_id, &subtree);
148         if let Some(err) = res.err {
149             diagnostic_sink(err.into());
150         }
151
152         let loc = MacroCallLoc {
153             def,
154             krate,
155             eager: Some(EagerCallInfo {
156                 arg_or_expansion: Arc::new(res.value.subtree),
157                 included_file: res.value.included_file,
158             }),
159             kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
160         };
161
162         Ok(Ok(db.intern_macro_call(loc)))
163     } else {
164         panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
165     }
166 }
167
168 fn to_subtree(node: &SyntaxNode) -> tt::Subtree {
169     let mut subtree = mbe::syntax_node_to_token_tree(node).0;
170     subtree.delimiter = None;
171     subtree
172 }
173
174 fn lazy_expand(
175     db: &dyn AstDatabase,
176     def: &MacroDefId,
177     macro_call: InFile<ast::MacroCall>,
178     krate: CrateId,
179 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
180     let ast_id = db.ast_id_map(macro_call.file_id).ast_id(&macro_call.value);
181
182     let expand_to = ExpandTo::from_call_site(&macro_call.value);
183     let id = def.as_lazy_macro(
184         db,
185         krate,
186         MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), expand_to },
187     );
188
189     let err = db.macro_expand_error(id);
190     let value = db.parse_or_expand(id.as_file()).map(|node| InFile::new(id.as_file(), node));
191
192     ExpandResult { value, err }
193 }
194
195 fn eager_macro_recur(
196     db: &dyn AstDatabase,
197     hygiene: &Hygiene,
198     curr: InFile<SyntaxNode>,
199     krate: CrateId,
200     macro_resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
201     mut diagnostic_sink: &mut dyn FnMut(ExpandError),
202 ) -> Result<Result<SyntaxNode, ErrorEmitted>, UnresolvedMacro> {
203     let original = curr.value.clone_for_update();
204
205     let children = original.descendants().filter_map(ast::MacroCall::cast);
206     let mut replacements = Vec::new();
207
208     // Collect replacement
209     for child in children {
210         let def = match child.path().and_then(|path| ModPath::from_src(db, path, &hygiene)) {
211             Some(path) => macro_resolver(path.clone()).ok_or_else(|| UnresolvedMacro { path })?,
212             None => {
213                 diagnostic_sink(ExpandError::Other("malformed macro invocation".into()));
214                 continue;
215             }
216         };
217         let insert = match def.kind {
218             MacroDefKind::BuiltInEager(..) => {
219                 let id = match expand_eager_macro(
220                     db,
221                     krate,
222                     curr.with_value(child.clone()),
223                     def,
224                     macro_resolver,
225                     diagnostic_sink,
226                 ) {
227                     Ok(Ok(it)) => it,
228                     Ok(Err(err)) => return Ok(Err(err)),
229                     Err(err) => return Err(err),
230                 };
231                 db.parse_or_expand(id.as_file())
232                     .expect("successful macro expansion should be parseable")
233                     .clone_for_update()
234             }
235             MacroDefKind::Declarative(_)
236             | MacroDefKind::BuiltIn(..)
237             | MacroDefKind::BuiltInAttr(..)
238             | MacroDefKind::BuiltInDerive(..)
239             | MacroDefKind::ProcMacro(..) => {
240                 let res = lazy_expand(db, &def, curr.with_value(child.clone()), krate);
241                 let val = match diagnostic_sink.expand_result_option(res) {
242                     Ok(it) => it,
243                     Err(err) => return Ok(Err(err)),
244                 };
245
246                 // replace macro inside
247                 let hygiene = Hygiene::new(db, val.file_id);
248                 match eager_macro_recur(db, &hygiene, val, krate, macro_resolver, diagnostic_sink) {
249                     Ok(Ok(it)) => it,
250                     Ok(Err(err)) => return Ok(Err(err)),
251                     Err(err) => return Err(err),
252                 }
253             }
254         };
255
256         // check if the whole original syntax is replaced
257         if child.syntax() == &original {
258             return Ok(Ok(insert));
259         }
260
261         replacements.push((child, insert));
262     }
263
264     replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
265     Ok(Ok(original))
266 }