1 //! Eager expansion related utils
3 //! Here is a dump of a discussion from Vadim Petrochenkov about Eager Expansion and
4 //! Its name resolution :
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).
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.
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.
20 //! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros>
24 use mbe::ExpandResult;
25 use syntax::{ted, SyntaxNode};
30 EagerCallInfo, ExpandTo, InFile, MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId,
35 pub struct ErrorEmitted {
40 fn emit(&mut self, err: mbe::ExpandError);
45 error: impl FnOnce() -> mbe::ExpandError,
46 ) -> Result<T, ErrorEmitted> {
51 Err(ErrorEmitted { _private: () })
58 opt: impl FnOnce() -> Option<T>,
59 error: impl FnOnce() -> mbe::ExpandError,
60 ) -> Result<T, ErrorEmitted> {
61 self.option(opt(), error)
64 fn result<T>(&mut self, res: Result<T, mbe::ExpandError>) -> Result<T, ErrorEmitted> {
69 Err(ErrorEmitted { _private: () })
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)) => {
78 Err(ErrorEmitted { _private: () })
80 (Some(value), opt_err) => {
81 if let Some(err) = opt_err {
86 (None, None) => unreachable!("`ExpandResult` without value or error"),
91 impl ErrorSink for &'_ mut dyn FnMut(mbe::ExpandError) {
92 fn emit(&mut self, err: mbe::ExpandError) {
97 fn err(msg: impl Into<String>) -> mbe::ExpandError {
98 mbe::ExpandError::Other(msg.into())
101 pub fn expand_eager_macro(
102 db: &dyn AstDatabase,
104 macro_call: InFile<ast::MacroCall>,
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::syntax_node_to_token_tree(macro_call.value.token_tree()?.syntax()).0),
111 || err("malformed macro invocation"),
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(¯o_call.value));
116 let expand_to = ExpandTo::from_call_site(¯o_call.value);
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
122 let arg_id = db.intern_macro_call(MacroCallLoc {
125 eager: Some(EagerCallInfo {
126 arg_or_expansion: Arc::new(parsed_args.clone()),
129 kind: MacroCallKind::FnLike { ast_id: call_id, expand_to: ExpandTo::Expr },
131 let arg_file_id = arg_id;
133 let parsed_args = diagnostic_sink
134 .result(mbe::token_tree_to_syntax_node(&parsed_args, mbe::ParserEntryPoint::Expr))?
136 let result = eager_macro_recur(
138 InFile::new(arg_file_id.as_file(), parsed_args.syntax_node()),
144 diagnostic_sink.option(to_subtree(&result), || err("failed to parse macro result"))?;
146 if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
147 let res = eager.expand(db, arg_id, &subtree);
149 let expanded = diagnostic_sink.expand_result_option(res)?;
150 let loc = MacroCallLoc {
153 eager: Some(EagerCallInfo {
154 arg_or_expansion: Arc::new(expanded.subtree),
155 included_file: expanded.included_file,
157 kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
160 Ok(db.intern_macro_call(loc))
162 panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
166 fn to_subtree(node: &SyntaxNode) -> Option<tt::Subtree> {
167 let mut subtree = mbe::syntax_node_to_token_tree(node).0;
168 subtree.delimiter = None;
173 db: &dyn AstDatabase,
175 macro_call: InFile<ast::MacroCall>,
177 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
178 let ast_id = db.ast_id_map(macro_call.file_id).ast_id(¯o_call.value);
180 let expand_to = ExpandTo::from_call_site(¯o_call.value);
181 let id = def.as_lazy_macro(
184 MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), expand_to },
187 let err = db.macro_expand_error(id);
188 let value = db.parse_or_expand(id.as_file()).map(|node| InFile::new(id.as_file(), node));
190 ExpandResult { value, err }
193 fn eager_macro_recur(
194 db: &dyn AstDatabase,
195 curr: InFile<SyntaxNode>,
197 macro_resolver: &dyn Fn(ast::Path) -> Option<MacroDefId>,
198 mut diagnostic_sink: &mut dyn FnMut(mbe::ExpandError),
199 ) -> Result<SyntaxNode, ErrorEmitted> {
200 let original = curr.value.clone_for_update();
202 let children = original.descendants().filter_map(ast::MacroCall::cast);
203 let mut replacements = Vec::new();
205 // Collect replacement
206 for child in children {
207 let def = diagnostic_sink.option_with(
208 || macro_resolver(child.path()?),
210 let path = child.path().map(|path| format!(" `{}!`", path)).unwrap_or_default();
211 err(format!("failed to resolve macro{}", path))
214 let insert = match def.kind {
215 MacroDefKind::BuiltInEager(..) => {
216 let id = expand_eager_macro(
219 curr.with_value(child.clone()),
224 db.parse_or_expand(id.as_file())
225 .expect("successful macro expansion should be parseable")
228 MacroDefKind::Declarative(_)
229 | MacroDefKind::BuiltIn(..)
230 | MacroDefKind::BuiltInAttr(..)
231 | MacroDefKind::BuiltInDerive(..)
232 | MacroDefKind::ProcMacro(..) => {
233 let res = lazy_expand(db, &def, curr.with_value(child.clone()), krate);
234 let val = diagnostic_sink.expand_result_option(res)?;
236 // replace macro inside
237 eager_macro_recur(db, val, krate, macro_resolver, diagnostic_sink)?
241 // check if the whole original syntax is replaced
242 if child.syntax() == &original {
246 replacements.push((child, insert));
249 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));