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