]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/db.rs
Merge #8801
[rust.git] / crates / hir_expand / src / db.rs
1 //! Defines database & queries for macro expansion.
2
3 use std::sync::Arc;
4
5 use base_db::{salsa, SourceDatabase};
6 use mbe::{ExpandError, ExpandResult};
7 use parser::FragmentKind;
8 use syntax::{
9     algo::diff,
10     ast::{self, NameOwner},
11     AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken,
12 };
13
14 use crate::{
15     ast_id_map::AstIdMap, hygiene::HygieneFrame, input::process_macro_input, BuiltinDeriveExpander,
16     BuiltinFnLikeExpander, EagerCallLoc, EagerMacroId, HirFileId, HirFileIdRepr, LazyMacroId,
17     MacroCallId, MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
18 };
19
20 /// Total limit on the number of tokens produced by any macro invocation.
21 ///
22 /// If an invocation produces more tokens than this limit, it will not be stored in the database and
23 /// an error will be emitted.
24 const TOKEN_LIMIT: usize = 524288;
25
26 #[derive(Debug, Clone, Eq, PartialEq)]
27 pub enum TokenExpander {
28     /// Old-style `macro_rules`.
29     MacroRules { mac: mbe::MacroRules, def_site_token_map: mbe::TokenMap },
30     /// AKA macros 2.0.
31     MacroDef { mac: mbe::MacroDef, def_site_token_map: mbe::TokenMap },
32     /// Stuff like `line!` and `file!`.
33     Builtin(BuiltinFnLikeExpander),
34     /// `derive(Copy)` and such.
35     BuiltinDerive(BuiltinDeriveExpander),
36     /// The thing we love the most here in rust-analyzer -- procedural macros.
37     ProcMacro(ProcMacroExpander),
38 }
39
40 impl TokenExpander {
41     fn expand(
42         &self,
43         db: &dyn AstDatabase,
44         id: LazyMacroId,
45         tt: &tt::Subtree,
46     ) -> mbe::ExpandResult<tt::Subtree> {
47         match self {
48             TokenExpander::MacroRules { mac, .. } => mac.expand(tt),
49             TokenExpander::MacroDef { mac, .. } => mac.expand(tt),
50             TokenExpander::Builtin(it) => it.expand(db, id, tt),
51             // FIXME switch these to ExpandResult as well
52             TokenExpander::BuiltinDerive(it) => it.expand(db, id, tt).into(),
53             TokenExpander::ProcMacro(_) => {
54                 // We store the result in salsa db to prevent non-deterministic behavior in
55                 // some proc-macro implementation
56                 // See #4315 for details
57                 db.expand_proc_macro(id.into()).into()
58             }
59         }
60     }
61
62     pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
63         match self {
64             TokenExpander::MacroRules { mac, .. } => mac.map_id_down(id),
65             TokenExpander::MacroDef { mac, .. } => mac.map_id_down(id),
66             TokenExpander::Builtin(..)
67             | TokenExpander::BuiltinDerive(..)
68             | TokenExpander::ProcMacro(..) => id,
69         }
70     }
71
72     pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
73         match self {
74             TokenExpander::MacroRules { mac, .. } => mac.map_id_up(id),
75             TokenExpander::MacroDef { mac, .. } => mac.map_id_up(id),
76             TokenExpander::Builtin(..)
77             | TokenExpander::BuiltinDerive(..)
78             | TokenExpander::ProcMacro(..) => (id, mbe::Origin::Call),
79         }
80     }
81 }
82
83 // FIXME: rename to ExpandDatabase
84 #[salsa::query_group(AstDatabaseStorage)]
85 pub trait AstDatabase: SourceDatabase {
86     fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
87
88     /// Main public API -- parsis a hir file, not caring whether it's a real
89     /// file or a macro expansion.
90     #[salsa::transparent]
91     fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
92     /// Implementation for the macro case.
93     fn parse_macro_expansion(
94         &self,
95         macro_file: MacroFile,
96     ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
97
98     /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
99     /// reason why we use salsa at all.
100     ///
101     /// We encode macro definitions into ids of macro calls, this what allows us
102     /// to be incremental.
103     #[salsa::interned]
104     fn intern_macro(&self, macro_call: MacroCallLoc) -> LazyMacroId;
105     /// Certain built-in macros are eager (`format!(concat!("file: ", file!(), "{}"")), 92`).
106     /// For them, we actually want to encode the whole token tree as an argument.
107     #[salsa::interned]
108     fn intern_eager_expansion(&self, eager: EagerCallLoc) -> EagerMacroId;
109
110     /// Lowers syntactic macro call to a token tree representation.
111     #[salsa::transparent]
112     fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
113     /// Extracts syntax node, corresponding to a macro call. That's a firewall
114     /// query, only typing in the macro call itself changes the returned
115     /// subtree.
116     fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
117     /// Gets the expander for this macro. This compiles declarative macros, and
118     /// just fetches procedural ones.
119     fn macro_def(&self, id: MacroDefId) -> Option<Arc<TokenExpander>>;
120
121     /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
122     fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
123     /// Special case of the previous query for procedural macros. We can't LRU
124     /// proc macros, since they are not deterministic in general, and
125     /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
126     /// heroically debugged this once!
127     fn expand_proc_macro(&self, call: MacroCallId) -> Result<tt::Subtree, mbe::ExpandError>;
128     /// Firewall query that returns the error from the `macro_expand` query.
129     fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
130
131     fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
132 }
133
134 /// This expands the given macro call, but with different arguments. This is
135 /// used for completion, where we want to see what 'would happen' if we insert a
136 /// token. The `token_to_map` mapped down into the expansion, with the mapped
137 /// token returned.
138 pub fn expand_hypothetical(
139     db: &dyn AstDatabase,
140     actual_macro_call: MacroCallId,
141     hypothetical_args: &ast::TokenTree,
142     token_to_map: SyntaxToken,
143 ) -> Option<(SyntaxNode, SyntaxToken)> {
144     let (tt, tmap_1) = mbe::syntax_node_to_token_tree(hypothetical_args.syntax());
145     let range =
146         token_to_map.text_range().checked_sub(hypothetical_args.syntax().text_range().start())?;
147     let token_id = tmap_1.token_by_range(range)?;
148
149     let lazy_id = match actual_macro_call {
150         MacroCallId::LazyMacro(id) => id,
151         MacroCallId::EagerMacro(_) => return None,
152     };
153
154     let macro_def = {
155         let loc = db.lookup_intern_macro(lazy_id);
156         db.macro_def(loc.def)?
157     };
158
159     let hypothetical_expansion = macro_def.expand(db, lazy_id, &tt);
160
161     let fragment_kind = macro_fragment_kind(db, actual_macro_call);
162
163     let (node, tmap_2) =
164         mbe::token_tree_to_syntax_node(&hypothetical_expansion.value, fragment_kind).ok()?;
165
166     let token_id = macro_def.map_id_down(token_id);
167     let range = tmap_2.range_by_token(token_id)?.by_kind(token_to_map.kind())?;
168     let token = node.syntax_node().covering_element(range).into_token()?;
169     Some((node.syntax_node(), token))
170 }
171
172 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
173     let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
174     Arc::new(map)
175 }
176
177 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
178     match file_id.0 {
179         HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
180         HirFileIdRepr::MacroFile(macro_file) => {
181             db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
182         }
183     }
184 }
185
186 fn parse_macro_expansion(
187     db: &dyn AstDatabase,
188     macro_file: MacroFile,
189 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
190     let _p = profile::span("parse_macro_expansion");
191     let result = db.macro_expand(macro_file.macro_call_id);
192
193     if let Some(err) = &result.err {
194         // Note:
195         // The final goal we would like to make all parse_macro success,
196         // such that the following log will not call anyway.
197         match macro_file.macro_call_id {
198             MacroCallId::LazyMacro(id) => {
199                 let loc: MacroCallLoc = db.lookup_intern_macro(id);
200                 let node = loc.kind.node(db);
201
202                 // collect parent information for warning log
203                 let parents = std::iter::successors(loc.kind.file_id().call_node(db), |it| {
204                     it.file_id.call_node(db)
205                 })
206                 .map(|n| format!("{:#}", n.value))
207                 .collect::<Vec<_>>()
208                 .join("\n");
209
210                 log::warn!(
211                     "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
212                     err,
213                     node.value,
214                     parents
215                 );
216             }
217             _ => {
218                 log::warn!("fail on macro_parse: (reason: {:?})", err);
219             }
220         }
221     }
222     let tt = match result.value {
223         Some(tt) => tt,
224         None => return ExpandResult { value: None, err: result.err },
225     };
226
227     let fragment_kind = macro_fragment_kind(db, macro_file.macro_call_id);
228
229     log::debug!("expanded = {}", tt.as_debug_string());
230     log::debug!("kind = {:?}", fragment_kind);
231
232     let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) {
233         Ok(it) => it,
234         Err(err) => {
235             log::debug!(
236                 "failed to parse expanstion to {:?} = {}",
237                 fragment_kind,
238                 tt.as_debug_string()
239             );
240             return ExpandResult::only_err(err);
241         }
242     };
243
244     match result.err {
245         Some(err) => {
246             // Safety check for recursive identity macro.
247             let node = parse.syntax_node();
248             let file: HirFileId = macro_file.into();
249             let call_node = match file.call_node(db) {
250                 Some(it) => it,
251                 None => {
252                     return ExpandResult::only_err(err);
253                 }
254             };
255             if is_self_replicating(&node, &call_node.value) {
256                 return ExpandResult::only_err(err);
257             } else {
258                 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
259             }
260         }
261         None => {
262             log::debug!("parse = {:?}", parse.syntax_node().kind());
263             ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
264         }
265     }
266 }
267
268 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
269     let arg = db.macro_arg_text(id)?;
270     let (tt, tmap) = mbe::syntax_node_to_token_tree(&SyntaxNode::new_root(arg));
271     Some(Arc::new((tt, tmap)))
272 }
273
274 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
275     let id = match id {
276         MacroCallId::LazyMacro(id) => id,
277         MacroCallId::EagerMacro(_id) => {
278             // FIXME: support macro_arg for eager macro
279             return None;
280         }
281     };
282     let loc = db.lookup_intern_macro(id);
283     let arg = loc.kind.arg(db)?;
284     let arg = process_macro_input(db, arg, id);
285     Some(arg.green().into())
286 }
287
288 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
289     match id.kind {
290         MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
291             ast::Macro::MacroRules(macro_rules) => {
292                 let arg = macro_rules.token_tree()?;
293                 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
294                 let mac = match mbe::MacroRules::parse(&tt) {
295                     Ok(it) => it,
296                     Err(err) => {
297                         let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
298                         log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
299                         return None;
300                     }
301                 };
302                 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
303             }
304             ast::Macro::MacroDef(macro_def) => {
305                 let arg = macro_def.body()?;
306                 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
307                 let mac = match mbe::MacroDef::parse(&tt) {
308                     Ok(it) => it,
309                     Err(err) => {
310                         let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
311                         log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
312                         return None;
313                     }
314                 };
315                 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
316             }
317         },
318         MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
319         MacroDefKind::BuiltInDerive(expander, _) => {
320             Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
321         }
322         MacroDefKind::BuiltInEager(..) => None,
323         MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
324     }
325 }
326
327 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
328     macro_expand_with_arg(db, id, None)
329 }
330
331 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
332     db.macro_expand(macro_call).err
333 }
334
335 fn macro_expand_with_arg(
336     db: &dyn AstDatabase,
337     id: MacroCallId,
338     arg: Option<Arc<(tt::Subtree, mbe::TokenMap)>>,
339 ) -> ExpandResult<Option<Arc<tt::Subtree>>> {
340     let _p = profile::span("macro_expand");
341     let lazy_id = match id {
342         MacroCallId::LazyMacro(id) => id,
343         MacroCallId::EagerMacro(id) => {
344             if arg.is_some() {
345                 return ExpandResult::str_err(
346                     "hypothetical macro expansion not implemented for eager macro".to_owned(),
347                 );
348             } else {
349                 return ExpandResult {
350                     value: Some(db.lookup_intern_eager_expansion(id).subtree),
351                     // FIXME: There could be errors here!
352                     err: None,
353                 };
354             }
355         }
356     };
357
358     let loc = db.lookup_intern_macro(lazy_id);
359     let macro_arg = match arg.or_else(|| db.macro_arg(id)) {
360         Some(it) => it,
361         None => return ExpandResult::str_err("Fail to args in to tt::TokenTree".into()),
362     };
363
364     let macro_rules = match db.macro_def(loc.def) {
365         Some(it) => it,
366         None => return ExpandResult::str_err("Fail to find macro definition".into()),
367     };
368     let ExpandResult { value: tt, err } = macro_rules.expand(db, lazy_id, &macro_arg.0);
369     // Set a hard limit for the expanded tt
370     let count = tt.count();
371     if count > TOKEN_LIMIT {
372         return ExpandResult::str_err(format!(
373             "macro invocation exceeds token limit: produced {} tokens, limit is {}",
374             count, TOKEN_LIMIT,
375         ));
376     }
377
378     ExpandResult { value: Some(Arc::new(tt)), err }
379 }
380
381 fn expand_proc_macro(
382     db: &dyn AstDatabase,
383     id: MacroCallId,
384 ) -> Result<tt::Subtree, mbe::ExpandError> {
385     let lazy_id = match id {
386         MacroCallId::LazyMacro(id) => id,
387         MacroCallId::EagerMacro(_) => unreachable!(),
388     };
389
390     let loc = db.lookup_intern_macro(lazy_id);
391     let macro_arg = match db.macro_arg(id) {
392         Some(it) => it,
393         None => {
394             return Err(
395                 tt::ExpansionError::Unknown("No arguments for proc-macro".to_string()).into()
396             )
397         }
398     };
399
400     let expander = match loc.def.kind {
401         MacroDefKind::ProcMacro(expander, ..) => expander,
402         _ => unreachable!(),
403     };
404
405     expander.expand(db, loc.krate, &macro_arg.0)
406 }
407
408 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
409     if diff(from, to).is_empty() {
410         return true;
411     }
412     if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
413         if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
414             return true;
415         }
416         if let Some(expr) = stmts.expr() {
417             if diff(expr.syntax(), to).is_empty() {
418                 return true;
419             }
420         }
421     }
422     false
423 }
424
425 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
426     Arc::new(HygieneFrame::new(db, file_id))
427 }
428
429 fn macro_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
430     match id {
431         MacroCallId::LazyMacro(id) => {
432             let loc: MacroCallLoc = db.lookup_intern_macro(id);
433             loc.kind.fragment_kind()
434         }
435         MacroCallId::EagerMacro(id) => {
436             let loc: EagerCallLoc = db.lookup_intern_eager_expansion(id);
437             loc.fragment
438         }
439     }
440 }