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
25 EagerCallInfo, InFile, MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
29 use mbe::ExpandResult;
30 use parser::FragmentKind;
32 use syntax::{ted, SyntaxNode};
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::ast_to_token_tree(¯o_call.value.token_tree()?).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));
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
121 let arg_id = db.intern_macro(MacroCallLoc {
124 eager: Some(EagerCallInfo {
125 arg_or_expansion: Arc::new(parsed_args.clone()),
128 kind: MacroCallKind::FnLike { ast_id: call_id, fragment: FragmentKind::Expr },
130 let arg_file_id: MacroCallId = arg_id.into();
133 diagnostic_sink.result(mbe::token_tree_to_syntax_node(&parsed_args, FragmentKind::Expr))?.0;
134 let result = eager_macro_recur(
136 InFile::new(arg_file_id.as_file(), parsed_args.syntax_node()),
142 diagnostic_sink.option(to_subtree(&result), || err("failed to parse macro result"))?;
144 if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
145 let res = eager.expand(db, arg_id, &subtree);
147 let expanded = diagnostic_sink.expand_result_option(res)?;
148 let loc = MacroCallLoc {
151 eager: Some(EagerCallInfo {
152 arg_or_expansion: Arc::new(expanded.subtree),
153 included_file: expanded.included_file,
155 kind: MacroCallKind::FnLike { ast_id: call_id, fragment: expanded.fragment },
158 Ok(db.intern_macro(loc))
160 panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
164 fn to_subtree(node: &SyntaxNode) -> Option<tt::Subtree> {
165 let mut subtree = mbe::syntax_node_to_token_tree(node).0;
166 subtree.delimiter = None;
171 db: &dyn AstDatabase,
173 macro_call: InFile<ast::MacroCall>,
175 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
176 let ast_id = db.ast_id_map(macro_call.file_id).ast_id(¯o_call.value);
178 let fragment = crate::to_fragment_kind(¯o_call.value);
179 let id: MacroCallId = def
183 MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), fragment },
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
208 .option_with(|| macro_resolver(child.path()?), || err("failed to resolve macro"))?;
209 let insert = match def.kind {
210 MacroDefKind::BuiltInEager(..) => {
211 let id: MacroCallId = expand_eager_macro(
214 curr.with_value(child.clone()),
220 db.parse_or_expand(id.as_file())
221 .expect("successful macro expansion should be parseable")
224 MacroDefKind::Declarative(_)
225 | MacroDefKind::BuiltIn(..)
226 | MacroDefKind::BuiltInDerive(..)
227 | MacroDefKind::ProcMacro(..) => {
228 let res = lazy_expand(db, &def, curr.with_value(child.clone()), krate);
229 let val = diagnostic_sink.expand_result_option(res)?;
231 // replace macro inside
232 eager_macro_recur(db, val, krate, macro_resolver, diagnostic_sink)?
236 // check if the whole original syntax is replaced
237 if child.syntax() == &original {
241 replacements.push((child, insert));
244 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));