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};
32 EagerCallInfo, ExpandTo, InFile, MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId,
33 MacroDefKind, UnresolvedMacro,
37 pub struct ErrorEmitted {
42 fn emit(&mut self, err: mbe::ExpandError);
47 error: impl FnOnce() -> mbe::ExpandError,
48 ) -> Result<T, ErrorEmitted> {
53 Err(ErrorEmitted { _private: () })
60 opt: impl FnOnce() -> Option<T>,
61 error: impl FnOnce() -> mbe::ExpandError,
62 ) -> Result<T, ErrorEmitted> {
63 self.option(opt(), error)
66 fn result<T>(&mut self, res: Result<T, mbe::ExpandError>) -> Result<T, ErrorEmitted> {
71 Err(ErrorEmitted { _private: () })
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)) => {
80 Err(ErrorEmitted { _private: () })
82 (Some(value), opt_err) => {
83 if let Some(err) = opt_err {
88 (None, None) => unreachable!("`ExpandResult` without value or error"),
93 impl ErrorSink for &'_ mut dyn FnMut(mbe::ExpandError) {
94 fn emit(&mut self, err: mbe::ExpandError) {
99 pub fn expand_eager_macro(
100 db: &dyn AstDatabase,
102 macro_call: InFile<ast::MacroCall>,
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
111 .map(|tt| mbe::syntax_node_to_token_tree(tt.syntax()).0)
112 .unwrap_or_default();
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 },
132 let parsed_args = mbe::token_tree_to_syntax_node(&parsed_args, mbe::TopEntryPoint::Expr).0;
133 let result = match eager_macro_recur(
136 InFile::new(arg_id.as_file(), parsed_args.syntax_node()),
142 Ok(Err(err)) => return Ok(Err(err)),
143 Err(err) => return Err(err),
145 let subtree = to_subtree(&result);
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);
153 let loc = MacroCallLoc {
156 eager: Some(EagerCallInfo {
157 arg_or_expansion: Arc::new(res.value.subtree),
158 included_file: res.value.included_file,
160 kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
163 Ok(Ok(db.intern_macro_call(loc)))
165 panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
169 fn to_subtree(node: &SyntaxNode) -> tt::Subtree {
170 let mut subtree = mbe::syntax_node_to_token_tree(node).0;
171 subtree.delimiter = None;
176 db: &dyn AstDatabase,
178 macro_call: InFile<ast::MacroCall>,
180 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
181 let ast_id = db.ast_id_map(macro_call.file_id).ast_id(¯o_call.value);
183 let expand_to = ExpandTo::from_call_site(¯o_call.value);
184 let id = def.as_lazy_macro(
187 MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), expand_to },
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));
193 ExpandResult { value, err }
196 fn eager_macro_recur(
197 db: &dyn AstDatabase,
199 curr: InFile<SyntaxNode>,
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();
206 let children = original.descendants().filter_map(ast::MacroCall::cast);
207 let mut replacements = Vec::new();
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 })?,
214 diagnostic_sink(mbe::ExpandError::Other("malformed macro invocation".into()));
218 let insert = match def.kind {
219 MacroDefKind::BuiltInEager(..) => {
220 let id = match expand_eager_macro(
223 curr.with_value(child.clone()),
229 Ok(Err(err)) => return Ok(Err(err)),
230 Err(err) => return Err(err),
232 db.parse_or_expand(id.as_file())
233 .expect("successful macro expansion should be parseable")
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) {
244 Err(err) => return Ok(Err(err)),
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) {
251 Ok(Err(err)) => return Ok(Err(err)),
252 Err(err) => return Err(err),
257 // check if the whole original syntax is replaced
258 if child.syntax() == &original {
259 return Ok(Ok(insert));
262 replacements.push((child, insert));
265 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));