]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/db.rs
Merge #10767
[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 limit::Limit;
7 use mbe::{syntax_node_to_token_tree, ExpandError, ExpandResult};
8 use rustc_hash::FxHashSet;
9 use syntax::{
10     algo::diff,
11     ast::{self, HasAttrs},
12     AstNode, GreenNode, Parse, SyntaxNode, SyntaxToken, T,
13 };
14
15 use crate::{
16     ast_id_map::AstIdMap, hygiene::HygieneFrame, BuiltinAttrExpander, BuiltinDeriveExpander,
17     BuiltinFnLikeExpander, ExpandTo, HirFileId, HirFileIdRepr, MacroCallId, MacroCallKind,
18     MacroCallLoc, MacroDefId, MacroDefKind, MacroFile, ProcMacroExpander,
19 };
20
21 /// Total limit on the number of tokens produced by any macro invocation.
22 ///
23 /// If an invocation produces more tokens than this limit, it will not be stored in the database and
24 /// an error will be emitted.
25 ///
26 /// Actual max for `analysis-stats .` at some point: 30672.
27 static TOKEN_LIMIT: Limit = Limit::new(524_288);
28
29 #[derive(Debug, Clone, Eq, PartialEq)]
30 pub enum TokenExpander {
31     /// Old-style `macro_rules` or the new macros 2.0
32     DeclarativeMacro { mac: mbe::DeclarativeMacro, def_site_token_map: mbe::TokenMap },
33     /// Stuff like `line!` and `file!`.
34     Builtin(BuiltinFnLikeExpander),
35     /// `global_allocator` and such.
36     BuiltinAttr(BuiltinAttrExpander),
37     /// `derive(Copy)` and such.
38     BuiltinDerive(BuiltinDeriveExpander),
39     /// The thing we love the most here in rust-analyzer -- procedural macros.
40     ProcMacro(ProcMacroExpander),
41 }
42
43 impl TokenExpander {
44     fn expand(
45         &self,
46         db: &dyn AstDatabase,
47         id: MacroCallId,
48         tt: &tt::Subtree,
49     ) -> mbe::ExpandResult<tt::Subtree> {
50         match self {
51             TokenExpander::DeclarativeMacro { mac, .. } => mac.expand(tt),
52             TokenExpander::Builtin(it) => it.expand(db, id, tt),
53             TokenExpander::BuiltinAttr(it) => it.expand(db, id, tt),
54             TokenExpander::BuiltinDerive(it) => it.expand(db, id, tt),
55             TokenExpander::ProcMacro(_) => {
56                 // We store the result in salsa db to prevent non-deterministic behavior in
57                 // some proc-macro implementation
58                 // See #4315 for details
59                 db.expand_proc_macro(id)
60             }
61         }
62     }
63
64     pub(crate) fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
65         match self {
66             TokenExpander::DeclarativeMacro { mac, .. } => mac.map_id_down(id),
67             TokenExpander::Builtin(..)
68             | TokenExpander::BuiltinAttr(..)
69             | TokenExpander::BuiltinDerive(..)
70             | TokenExpander::ProcMacro(..) => id,
71         }
72     }
73
74     pub(crate) fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, mbe::Origin) {
75         match self {
76             TokenExpander::DeclarativeMacro { mac, .. } => mac.map_id_up(id),
77             TokenExpander::Builtin(..)
78             | TokenExpander::BuiltinAttr(..)
79             | TokenExpander::BuiltinDerive(..)
80             | TokenExpander::ProcMacro(..) => (id, mbe::Origin::Call),
81         }
82     }
83 }
84
85 // FIXME: rename to ExpandDatabase
86 #[salsa::query_group(AstDatabaseStorage)]
87 pub trait AstDatabase: SourceDatabase {
88     fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
89
90     /// Main public API -- parses a hir file, not caring whether it's a real
91     /// file or a macro expansion.
92     #[salsa::transparent]
93     fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
94     /// Implementation for the macro case.
95     fn parse_macro_expansion(
96         &self,
97         macro_file: MacroFile,
98     ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>>;
99
100     /// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
101     /// reason why we use salsa at all.
102     ///
103     /// We encode macro definitions into ids of macro calls, this what allows us
104     /// to be incremental.
105     #[salsa::interned]
106     fn intern_macro_call(&self, macro_call: MacroCallLoc) -> MacroCallId;
107
108     /// Lowers syntactic macro call to a token tree representation.
109     #[salsa::transparent]
110     fn macro_arg(&self, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>>;
111     /// Extracts syntax node, corresponding to a macro call. That's a firewall
112     /// query, only typing in the macro call itself changes the returned
113     /// subtree.
114     fn macro_arg_text(&self, id: MacroCallId) -> Option<GreenNode>;
115     /// Gets the expander for this macro. This compiles declarative macros, and
116     /// just fetches procedural ones.
117     fn macro_def(&self, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError>;
118
119     /// Expand macro call to a token tree. This query is LRUed (we keep 128 or so results in memory)
120     fn macro_expand(&self, macro_call: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>>;
121     /// Special case of the previous query for procedural macros. We can't LRU
122     /// proc macros, since they are not deterministic in general, and
123     /// non-determinism breaks salsa in a very, very, very bad way. @edwin0cheng
124     /// heroically debugged this once!
125     fn expand_proc_macro(&self, call: MacroCallId) -> ExpandResult<tt::Subtree>;
126     /// Firewall query that returns the error from the `macro_expand` query.
127     fn macro_expand_error(&self, macro_call: MacroCallId) -> Option<ExpandError>;
128
129     fn hygiene_frame(&self, file_id: HirFileId) -> Arc<HygieneFrame>;
130 }
131
132 /// This expands the given macro call, but with different arguments. This is
133 /// used for completion, where we want to see what 'would happen' if we insert a
134 /// token. The `token_to_map` mapped down into the expansion, with the mapped
135 /// token returned.
136 pub fn expand_speculative(
137     db: &dyn AstDatabase,
138     actual_macro_call: MacroCallId,
139     speculative_args: &SyntaxNode,
140     token_to_map: SyntaxToken,
141 ) -> Option<(SyntaxNode, SyntaxToken)> {
142     let loc = db.lookup_intern_macro_call(actual_macro_call);
143     let macro_def = db.macro_def(loc.def).ok()?;
144     let token_range = token_to_map.text_range();
145
146     // Build the subtree and token mapping for the speculative args
147     let censor = censor_for_macro_input(&loc, &speculative_args);
148     let (mut tt, spec_args_tmap) =
149         mbe::syntax_node_to_token_tree_censored(&speculative_args, &censor);
150
151     let (attr_arg, token_id) = match loc.kind {
152         MacroCallKind::Attr { invoc_attr_index, .. } => {
153             // Attributes may have an input token tree, build the subtree and map for this as well
154             // then try finding a token id for our token if it is inside this input subtree.
155             let item = ast::Item::cast(speculative_args.clone())?;
156             let attr = item.attrs().nth(invoc_attr_index as usize)?;
157             match attr.token_tree() {
158                 Some(token_tree) => {
159                     let (mut tree, map) = syntax_node_to_token_tree(attr.token_tree()?.syntax());
160                     tree.delimiter = None;
161
162                     let shift = mbe::Shift::new(&tt);
163                     shift.shift_all(&mut tree);
164
165                     let token_id = if token_tree.syntax().text_range().contains_range(token_range) {
166                         let attr_input_start =
167                             token_tree.left_delimiter_token()?.text_range().start();
168                         let range = token_range.checked_sub(attr_input_start)?;
169                         let token_id = shift.shift(map.token_by_range(range)?);
170                         Some(token_id)
171                     } else {
172                         None
173                     };
174                     (Some(tree), token_id)
175                 }
176                 _ => (None, None),
177             }
178         }
179         _ => (None, None),
180     };
181     let token_id = match token_id {
182         Some(token_id) => token_id,
183         // token wasn't inside an attribute input so it has to be in the general macro input
184         None => {
185             let range = token_range.checked_sub(speculative_args.text_range().start())?;
186             let token_id = spec_args_tmap.token_by_range(range)?;
187             macro_def.map_id_down(token_id)
188         }
189     };
190
191     // Do the actual expansion, we need to directly expand the proc macro due to the attribute args
192     // Otherwise the expand query will fetch the non speculative attribute args and pass those instead.
193     let speculative_expansion = if let MacroDefKind::ProcMacro(expander, ..) = loc.def.kind {
194         tt.delimiter = None;
195         expander.expand(db, loc.krate, &tt, attr_arg.as_ref())
196     } else {
197         macro_def.expand(db, actual_macro_call, &tt)
198     };
199
200     let expand_to = macro_expand_to(db, actual_macro_call);
201     let (node, rev_tmap) =
202         token_tree_to_syntax_node(&speculative_expansion.value, expand_to).ok()?;
203
204     let range = rev_tmap.first_range_by_token(token_id, token_to_map.kind())?;
205     let token = node.syntax_node().covering_element(range).into_token()?;
206     Some((node.syntax_node(), token))
207 }
208
209 fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
210     let map = db.parse_or_expand(file_id).map(|it| AstIdMap::from_source(&it)).unwrap_or_default();
211     Arc::new(map)
212 }
213
214 fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
215     match file_id.0 {
216         HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
217         HirFileIdRepr::MacroFile(macro_file) => {
218             db.parse_macro_expansion(macro_file).value.map(|(it, _)| it.syntax_node())
219         }
220     }
221 }
222
223 fn parse_macro_expansion(
224     db: &dyn AstDatabase,
225     macro_file: MacroFile,
226 ) -> ExpandResult<Option<(Parse<SyntaxNode>, Arc<mbe::TokenMap>)>> {
227     let _p = profile::span("parse_macro_expansion");
228     let result = db.macro_expand(macro_file.macro_call_id);
229
230     if let Some(err) = &result.err {
231         // Note:
232         // The final goal we would like to make all parse_macro success,
233         // such that the following log will not call anyway.
234         let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
235         let node = loc.kind.to_node(db);
236
237         // collect parent information for warning log
238         let parents =
239             std::iter::successors(loc.kind.file_id().call_node(db), |it| it.file_id.call_node(db))
240                 .map(|n| format!("{:#}", n.value))
241                 .collect::<Vec<_>>()
242                 .join("\n");
243
244         tracing::warn!(
245             "fail on macro_parse: (reason: {:?} macro_call: {:#}) parents: {}",
246             err,
247             node.value,
248             parents
249         );
250     }
251     let tt = match result.value {
252         Some(tt) => tt,
253         None => return ExpandResult { value: None, err: result.err },
254     };
255
256     let expand_to = macro_expand_to(db, macro_file.macro_call_id);
257
258     tracing::debug!("expanded = {}", tt.as_debug_string());
259     tracing::debug!("kind = {:?}", expand_to);
260
261     let (parse, rev_token_map) = match token_tree_to_syntax_node(&tt, expand_to) {
262         Ok(it) => it,
263         Err(err) => {
264             tracing::debug!(
265                 "failed to parse expansion to {:?} = {}",
266                 expand_to,
267                 tt.as_debug_string()
268             );
269             return ExpandResult::only_err(err);
270         }
271     };
272
273     match result.err {
274         Some(err) => {
275             // Safety check for recursive identity macro.
276             let node = parse.syntax_node();
277             let file: HirFileId = macro_file.into();
278             let call_node = match file.call_node(db) {
279                 Some(it) => it,
280                 None => {
281                     return ExpandResult::only_err(err);
282                 }
283             };
284             if is_self_replicating(&node, &call_node.value) {
285                 ExpandResult::only_err(err)
286             } else {
287                 ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: Some(err) }
288             }
289         }
290         None => {
291             tracing::debug!("parse = {:?}", parse.syntax_node().kind());
292             ExpandResult { value: Some((parse, Arc::new(rev_token_map))), err: None }
293         }
294     }
295 }
296
297 fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<(tt::Subtree, mbe::TokenMap)>> {
298     let arg = db.macro_arg_text(id)?;
299     let loc = db.lookup_intern_macro_call(id);
300
301     let node = SyntaxNode::new_root(arg);
302     let censor = censor_for_macro_input(&loc, &node);
303     let (mut tt, tmap) = mbe::syntax_node_to_token_tree_censored(&node, &censor);
304
305     if loc.def.is_proc_macro() {
306         // proc macros expect their inputs without parentheses, MBEs expect it with them included
307         tt.delimiter = None;
308     }
309
310     Some(Arc::new((tt, tmap)))
311 }
312
313 fn censor_for_macro_input(loc: &MacroCallLoc, node: &SyntaxNode) -> FxHashSet<SyntaxNode> {
314     (|| {
315         let censor = match loc.kind {
316             MacroCallKind::FnLike { .. } => return None,
317             MacroCallKind::Derive { derive_attr_index, .. } => {
318                 cov_mark::hit!(derive_censoring);
319                 ast::Item::cast(node.clone())?
320                     .attrs()
321                     .take(derive_attr_index as usize + 1)
322                     .filter(|attr| attr.simple_name().as_deref() == Some("derive"))
323                     .map(|it| it.syntax().clone())
324                     .collect()
325             }
326             MacroCallKind::Attr { invoc_attr_index, .. } => {
327                 cov_mark::hit!(attribute_macro_attr_censoring);
328                 ast::Item::cast(node.clone())?
329                     .attrs()
330                     .nth(invoc_attr_index as usize)
331                     .map(|attr| attr.syntax().clone())
332                     .into_iter()
333                     .collect()
334             }
335         };
336         Some(censor)
337     })()
338     .unwrap_or_default()
339 }
340
341 fn macro_arg_text(db: &dyn AstDatabase, id: MacroCallId) -> Option<GreenNode> {
342     let loc = db.lookup_intern_macro_call(id);
343     let arg = loc.kind.arg(db)?;
344     if matches!(loc.kind, MacroCallKind::FnLike { .. }) {
345         let first = arg.first_child_or_token().map_or(T![.], |it| it.kind());
346         let last = arg.last_child_or_token().map_or(T![.], |it| it.kind());
347         let well_formed_tt =
348             matches!((first, last), (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']));
349         if !well_formed_tt {
350             // Don't expand malformed (unbalanced) macro invocations. This is
351             // less than ideal, but trying to expand unbalanced  macro calls
352             // sometimes produces pathological, deeply nested code which breaks
353             // all kinds of things.
354             //
355             // Some day, we'll have explicit recursion counters for all
356             // recursive things, at which point this code might be removed.
357             cov_mark::hit!(issue9358_bad_macro_stack_overflow);
358             return None;
359         }
360     }
361     Some(arg.green().into())
362 }
363
364 fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Result<Arc<TokenExpander>, mbe::ParseError> {
365     match id.kind {
366         MacroDefKind::Declarative(ast_id) => {
367             let (mac, def_site_token_map) = match ast_id.to_node(db) {
368                 ast::Macro::MacroRules(macro_rules) => {
369                     let arg = macro_rules
370                         .token_tree()
371                         .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
372                     let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
373                     let mac = mbe::DeclarativeMacro::parse_macro_rules(&tt)?;
374                     (mac, def_site_token_map)
375                 }
376                 ast::Macro::MacroDef(macro_def) => {
377                     let arg = macro_def
378                         .body()
379                         .ok_or_else(|| mbe::ParseError::Expected("expected a token tree".into()))?;
380                     let (tt, def_site_token_map) = mbe::syntax_node_to_token_tree(arg.syntax());
381                     let mac = mbe::DeclarativeMacro::parse_macro2(&tt)?;
382                     (mac, def_site_token_map)
383                 }
384             };
385             Ok(Arc::new(TokenExpander::DeclarativeMacro { mac, def_site_token_map }))
386         }
387         MacroDefKind::BuiltIn(expander, _) => Ok(Arc::new(TokenExpander::Builtin(expander))),
388         MacroDefKind::BuiltInAttr(expander, _) => {
389             Ok(Arc::new(TokenExpander::BuiltinAttr(expander)))
390         }
391         MacroDefKind::BuiltInDerive(expander, _) => {
392             Ok(Arc::new(TokenExpander::BuiltinDerive(expander)))
393         }
394         MacroDefKind::BuiltInEager(..) => {
395             // FIXME: Return a random error here just to make the types align.
396             // This obviously should do something real instead.
397             Err(mbe::ParseError::UnexpectedToken("unexpected eager macro".to_string()))
398         }
399         MacroDefKind::ProcMacro(expander, ..) => Ok(Arc::new(TokenExpander::ProcMacro(expander))),
400     }
401 }
402
403 fn macro_expand(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<Option<Arc<tt::Subtree>>> {
404     let _p = profile::span("macro_expand");
405     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
406     if let Some(eager) = &loc.eager {
407         return ExpandResult {
408             value: Some(eager.arg_or_expansion.clone()),
409             // FIXME: There could be errors here!
410             err: None,
411         };
412     }
413
414     let macro_arg = match db.macro_arg(id) {
415         Some(it) => it,
416         None => return ExpandResult::str_err("Failed to lower macro args to token tree".into()),
417     };
418
419     let expander = match db.macro_def(loc.def) {
420         Ok(it) => it,
421         // FIXME: This is weird -- we effectively report macro *definition*
422         // errors lazily, when we try to expand the macro. Instead, they should
423         // be reported at the definition site (when we construct a def map).
424         Err(err) => return ExpandResult::str_err(format!("invalid macro definition: {}", err)),
425     };
426     let ExpandResult { value: tt, err } = expander.expand(db, id, &macro_arg.0);
427     // Set a hard limit for the expanded tt
428     let count = tt.count();
429     // XXX: Make ExpandResult a real error and use .map_err instead?
430     if TOKEN_LIMIT.check(count).is_err() {
431         return ExpandResult::str_err(format!(
432             "macro invocation exceeds token limit: produced {} tokens, limit is {}",
433             count,
434             TOKEN_LIMIT.inner(),
435         ));
436     }
437
438     ExpandResult { value: Some(Arc::new(tt)), err }
439 }
440
441 fn macro_expand_error(db: &dyn AstDatabase, macro_call: MacroCallId) -> Option<ExpandError> {
442     db.macro_expand(macro_call).err
443 }
444
445 fn expand_proc_macro(db: &dyn AstDatabase, id: MacroCallId) -> ExpandResult<tt::Subtree> {
446     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
447     let macro_arg = match db.macro_arg(id) {
448         Some(it) => it,
449         None => return ExpandResult::str_err("No arguments for proc-macro".to_string()),
450     };
451
452     let expander = match loc.def.kind {
453         MacroDefKind::ProcMacro(expander, ..) => expander,
454         _ => unreachable!(),
455     };
456
457     let attr_arg = match &loc.kind {
458         MacroCallKind::Attr { attr_args, .. } => {
459             let mut attr_args = attr_args.0.clone();
460             mbe::Shift::new(&macro_arg.0).shift_all(&mut attr_args);
461             Some(attr_args)
462         }
463         _ => None,
464     };
465
466     expander.expand(db, loc.krate, &macro_arg.0, attr_arg.as_ref())
467 }
468
469 fn is_self_replicating(from: &SyntaxNode, to: &SyntaxNode) -> bool {
470     if diff(from, to).is_empty() {
471         return true;
472     }
473     if let Some(stmts) = ast::MacroStmts::cast(from.clone()) {
474         if stmts.statements().any(|stmt| diff(stmt.syntax(), to).is_empty()) {
475             return true;
476         }
477         if let Some(expr) = stmts.expr() {
478             if diff(expr.syntax(), to).is_empty() {
479                 return true;
480             }
481         }
482     }
483     false
484 }
485
486 fn hygiene_frame(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<HygieneFrame> {
487     Arc::new(HygieneFrame::new(db, file_id))
488 }
489
490 fn macro_expand_to(db: &dyn AstDatabase, id: MacroCallId) -> ExpandTo {
491     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
492     loc.kind.expand_to()
493 }
494
495 fn token_tree_to_syntax_node(
496     tt: &tt::Subtree,
497     expand_to: ExpandTo,
498 ) -> Result<(Parse<SyntaxNode>, mbe::TokenMap), ExpandError> {
499     let entry_point = match expand_to {
500         ExpandTo::Statements => mbe::ParserEntryPoint::Statements,
501         ExpandTo::Items => mbe::ParserEntryPoint::Items,
502         ExpandTo::Pattern => mbe::ParserEntryPoint::Pattern,
503         ExpandTo::Type => mbe::ParserEntryPoint::Type,
504         ExpandTo::Expr => mbe::ParserEntryPoint::Expr,
505     };
506     mbe::token_tree_to_syntax_node(tt, entry_point)
507 }