]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/db.rs
5c769c1bf2c44605855c5aca7774552263e3f66b
[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, HirFileId, HirFileIdRepr, MacroCallId, MacroCallLoc, MacroDefId,
17     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: MacroCallId,
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) -> MacroCallId;
105
106     /// Lowers syntactic macro call to a token tree representation.
107     #[salsa::transparent]
108     fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
109     /// Extracts syntax node, corresponding to a macro call. That's a firewall
110     /// query, only typing in the macro call itself changes the returned
111     /// subtree.
112     fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
113     /// Gets the expander for this macro. This compiles declarative macros, and
114     /// just fetches procedural ones.
115     fn macro_def(&self, id: MacroDefId) -> Option<Arc<TokenExpander>>;
116
117     /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
118     fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
119     /// Special case of the previous query for procedural macros. We can't LRU
120     /// proc macros, since they are not deterministic in general, and
121     /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
122     /// heroically debugged this once!
123     fn expand_proc_macro(&self, call: MacroCallId) -> Result<tt::Subtree, mbe::ExpandError>;
124     /// Firewall query that returns the error from the `macro_expand` query.
125     fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
126
127     fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
128 }
129
130 /// This expands the given macro call, but with different arguments. This is
131 /// used for completion, where we want to see what 'would happen' if we insert a
132 /// token. The `token_to_map` mapped down into the expansion, with the mapped
133 /// token returned.
134 pub fn expand_hypothetical(
135     db: &dyn AstDatabase,
136     actual_macro_call: MacroCallId,
137     hypothetical_args: &ast::TokenTree,
138     token_to_map: SyntaxToken,
139 ) -> Option<(SyntaxNode, SyntaxToken)> {
140     let (tt, tmap_1) = mbe::syntax_node_to_token_tree(hypothetical_args.syntax());
141     let range =
142         token_to_map.text_range().checked_sub(hypothetical_args.syntax().text_range().start())?;
143     let token_id = tmap_1.token_by_range(range)?;
144
145     let macro_def = {
146         let loc: MacroCallLoc = db.lookup_intern_macro(actual_macro_call);
147         db.macro_def(loc.def)?
148     };
149
150     let hypothetical_expansion = macro_def.expand(db, actual_macro_call, &tt);
151
152     let fragment_kind = macro_fragment_kind(db, actual_macro_call);
153
154     let (node, tmap_2) =
155         mbe::token_tree_to_syntax_node(&hypothetical_expansion.value, fragment_kind).ok()?;
156
157     let token_id = macro_def.map_id_down(token_id);
158     let range = tmap_2.range_by_token(token_id)?.by_kind(token_to_map.kind())?;
159     let token = node.syntax_node().covering_element(range).into_token()?;
160     Some((node.syntax_node(), token))
161 }
162
163 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
164     let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
165     Arc::new(map)
166 }
167
168 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
169     match file_id.0 {
170         HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
171         HirFileIdRepr::MacroFile(macro_file) => {
172             db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
173         }
174     }
175 }
176
177 fn parse_macro_expansion(
178     db: &dyn AstDatabase,
179     macro_file: MacroFile,
180 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
181     let _p = profile::span("parse_macro_expansion");
182     let result = db.macro_expand(macro_file.macro_call_id);
183
184     if let Some(err) = &result.err {
185         // Note:
186         // The final goal we would like to make all parse_macro success,
187         // such that the following log will not call anyway.
188         let loc: MacroCallLoc = db.lookup_intern_macro(macro_file.macro_call_id);
189         let node = loc.kind.node(db);
190
191         // collect parent information for warning log
192         let parents =
193             std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
194                 .map(|n| format!("{:#}", n.value))
195                 .collect::<Vec<_>>()
196                 .join("\n");
197
198         log::warn!(
199             "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
200             err,
201             node.value,
202             parents
203         );
204     }
205     let tt = match result.value {
206         Some(tt) => tt,
207         None => return ExpandResult { value: None, err: result.err },
208     };
209
210     let fragment_kind = macro_fragment_kind(db, macro_file.macro_call_id);
211
212     log::debug!("expanded = {}", tt.as_debug_string());
213     log::debug!("kind = {:?}", fragment_kind);
214
215     let (parse, rev_token_map) = match mbe::token_tree_to_syntax_node(&tt, fragment_kind) {
216         Ok(it) => it,
217         Err(err) => {
218             log::debug!(
219                 "failed to parse expanstion to {:?} = {}",
220                 fragment_kind,
221                 tt.as_debug_string()
222             );
223             return ExpandResult::only_err(err);
224         }
225     };
226
227     match result.err {
228         Some(err) => {
229             // Safety check for recursive identity macro.
230             let node = parse.syntax_node();
231             let file: HirFileId = macro_file.into();
232             let call_node = match file.call_node(db) {
233                 Some(it) => it,
234                 None => {
235                     return ExpandResult::only_err(err);
236                 }
237             };
238             if is_self_replicating(&node, &call_node.value) {
239                 return ExpandResult::only_err(err);
240             } else {
241                 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
242             }
243         }
244         None => {
245             log::debug!("parse = {:?}", parse.syntax_node().kind());
246             ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
247         }
248     }
249 }
250
251 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
252     let arg = db.macro_arg_text(id)?;
253     let (mut tt, tmap) = mbe::syntax_node_to_token_tree(&SyntaxNode::new_root(arg));
254
255     let loc: MacroCallLoc = db.lookup_intern_macro(id);
256     if loc.def.is_proc_macro() {
257         // proc macros expect their inputs without parentheses, MBEs expect it with them included
258         tt.delimiter = None;
259     }
260
261     Some(Arc::new((tt, tmap)))
262 }
263
264 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
265     let loc = db.lookup_intern_macro(id);
266     let arg = loc.kind.arg(db)?;
267     let arg = process_macro_input(db, arg, id);
268     Some(arg.green().into())
269 }
270
271 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<TokenExpander>> {
272     match id.kind {
273         MacroDefKind::Declarative(ast_id) => match ast_id.to_node(db) {
274             ast::Macro::MacroRules(macro_rules) => {
275                 let arg = macro_rules.token_tree()?;
276                 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
277                 let mac = match mbe::MacroRules::parse(&tt) {
278                     Ok(it) => it,
279                     Err(err) => {
280                         let name = macro_rules.name().map(|n| n.to_string()).unwrap_or_default();
281                         log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
282                         return None;
283                     }
284                 };
285                 Some(Arc::new(TokenExpander::MacroRules { mac, def_site_token_map }))
286             }
287             ast::Macro::MacroDef(macro_def) => {
288                 let arg = macro_def.body()?;
289                 let (tt, def_site_token_map) = mbe::ast_to_token_tree(&arg);
290                 let mac = match mbe::MacroDef::parse(&tt) {
291                     Ok(it) => it,
292                     Err(err) => {
293                         let name = macro_def.name().map(|n| n.to_string()).unwrap_or_default();
294                         log::warn!("fail on macro_def parse ({}): {:?} {:#?}", name, err, tt);
295                         return None;
296                     }
297                 };
298                 Some(Arc::new(TokenExpander::MacroDef { mac, def_site_token_map }))
299             }
300         },
301         MacroDefKind::BuiltIn(expander, _) => Some(Arc::new(TokenExpander::Builtin(expander))),
302         MacroDefKind::BuiltInDerive(expander, _) => {
303             Some(Arc::new(TokenExpander::BuiltinDerive(expander)))
304         }
305         MacroDefKind::BuiltInEager(..) => None,
306         MacroDefKind::ProcMacro(expander, ..) => Some(Arc::new(TokenExpander::ProcMacro(expander))),
307     }
308 }
309
310 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
311     macro_expand_with_arg(db, id, None)
312 }
313
314 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
315     db.macro_expand(macro_call).err
316 }
317
318 fn macro_expand_with_arg(
319     db: &dyn AstDatabase,
320     id: MacroCallId,
321     arg: Option<Arc<(tt::Subtree, mbe::TokenMap)>>,
322 ) -> ExpandResult<Option<Arc<tt::Subtree>>> {
323     let _p = profile::span("macro_expand");
324     let loc: MacroCallLoc = db.lookup_intern_macro(id);
325     if let Some(eager) = &loc.eager {
326         if arg.is_some() {
327             return ExpandResult::str_err(
328                 "hypothetical macro expansion not implemented for eager macro".to_owned(),
329             );
330         } else {
331             return ExpandResult {
332                 value: Some(eager.arg_or_expansion.clone()),
333                 // FIXME: There could be errors here!
334                 err: None,
335             };
336         }
337     }
338
339     let macro_arg = match arg.or_else(|| db.macro_arg(id)) {
340         Some(it) => it,
341         None => return ExpandResult::str_err("Fail to args in to tt::TokenTree".into()),
342     };
343
344     let macro_rules = match db.macro_def(loc.def) {
345         Some(it) => it,
346         None => return ExpandResult::str_err("Fail to find macro definition".into()),
347     };
348     let ExpandResult { value: tt, err } = macro_rules.expand(db, id, &macro_arg.0);
349     // Set a hard limit for the expanded tt
350     let count = tt.count();
351     if count > TOKEN_LIMIT {
352         return ExpandResult::str_err(format!(
353             "macro invocation exceeds token limit: produced {} tokens, limit is {}",
354             count, TOKEN_LIMIT,
355         ));
356     }
357
358     ExpandResult { value: Some(Arc::new(tt)), err }
359 }
360
361 fn expand_proc_macro(
362     db: &dyn AstDatabase,
363     id: MacroCallId,
364 ) -> Result<tt::Subtree, mbe::ExpandError> {
365     let loc: MacroCallLoc = db.lookup_intern_macro(id);
366     let macro_arg = match db.macro_arg(id) {
367         Some(it) => it,
368         None => {
369             return Err(
370                 tt::ExpansionError::Unknown("No arguments for proc-macro".to_string()).into()
371             )
372         }
373     };
374
375     let expander = match loc.def.kind {
376         MacroDefKind::ProcMacro(expander, ..) => expander,
377         _ => unreachable!(),
378     };
379
380     expander.expand(db, loc.krate, &macro_arg.0)
381 }
382
383 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
384     if diff(from, to).is_empty() {
385         return true;
386     }
387     if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
388         if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
389             return true;
390         }
391         if let Some(expr) = stmts.expr() {
392             if diff(expr.syntax(), to).is_empty() {
393                 return true;
394             }
395         }
396     }
397     false
398 }
399
400 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
401     Arc::new(HygieneFrame::new(db, file_id))
402 }
403
404 fn macro_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
405     let loc: MacroCallLoc = db.lookup_intern_macro(id);
406     loc.kind.fragment_kind()
407 }