]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/eager.rs
clippy::redundant_clone fixes
[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
117     // Note:
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
120     // for that purpose.
121     let arg_id = db.intern_macro(MacroCallLoc {
122         def,
123         krate,
124         eager: Some(EagerCallInfo {
125             arg_or_expansion: Arc::new(parsed_args.clone()),
126             included_file: None,
127         }),
128         kind: MacroCallKind::FnLike { ast_id: call_id, fragment: FragmentKind::Expr },
129     });
130     let arg_file_id: MacroCallId = arg_id.into();
131
132     let parsed_args =
133         diagnostic_sink.result(mbe::token_tree_to_syntax_node(&parsed_args, FragmentKind::Expr))?.0;
134     let result = eager_macro_recur(
135         db,
136         InFile::new(arg_file_id.as_file(), parsed_args.syntax_node()),
137         krate,
138         resolver,
139         diagnostic_sink,
140     )?;
141     let subtree =
142         diagnostic_sink.option(to_subtree(&result), || err("failed to parse macro result"))?;
143
144     if let MacroDefKind::BuiltInEager(eager, _) = def.kind {
145         let res = eager.expand(db, arg_id, &subtree);
146
147         let expanded = diagnostic_sink.expand_result_option(res)?;
148         let loc = MacroCallLoc {
149             def,
150             krate,
151             eager: Some(EagerCallInfo {
152                 arg_or_expansion: Arc::new(expanded.subtree),
153                 included_file: expanded.included_file,
154             }),
155             kind: MacroCallKind::FnLike { ast_id: call_id, fragment: expanded.fragment },
156         };
157
158         Ok(db.intern_macro(loc))
159     } else {
160         panic!("called `expand_eager_macro` on non-eager macro def {:?}", def);
161     }
162 }
163
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;
167     Some(subtree)
168 }
169
170 fn lazy_expand(
171     db: &dyn AstDatabase,
172     def: &MacroDefId,
173     macro_call: InFile<ast::MacroCall>,
174     krate: CrateId,
175 ) -> ExpandResult<Option<InFile<SyntaxNode>>> {
176     let ast_id = db.ast_id_map(macro_call.file_id).ast_id(&macro_call.value);
177
178     let fragment = crate::to_fragment_kind(&macro_call.value);
179     let id: MacroCallId = def
180         .as_lazy_macro(
181             db,
182             krate,
183             MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), fragment },
184         )
185         .into();
186
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));
189
190     ExpandResult { value, err }
191 }
192
193 fn eager_macro_recur(
194     db: &dyn AstDatabase,
195     curr: InFile<SyntaxNode>,
196     krate: CrateId,
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();
201
202     let children = original.descendants().filter_map(ast::MacroCall::cast);
203     let mut replacements = Vec::new();
204
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(
212                     db,
213                     krate,
214                     curr.with_value(child.clone()),
215                     def,
216                     macro_resolver,
217                     diagnostic_sink,
218                 )?
219                 .into();
220                 db.parse_or_expand(id.as_file())
221                     .expect("successful macro expansion should be parseable")
222                     .clone_for_update()
223             }
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)?;
230
231                 // replace macro inside
232                 eager_macro_recur(db, val, krate, macro_resolver, diagnostic_sink)?
233             }
234         };
235
236         // check if the whole original syntax is replaced
237         if child.syntax() == &original {
238             return Ok(insert);
239         }
240
241         replacements.push((child, insert));
242     }
243
244     replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
245     Ok(original)
246 }