hir_expand/
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>
21use base_db::Crate;
22use span::SyntaxContext;
23use syntax::{AstPtr, Parse, SyntaxElement, SyntaxNode, TextSize, WalkEvent, ted};
24use syntax_bridge::DocCommentDesugarMode;
25use triomphe::Arc;
26
27use crate::{
28    AstId, EagerCallInfo, ExpandError, ExpandResult, ExpandTo, ExpansionSpanMap, InFile,
29    MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
30    ast::{self, AstNode},
31    db::ExpandDatabase,
32    mod_path::ModPath,
33};
34
35pub type EagerCallBackFn<'a> = &'a mut dyn FnMut(
36    InFile<(syntax::AstPtr<ast::MacroCall>, span::FileAstId<ast::MacroCall>)>,
37    MacroCallId,
38);
39
40pub fn expand_eager_macro_input(
41    db: &dyn ExpandDatabase,
42    krate: Crate,
43    macro_call: &ast::MacroCall,
44    ast_id: AstId<ast::MacroCall>,
45    def: MacroDefId,
46    call_site: SyntaxContext,
47    resolver: &dyn Fn(&ModPath) -> Option<MacroDefId>,
48    eager_callback: EagerCallBackFn<'_>,
49) -> ExpandResult<Option<MacroCallId>> {
50    let expand_to = ExpandTo::from_call_site(macro_call);
51
52    // Note:
53    // When `lazy_expand` is called, its *parent* file must already exist.
54    // Here we store an eager macro id for the argument expanded subtree
55    // for that purpose.
56    let loc = MacroCallLoc {
57        def,
58        krate,
59        kind: MacroCallKind::FnLike { ast_id, expand_to: ExpandTo::Expr, eager: None },
60        ctxt: call_site,
61    };
62    let arg_id = db.intern_macro_call(loc);
63    #[allow(deprecated)] // builtin eager macros are never derives
64    let (_, _, span) = db.macro_arg(arg_id);
65    let ExpandResult { value: (arg_exp, arg_exp_map), err: parse_err } =
66        db.parse_macro_expansion(arg_id);
67
68    let mut arg_map = ExpansionSpanMap::empty();
69
70    let ExpandResult { value: expanded_eager_input, err } = {
71        eager_macro_recur(
72            db,
73            &arg_exp_map,
74            &mut arg_map,
75            TextSize::new(0),
76            InFile::new(arg_id.into(), arg_exp.syntax_node()),
77            krate,
78            call_site,
79            resolver,
80            eager_callback,
81        )
82    };
83    let err = parse_err.or(err);
84    if cfg!(debug_assertions) {
85        arg_map.finish();
86    }
87
88    let Some((expanded_eager_input, _mapping)) = expanded_eager_input else {
89        return ExpandResult { value: None, err };
90    };
91
92    let mut subtree = syntax_bridge::syntax_node_to_token_tree(
93        &expanded_eager_input,
94        arg_map,
95        span,
96        DocCommentDesugarMode::Mbe,
97    );
98
99    subtree.top_subtree_delimiter_mut().kind = crate::tt::DelimiterKind::Invisible;
100
101    let loc = MacroCallLoc {
102        def,
103        krate,
104        kind: MacroCallKind::FnLike {
105            ast_id,
106            expand_to,
107            eager: Some(Arc::new(EagerCallInfo {
108                arg: Arc::new(subtree),
109                arg_id,
110                error: err.clone(),
111                span,
112            })),
113        },
114        ctxt: call_site,
115    };
116
117    ExpandResult { value: Some(db.intern_macro_call(loc)), err }
118}
119
120fn lazy_expand(
121    db: &dyn ExpandDatabase,
122    def: &MacroDefId,
123    macro_call: &ast::MacroCall,
124    ast_id: AstId<ast::MacroCall>,
125    krate: Crate,
126    call_site: SyntaxContext,
127    eager_callback: EagerCallBackFn<'_>,
128) -> ExpandResult<(InFile<Parse<SyntaxNode>>, Arc<ExpansionSpanMap>)> {
129    let expand_to = ExpandTo::from_call_site(macro_call);
130    let id = def.make_call(
131        db,
132        krate,
133        MacroCallKind::FnLike { ast_id, expand_to, eager: None },
134        call_site,
135    );
136    eager_callback(ast_id.map(|ast_id| (AstPtr::new(macro_call), ast_id)), id);
137
138    db.parse_macro_expansion(id).map(|parse| (InFile::new(id.into(), parse.0), parse.1))
139}
140
141fn eager_macro_recur(
142    db: &dyn ExpandDatabase,
143    span_map: &ExpansionSpanMap,
144    expanded_map: &mut ExpansionSpanMap,
145    mut offset: TextSize,
146    curr: InFile<SyntaxNode>,
147    krate: Crate,
148    call_site: SyntaxContext,
149    macro_resolver: &dyn Fn(&ModPath) -> Option<MacroDefId>,
150    eager_callback: EagerCallBackFn<'_>,
151) -> ExpandResult<Option<(SyntaxNode, TextSize)>> {
152    let original = curr.value.clone_for_update();
153
154    let mut replacements = Vec::new();
155
156    // FIXME: We only report a single error inside of eager expansions
157    let mut error = None;
158    let mut children = original.preorder_with_tokens();
159
160    // Collect replacement
161    while let Some(child) = children.next() {
162        let call = match child {
163            WalkEvent::Enter(SyntaxElement::Node(child)) => match ast::MacroCall::cast(child) {
164                Some(it) => {
165                    children.skip_subtree();
166                    it
167                }
168                _ => continue,
169            },
170            WalkEvent::Enter(_) => continue,
171            WalkEvent::Leave(child) => {
172                if let SyntaxElement::Token(t) = child {
173                    let start = t.text_range().start();
174                    offset += t.text_range().len();
175                    expanded_map.push(offset, span_map.span_at(start));
176                }
177                continue;
178            }
179        };
180
181        let def = match call.path().and_then(|path| {
182            ModPath::from_src(db, path, &mut |range| span_map.span_at(range.start()).ctx)
183        }) {
184            Some(path) => match macro_resolver(&path) {
185                Some(def) => def,
186                None => {
187                    let edition = krate.data(db).edition;
188                    error = Some(ExpandError::other(
189                        span_map.span_at(call.syntax().text_range().start()),
190                        format!("unresolved macro {}", path.display(db, edition)),
191                    ));
192                    offset += call.syntax().text_range().len();
193                    continue;
194                }
195            },
196            None => {
197                error = Some(ExpandError::other(
198                    span_map.span_at(call.syntax().text_range().start()),
199                    "malformed macro invocation",
200                ));
201                offset += call.syntax().text_range().len();
202                continue;
203            }
204        };
205        let ast_id = db.ast_id_map(curr.file_id).ast_id(&call);
206        let ExpandResult { value, err } = match def.kind {
207            MacroDefKind::BuiltInEager(..) => {
208                let ExpandResult { value, err } = expand_eager_macro_input(
209                    db,
210                    krate,
211                    &call,
212                    curr.with_value(ast_id),
213                    def,
214                    call_site,
215                    macro_resolver,
216                    eager_callback,
217                );
218                match value {
219                    Some(call_id) => {
220                        eager_callback(
221                            curr.with_value(ast_id).map(|ast_id| (AstPtr::new(&call), ast_id)),
222                            call_id,
223                        );
224                        let ExpandResult { value: (parse, map), err: err2 } =
225                            db.parse_macro_expansion(call_id);
226
227                        map.iter().for_each(|(o, span)| expanded_map.push(o + offset, span));
228
229                        let syntax_node = parse.syntax_node();
230                        ExpandResult {
231                            value: Some((
232                                syntax_node.clone_for_update(),
233                                offset + syntax_node.text_range().len(),
234                            )),
235                            err: err.or(err2),
236                        }
237                    }
238                    None => ExpandResult { value: None, err },
239                }
240            }
241            MacroDefKind::Declarative(_)
242            | MacroDefKind::BuiltIn(..)
243            | MacroDefKind::BuiltInAttr(..)
244            | MacroDefKind::BuiltInDerive(..)
245            | MacroDefKind::ProcMacro(..) => {
246                let ExpandResult { value: (parse, tm), err } = lazy_expand(
247                    db,
248                    &def,
249                    &call,
250                    curr.with_value(ast_id),
251                    krate,
252                    call_site,
253                    eager_callback,
254                );
255
256                // replace macro inside
257                let ExpandResult { value, err: error } = eager_macro_recur(
258                    db,
259                    &tm,
260                    expanded_map,
261                    offset,
262                    // FIXME: We discard parse errors here
263                    parse.as_ref().map(|it| it.syntax_node()),
264                    krate,
265                    call_site,
266                    macro_resolver,
267                    eager_callback,
268                );
269                let err = err.or(error);
270
271                ExpandResult { value, err }
272            }
273        };
274        if err.is_some() {
275            error = err;
276        }
277        // check if the whole original syntax is replaced
278        if call.syntax() == &original {
279            return ExpandResult { value, err: error };
280        }
281
282        match value {
283            Some((insert, new_offset)) => {
284                replacements.push((call, insert));
285                offset = new_offset;
286            }
287            None => offset += call.syntax().text_range().len(),
288        }
289    }
290
291    replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
292    ExpandResult { value: Some((original, offset)), err: error }
293}