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